Define file permissions for the current user

I am looking for a way to determine file permissions for the current user (i.e. the process UID) for POSIX-compatible systems. I do not want to try to open the file - it can become messy with directories and all special files.

I am compiling a list of directories of the specified directory and for each file, reporting a lot of things: file name, size, type (file / directory / other), permissions (you can read, you can write). For size and type, I already have the results of the call stat.

Here is what I came up with:

if ((dirent->st_uid == getuid() && dirent->st_mode & S_IRUSR)
 || (dirent->st_gid == getgid() && dirent->st_mode & S_IRGRP)
 || (dirent->st_mode && S_IROTH)) entry->perm |= PERM_READ;
if ((dirent->st_uid == getuid() && dirent->st_mode & S_IWUSR)
 || (dirent->st_gid == getgid() && dirent->st_mode & S_IWGRP)
 || (dirent->st_mode && S_IWOTH)) entry->perm |= PERM_WRITE;

Do I need to do this, or is there a simple call / macro that will do the same thing? Bonus points for ACL support, although this is not necessary.

+3
2

access(2) , :

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

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

    for (i=0;i<argc;i++) {
            if(access(argv[i], R_OK)) {
                    printf("%s\n", argv[i]);
                    perror("R_OK");
            }
            if(access(argv[i], W_OK)) {
                    printf("%s\n", argv[i]);
                    perror("W_OK");
            }
    }

    return 0;
}

:

$ ./foo ./foo /etc/passwd /etc/shadow
/etc/passwd
W_OK: Permission denied
/etc/shadow
R_OK: Permission denied
/etc/shadow
W_OK: Permission denied

, access(2) TOCTTOU . access(2) , , . , , setfsuid(2) open(2) exec*().

+8
+3

Source: https://habr.com/ru/post/1762636/


All Articles