关于setuid的问题

Questions about setuid

我在使用 运行 下列 C 程序时遇到问题:

#include<unistd.h>

void main()
{
    if (access("/root/main.c",R_OK)==0)
    {
        printf("/root/main.c can be read\n");
    }
    else
    {
        printf("can't be read\n");
    }
}

当我 运行 以 root 身份执行可执行文件时,我可以获得输出:

/root/main.c can be read

但是当我将可执行文件的权限设置为4755,并且运行它作为普通用户时,我只得到输出:

can't be read

我的协议有错误吗?

access 忽略 setuid/setgid 位。这是设计使然。

man 2 access 在 Linux 上的引用:

The check is done using the calling process's real UID and GID, rather than the effective IDs as is done when actually attempting an operation (e.g., open(2)) on the file. Similarly, for the root user, the check uses the set of permitted capabilities rather than the set of effective capabilities; and for non-root users, the check uses an empty set of capabilities.

This allows set-user-ID programs and capability-endowed programs to easily determine the invoking user's authority. In other words, access() does not answer the "can I read/write/execute this file?" question. It answers a slightly different question: "(assuming I'm a setuid binary) can the user who invoked me read/write/execute this file?", which gives set-user-ID programs the possibility to prevent malicious users from causing them to read files which users shouldn't be able to read.

如果您想知道您的进程是否真的可以打开文件进行读取,只需 open() 它并处理错误(如果有)。 (这也避免了竞争条件。)