Alex Rivera | Logout

Calling a script from a setuid root C program - script does not run as root

Asked 2009-02-17T10:18:36.193
32

I need to run a bash script as root (passwordless sudo or su not viable) and since you cannot setuid a script in Linux, I thought about calling it from an executable and making it setuid:

$ cat wrapper.c
int main(void)
{
        system("/bin/bash ./should_run_as_root.sh");
}
$ gcc -o wrapper wrapper.c
$ sudo chown root wrapper
$ sudo chmod ug+s wrapper
$ ll wrapper
-rwsr-sr-x 1 root users 6667 2009-02-17 11:11 wrapper
$

This works - as in runs the script correctly - but the script runs as the user who executes "./wrapper".

Why? And how to correctly implement this?

Thanks!

Edit
Report

2 Answers

8

Another thing to note here is that the limitation here is from bash and not the *nix system itself. Bash actually make verifications on SUID scripts to only execute them with EUID root. If you take older shells, you will often get what you wanted out of the box. For example, sh doesn't make this kind of verifications:

$ cat wrapper.c
int main(void)
{
            system("/bin/sh -c whoami");
}

$ ls -l wrapper
-rwsr-sr-x 1 root users 8887 Feb 17 14:15 wrapper
$ ./wrapper
root

With bash:

$ cat wrapper.c
int main(void)
{
            system("/bin/bash -c whoami");
}

$ ls -l wrapper
-rwsr-sr-x 1 root users 8887 Feb 17 14:18 wrapper
$ ./wrapper
skinp

Still, Tom's answer is generally the way to go for making a wrapper for SUID root programs

answered 2009-02-17T14:18:32.607
2

The examples are horribly insecure and allows anyone with two bits of knowledge to run any program they want as the setuid user.

Never go through a shell unless you sanitize the environment first, most of the examples shown here are vulnerable to having IFS and PATH set before running it.

answered 2012-01-03T11:36:27.503

Your Answer