c++ - 无法写入/proc/<pid>/coredump_filter

标签 c++ linux

我的代码(下面)失败了: 11:资源暂时不可用 该代码以 root 身份运行(在 abrt Hook 中),但已向用户设置了 seteuid,该用户正在运行有问题的 pid。 从进程中写入/proc/self/coredump_filter 工作正常。 如何从 abrt Hook 写入 coredump_filter?

void SetDumpFlags(pid_t pid, int dumpflags){
std::string c_filter_name = "/proc/" + std::to_string( pid ) + "/coredump_filter";
int f = open( c_filter_name.c_str(), O_WRONLY );
if (f < 0) {
    fprintf( log, "Couldn't open %s\n", c_filter_name.c_str());
    bail_out(1);
}
int wsz = write( f, &dumpflags, sizeof dumpflags);

if (wsz != sizeof dumpflags){
    fprintf( log, "Couldn't write to %s, %d:%s\n", c_filter_name.c_str(),errno, strerror(errno));
    close( f );
    bail_out(1);
}
close( f );
fprintf( log, "Pid %d, dump filter set to 0x%x\n", pid, dumpflags);
}

最佳答案

我试图用 C 示例重现您的问题 (我会使用 C++11,但我使用的是没有 C++11 的古老上网本,很难在这里获得它并适应该语言)。

我在 open 上得到了一个 EACCESS(我猜你也可能得到它,但 errno 可能会在其他地方被覆盖?)。

似乎 coredump_filter(至少在这个 Linux 3.2 上)开始时拥有者 root 和 seteuid 不会改变它。

我在 setuid 之前尝试了 chown 无济于事。

有效的(如预期的那样)是在您仍然是 root 时打开 fd 并在 seteuid 调用期间保持打开状态。 然后即使在我的 euid 更改后,我也可以再次成功写入文件。

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

#define FLAGS "0x11"
#define FLAGSSZ (sizeof(FLAGS)-1)
int main()
{
    pid_t pid = getpid();
    char buf[sizeof("/proc/XXXXXXXXXXXXXX/coredump_filter")];
    sprintf(buf,"/proc/%ld/coredump_filter",(long)pid);
    int f;
    if(0>(f=open(buf,O_WRONLY|O_TRUNC))) {perror("open");exit(1);}
    if(FLAGSSZ != write(f,FLAGS,FLAGSSZ)){perror("write");exit(1);}
    puts("ok");

    char cat[sizeof("cat /proc/XXXXXXXXXXXXXX/coredump_filter")];
    sprintf(cat,"cat /proc/%ld/coredump_filter", (long)pid);

    system(cat);

    char ls[sizeof("ls -l /proc/XXXXXXXXXXXXXX/coredump_filter")];
    sprintf(ls,"ls -l /proc/%ld/coredump_filter", (long)pid);
    system(ls); //owned by root, not writable by others
    if(0>chown(buf,getuid(),getgid())){perror("chown"); exit(1); }
    //chown returns success but ls -l doesn't agree
    system(ls); //still owned by root

    if(0>seteuid(getuid())){
        perror("seteuid");
        exit(1);
    }
    //can't reopen because of the perms but can still
    //use the old fd if we kept it open
    if(0>lseek(f,SEEK_SET,0)){perror("lseek"); exit(1);}
    #define ALTFLAGS "0x22"
    #define ALTFLAGSSZ (sizeof(ALTFLAGS)-1)
    if(ALTFLAGSSZ != write(f,ALTFLAGS,ALTFLAGSSZ)){perror("write");exit(1);}
    puts("ok");
    system(cat);

}

我用 gcc c.c 编译并用 sudo sh -c 'chown 0 $1 && chmod u+s $1' - a.out 使 a.out setuid root在运行之前。

关于c++ - 无法写入/proc/<pid>/coredump_filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879298/

相关文章:

c++ - 如何从 boost 属性树中读取字段类型

c++ - 搜索给定单词的字符串并返回 bool 值

linux - 如何在使用单行 UNIX 命令创建文件时为其提供权限

c++ - OSX + llvm/libc++ 上的内存损坏/结构重新排序

c++ - 试图理解 C++ 深拷贝

C++ 从文件的一行中搜索某些单词,然后在这些单词之后插入一个单词

c++ - 将系统(char* 命令)的输出加载到变量,c++

linux - 在两个文本文件中找到相似的行?

linux - 将带有时间戳的鼠标坐标和鼠标点击写入文件?

arrays - 带有 bash for 循环的 SSH 命令选项