vitaliy
vitaliy

Reputation: 464

Checking file access permissions for specified user in C / *nix

Here is my problem. I need to check read permissions for specific file and specific user from C code on FreeBSD. I've written a piece of code:

#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;
}

In general it works fine, but when I set permissions for /tmp/dir like this:

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

the program ouputs

error: 13: Permission denied
-1

althou user with UID 1002 is a valid member of group fruit1:

# groups 1002
orange fruit1

I will be greatfull for any help.

Upvotes: 2

Views: 1857

Answers (1)

Martin R
Martin R

Reputation: 539685

setuid() sets the real and effective user ID of the process, but does not modify the group access list, for that you have to call setgid(), initgroups() or setgroups().

So your program runs with the used ID 1002 and with the original group ID and group access list, and not with the group access list of the user 1002. That explains why the process does not have read permission to the directory.

Note that access() is considered a "security hole", (see for example access() Security Hole). It is generally better just to try to open a file or directory instead of checking the read permissions beforehand.

Upvotes: 1

Related Questions