Search code examples
clinuxpermissionssetuid

Program still able to open root only files after setuid and setgid


I'm writing a program which will operate as different users based on authentication. The program is setuid root and uses PAM authentication before dropping privileges.

I'm using setuid() and setgid() to drop privileges after authentication. But apparently this isn't enough as after calling these my program still seems to have access to open() root only files.

Any suggestions?

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

// Code to drop Priv
int u = 1000, g = 1000;

printf("Starting User %d Group %d\n", (int) getuid(), (int) getgid());
printf("Setting User %d Group %d\n", u, g);
if (setgid(g) || setuid(u)) {
    printf("Could not set uid or gid %d", errno);
    return 0;
}
printf("Have set User %d Group %d\n", (int) getuid(), (int) getgid());

The output of from this is:

Starting User 0 Group 0
Setting User 1000 Group 1000
Have set User 1000 Group 1000

And yet after calling this code my program can still open a file which is root only permissions:

-rw-r----- 1 root   root    505 May  5  2015 rootFile

The code to open is simple enough:

// Later
int fd = open("rootFile", O_RDONLY);
if (fd == -1) {
    // Never happens
} else {
    // Happens
}

Solution

  • Take a look at this article: https://www.securecoding.cert.org/confluence/display/c/POS36-C.+Observe+correct+revocation+order+while+relinquishing+privileges

    Looks like you may have "problem" with suplementary groups. Before setting gid and uid do

    setgroups(0, NULL);
    

    and your code should work.