在C / * nix中检查指定用户的文件访问权限

时间:2013-09-10 19:02:59

标签: c linux unix file-permissions freebsd

这是我的问题。我需要从FreeBSD上的C代码中检查特定文件和特定用户的读取权限。我写了一段代码:

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

int main(int argc, char *argv[]){
    int r_ok;

    if(setuid(1002)){
        printf("Cant's set uid\n");
        exit(1); 
    }

    r_ok = access("/tmp/dir", R_OK);
    printf("error: %d: %s\n", errno, strerror(errno));
    printf("%d\n", r_ok);
    return 0;
}

一般情况下它工作正常,但是当我为/ tmp / dir设置权限时:

d---r-x---  2 root  fruit1  512 Sep 10 18:20 /tmp/dir

程序输出

error: 13: Permission denied
-1

使用UID 1002的用户是group1的有效成员:

# groups 1002
orange fruit1

我会很乐意为你提供帮助。

1 个答案:

答案 0 :(得分:1)

setuid()设置进​​程的真实有效用户ID,但修改组访问列表,因为您必须调用setgid(),{{1 }或initgroups()

因此,您的程序将使用已使用的ID 1002以及原始组ID和组运行 访问列表,而不是用户1002的组访问列表。 这就解释了为什么该进程没有对目录的读取权限。

请注意,setgroups()被视为“安全漏洞”,(例如参见access() Security Hole)。 通常最好只是尝试打开文件或目录而不是检查 事先读取权限。

相关问题