Recently I had a rather daunting task of writing a bash script to update a remote linux box (Ubuntu) via ftp. The person with the linux box needed to execute the script via a desktop launcher. After diving into various forums and blogs, I came up with this solution. Therefore this HOWTO aims to describe how an unprevilaged user can run executables and scripts with the permissions of the owner of the file.
- First I made sure the script which was to be run as sudo worked ok. This I just tested it by running the script as a superuser to make sure it works. Here is a sample script which I am going to use for this HOWTO.
# Remove all previous downloaded packages from package cache directory
sudo aptitude clean
- Save the script as foo.sh. We then change ownership of the script so that it belongs to root.
$ sudo chown root:root foo.sh
- Various sources claimed that setting the SUID sticky bit on this script would work but it doesn’t. The next step is to make a compiled program to run the script. This compiled executable will then be run by the unprevilaged user. I used C to run the script, here is the c source
setuid( 0 );
- save the c source file as runfoo.c and with a c compiler like gcc, you can compile it like so,
- gcc is going to spew out an executable named bar which is the file the unprevilaged user is going to execute.
- Finally we need to change the ownership and set the SUID to this executable file like so,
$ sudo chown root:root bar
$ sudo chmod 4755 bar
Now the unprevilaged user can execute our bash script without prompt for a password by executing bar which in my case I created a desktop launcher pointing to bar.
$ gcc runfoo.c -o bar