Bash – way to make a shell script always run as root

bashshell-scriptsudo

I want to know how to create (if possible) a bash script that runs as root on Debian regardless of the user that executes it, without asking for any kind of authentication.

This file will run all its commands as it were the root user, but only the real root user will be able to read it or write on it.

I need this because I want to run commands like swapoff, swapon, apt, etc… But through another application, and I want it to not ask me any password.

The commands will be fixed (those root commands will have their parameters in the file, not as input), so security implications are not exactly my preoccupation, but I accept explanations as well.

Best Answer

The low-level way to have a program always run under a particular UID, is the setuid bit on the binary file. That's how e.g. sudo and su get their root permissions, even if they're usually started by normal uses. But in general, Unix-like systems don't support setuid scripts, see: Allow setuid on shell scripts

However, what you can do, is to configure sudo or some other such tool to allow the users to run some particular files with the appropriate privileges. E.g., this would allow viceadmin to run /usr/local/bin/sudoswapon with any arguments, and without authentication:

viceadmin ALL = NOPASSWD:/usr/local/bin/sudoswapon

Now, since sudo deals with changing privileges itself, sudoswapon can be a shell script.

You're right to note that the script would need to be careful with how it deals with command line arguments, and that all the gotchas of the shell language will apply. Luckily, sudo filters out most environment variables, at least if the env_reset option is set.

Related Question