Question

I have a program to run as root, and during execution this program will do a few things as different uers, so I wanted to use a serial of setuid()s. But, I found that, after setuid(user1), I become user1 and thus don't have the privilege to do setuid(user2).

How can I get back to root so that I can do setuid(user2)?

Thanks.

Was it helpful?

Solution

Use fork, let the child setuid and perform whatever actions that needs to be done as the second user. The root parent waits for the child and continues when the child has finished executing.

childpid = fork();
if (childpid < 0) {
    // fork failed
} 
if (childpid == 0) {
  // Child
  setuid(user1);
  prepareUser1();  // Do some stuff as user1.
  exit(0);         // Done as user1
} else {
  // parent: wait for child to finish
  waitpid(childpid);
}
// Parent continues as root...

OTHER TIPS

You can't, Read the man : setuid

But you can try to chmod your file then you will be able to call setuid(0) to come back as yout first uid

The setuid says the following:

a set-user-ID-root program wishing to temporarily drop root privileges, assume the identity of a non-root user, and then regain root privileges afterwards cannot use setuid(). You can accomplish this with seteuid(2)

Meaning that you cannot use setuid() become root as you are unprivileged user. You have to use seteuid() to become a root user.

Try this sample program to use seteuid and change the privileges.

You cannot. By design, once you drop root privileges, you cannot get it back

man page says:

If the user is root or the program is set-user-ID-root, special care must be taken. The setuid() function checks the effective user ID of the caller and if it is the superuser, all process-related user ID's are set to uid. After this has occurred, it is impossible for the program to regain root privileges

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top