程序在 setuid 和 setgid 之后仍然能够打开 root only 文件

Program still able to open root only files after setuid and setgid

我正在编写一个程序,它将根据身份验证作为不同的用户运行。该程序是 setuid root 并在删除权限之前使用 PAM 身份验证。

我正在使用 setuid()setgid() 在身份验证后删除权限。但显然这还不够,因为在调用这些之后我的程序似乎仍然可以访问 open() 仅根文件。

有什么建议吗?

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

// Code to drop Priv
int u = 1000, g = 1000;

printf("Starting User %d Group %d\n", (int) getuid(), (int) getgid());
printf("Setting User %d Group %d\n", u, g);
if (setgid(g) || setuid(u)) {
    printf("Could not set uid or gid %d", errno);
    return 0;
}
printf("Have set User %d Group %d\n", (int) getuid(), (int) getgid());

由此产生的输出是:

Starting User 0 Group 0
Setting User 1000 Group 1000
Have set User 1000 Group 1000

然而在调用这段代码后,我的程序仍然可以打开一个只有 root 权限的文件:

-rw-r----- 1 root   root    505 May  5  2015 rootFile

打开代码很简单:

// Later
int fd = open("rootFile", O_RDONLY);
if (fd == -1) {
    // Never happens
} else {
    // Happens
}

看看这篇文章:https://www.securecoding.cert.org/confluence/display/c/POS36-C.+Observe+correct+revocation+order+while+relinquishing+privileges

看起来您可能 "problem" 有补充小组。在设置 gid 和 uid 之前做

setgroups(0, NULL);

你的代码应该可以工作。