简体   繁体   English

Linux:检查进程是否具有对C / C ++中文件的读取访问权限

[英]Linux: check if process has read access to file in C/C++

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

I'm only aware of one way to do this. 我只知道一种方法。 First, find the UID and GID of the process by constructing the path /proc/ + the PID. 首先,通过构造路径/proc/ + PID找到进程的UID和GID。 For example /proc/4261 . 例如/proc/4261 You then stat() that path and get its UID and GID. 然后,您可以stat()该路径并获取其UID和GID。 Then, you stat() the file you want to check for read access and check whether the UID/GID of the process has read permissions: 然后,对要检查读取访问权限的文件stat()进行检查,并检查进程的UID / GID是否具有读取权限:

(It is assumed you already constructed the "/proc/[PID]" path in path_to_proc .) (假定您已经在path_to_proc构造了“ / proc / [PID]”路径。)

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.
}

Note that the code is not perfect. 请注意,代码并不完美。 It does not handle the possibility that the user of the process actually belongs to the file's group without it being the user's primary group. 它不能处理进程用户实际上不是文件的主组而实际上属于该文件组的可能性。 To deal with that, you will need to make use of getgrouplist() (which means you will need to convert the process UID to a string containing the actual username first, and then compare all returned groups to the file's group and if one matches, check for group read access (S_IRGRP).) 为了解决这个问题,您将需要使用getgrouplist()(这意味着您需要先将进程UID转换为包含实际用户名的字符串,然后将所有返回的组与文件的组进行比较,如果有匹配项,检查组读取访问权限(S_IRGRP)。

Open the file. 打开文件。 That's really the only way to know. 那真的是唯一知道的方法。 The answers involving stat(2) require that you write code to interpret the permissions bits and compare them to your active uid/gid and supplemental groups. 涉及stat(2)的答案要求您编写代码来解释权限位,并将它们与活动的uid / gid和补充组进行比较。 And in any case it is incomplete in the general case: LSM hooks like selinux or apparmor can also implement permissions models on files that are not captured by the traditional Unix permissions model. 而且在任何情况下在一般情况下都是不完整的:诸如selinux或apparmor之类的LSM钩子还可以对传统Unix权限模型无法捕获的文件实现权限模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM