C++ – setuid and getuid don’t seem to work

setuid and getuid don’t seem to work… here is a solution to the problem.

setuid and getuid don’t seem to work

I’m writing a Qt application that accesses Linux raw sockets, so I need root privileges to run the program. So I did it :

In my program, it starts like this:

if (getuid() != 0)
{
    fprintf(stderr, "You must be root to run this program. UID = %i\n", getuid());
    exit(-1);
}

Then, I execute “chmod 6777 myProgram” as root.

However, when I try to run it as a normal user, it says:
“You must be root to run this program. UID = 1002”, where 1002 is the user ID I am currently using.

Can anyone post leads?

Thanks

Solution

You confuse getuid() and geteuid(). Man page from getuid():

The getuid() function returns the real user ID of the calling process. The geteuid() function returns the effective user ID of the calling process.

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.

The man pages for Linux are more concise (the previous one is from Mac OS X):

When a normal program is executed, the effective and real user ID of the process are set to the ID of the user executing the file. When a set ID program is executed the real user ID is set to the calling user and the effective user ID corresponds to the set ID bit on the file being executed.

For setuid programs, the file needs to be owned by the user ID for which you want to set setuid, in most cases root.

Related Problems and Solutions