seteuid/geteuid: Program always has root id

Chris picture Chris · Apr 5, 2011 · Viewed 8.7k times · Source

I'm currently trying to figure out how the SUID-bit and the corresponding functions seteuid and geteuid work. So I wrote this little program:

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

int main(int argc, char **argv) {

    printf("oldid %d\n", geteuid());
    if(seteuid(0) == -1)
        perror("seteuid faied");
    printf("newid %d\n", geteuid());

    return 0;

}

Compiled it, changed its owner to root and the s-bit for the owner of the file:

[chris@myhost Test]$ ls -l test
-rwsr-xr-x 1 root root 4830 Apr  5 07:56 test

But then the produced output looks like this:

[chris@myhost Test]$ ./test
oldid 0
newid 0

And this is something I do not understand. According to what I have found the first call of geteuid should actually return the userid of the caller of this program (i.e. chris - my ID would be 1000), but the program shows root as the effective user id. Can anyone explain me why this is the case?

Answer

JeremyP picture JeremyP · Apr 5, 2011

From the man page of geteuid() on my Mac (OS X 10.6.7):

The real user ID is that of the user who has invoked the program. As the effective user ID gives the process additional permissions during execution of ``set-user-ID'' mode processes, getuid() is used to determine the real-user-id of the calling process.

Since you have set the suid bit, the effective user id of the program is the file owner (root) from the start of execution.