2

假设我们有一些 PID 和绝对文件路径 [不是符号链接,只是一个常规文件] - 确定 PID 对该文件具有读取权限的最有效方法是什么?

4

2 回答 2

4

我只知道一种方法可以做到这一点。首先,通过构造路径/proc/+PID,找到进程的UID和GID。例如/proc/4261. 然后您 stat() 该路径并获取其 UID 和 GID。然后,您 stat() 您要检查读取访问权限的文件并检查进程的 UID/GID 是否具有读取权限:

(假设您已经在 中构建了“/proc/[PID]”路径path_to_proc。)

struct stat buf;

// Get UID and GID of the process.
stat(path_to_proc, &buf);
uid_t proc_uid = buf.st_uid;
gid_t proc_gid = buf.st_gid;

// Get UID and GID of the file.
stat(path_to_file_you_want_to_check, &buf);

// If the process owns the file, check if it has read access.
if (proc_uid == buf.st_uid && buf.st_mode & S_IRUSR) {
    // Yes, the process has read access.
}

// Check if the group of the process's UID matches the file's group
// and if so, check for read/write access.
else if (proc_gid == buf.st_gid && buf.st_mode & S_IRGRP) {
    // Yes, the process has read access.
}

// The process's UID is neither the owner of the file nor does its GID
// match the file's.  Check whether the file is world readable.
else if (buf.st_mode & S_IROTH) {
    // Yes, the process has read access.
}

请注意,代码并不完美。它不处理进程的用户实际上属于文件组而不是用户的主要组的可能性。为了解决这个问题,您需要使用 getgrouplist() (这意味着您需要先将进程 UID 转换为包含实际用户名的字符串,然后将所有返回的组与文件的组进行比较,如果匹配,检查组读取访问权限 (S_IRGRP)。)

于 2013-02-13T21:17:49.200 回答
1

打开文件。这真的是唯一知道的方法。涉及的答案stat(2)要求您编写代码来解释权限位并将它们与您的活动 uid/gid 和补充组进行比较。无论如何,它在一般情况下是不完整的:像 selinux 或 apparmor 这样的 LSM 钩子也可以在传统 Unix 权限模型未捕获的文件上实现权限模型。

于 2013-02-13T21:42:54.763 回答