36

How to make a script execute as root, no matter who executes it?

I read about setuid but I'm not sure how to do this.

I'm using Linux, Ubuntu 12.04 LTS.

Deltik
  • 19,971

5 Answers5

36

Be really careful: scripts combined with setuid are dangerous!

First, please have a look on this question/answers, especially on this answer and security warning.

If you still want to execute your script with setuid set, then you can write a short C program as wrapper and set the setuid bit on the compiled binary.

Wrapper example:

int main(void) {        
    setuid(0);
    clearenv();
    system("/absolute/path/to/your/script.sh");
}

Another solution using sudo (mentioned here):

  1. As root, prevent write (and maybe other) access to your script:

    chown root /absolute/path/to/your/script.sh
    chmod 700 /absolute/path/to/your/script.sh
    
  2. Verify that noone except root can replace the script, e.g. by modifying the access rights of the parent folder:

    chown root /absolute/path/to/your/
    chmod 755 /absolute/path/to/your/
    
  3. Modify sudo access rights in /etc/sudoers with visudo:

    ALL    ALL = (root) NOPASSWD: /absolute/path/to/your/script.sh
    

    More details about the settings (e.g. restricting access to specific users or groups) can be found in the sudoers manpage.

Afterwards, all users can run the script as root without password:

sudo /absolute/path/to/your/script.sh

This is similar to using the wrapper/setuid solution above.

speakr
  • 3,957
4

Easiest and safest way is to use SETUID bits in file permissions. that way command permissions will be elevated to file owner permissions.

to prevent script from edition do not set write for everyone bits.

Tadas
  • 41
0

I don't know if this may be useful but, to make the script only run as root, you could use this shebang on the first line of the script:

#!/bin/su root
0

Stumbled across this question when I was searching for a snippet like this:

[ "$(id -u)" != 0 ] && exec sudo "$0"

Adding this to the top of a script will preface it with sudo and ensure it'll always run as root, allowing us to run our script as ./hello.sh. Of course, sudo will still ask for a password, but the accepted answer will help avoid that.

0

Alternatively, to run e.g. wireshark always as root I have put this to /etc/sudoers:

your_username ALL = NOPASSWD: /usr/bin/wireshark

and then made this alias in my .bashrc:

alias wireshark="sudo /usr/bin/wireshark"