Setuid and setgid not working

I'm having a problem with setuid and setgid. I've written this C code:

int main() { setuid(0); setgid(0); system("/path/to/script.sh"); return 0;
}

Compiled it using gcc:

gcc test.c -o test

Then I used chmod +s. In script.sh there's only the id command. Here are the permissions for the test executable:

-rwxr-sr-x 1 root root 8464 mag 15 20:14 test

When I execute the program I get the following output:

uid=1000(user) gid=1000(user) gruppi=1000(user)

Why am I not getting the output of id executed by root?

2 Answers

You can't use setuid and setgid to run a shell script as a different user. It's a security feature, and you can read more about it in the very comprehensive top answer to this UL post.

2

aquote from the MAN page for setuid()

Thus, a set-user-ID-root program wishing to temporarily drop root priv‐ ileges, assume the identity of an unprivileged user, and then regain root privileges afterward cannot use setuid(). You can accomplish this with seteuid(2).

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

 Note: there are cases where setuid() can fail even when the caller is UID 0; it is a grave security error to omit checking for a failure return from setuid().

amongst other things, This means a user cannot become root via this command.

If the posted code had checked the returned value from these commands, the would have seen that the commands failed.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like