user2069958
user2069958

Reputation: 23

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

Assuming we have some PID and absolute file path [not a symlink, just a regular file] - what is the most efficient way to determine that PID has read access to this file?

Upvotes: 2

Views: 3828

Answers (2)

Nikos C.
Nikos C.

Reputation: 51832

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. For example /proc/4261. You then stat() that path and get its UID and 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:

(It is assumed you already constructed the "/proc/[PID]" path in 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.
}

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

Upvotes: 4

Andy Ross
Andy Ross

Reputation: 12033

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

Upvotes: 1

Related Questions