Linux SUID – Cannot Set UID on Shell Scripts

iptableslinuxsuid

Can anyone help me find out what is going on here? I have some rules set up tracking packet counts. When I run the following script as root:

#!/bin/bash
iptables -t mangle -xnvL

I get the output I expect:

//snip
233203 199929802 MARK  //blah blah blah
//snip

However, I want to run this as part of cacti, which runs as apache. Now apache can't run iptables, which is why I have the script. I set it up as SUID root:

-rwsr-sr-x 1 root root   37 May 14 23:06 iptables_packet_report.sh

But then I get this output:

server # sudo -u apache ./iptables_packet_report.sh
iptables v1.4.2: can't initialize iptables table `mangle': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.

Obviously my kernel is fine, and the fact that I'm running it as non-root is messing something up, but I don't understand why. I did double check the SUID with [the demonstration](http://en.wikipedia.org/wiki/Setuid#Demonstration and confirmed it was working.

server # sudo -u apache ./printid
Real UID  = 81
Effective UID = 0
Real GID  = 81
Effective GID = 0

My end goal is to get the output of iptables -t mangle -xnvL while running as apache so I can use cacti to graph it all nicely.

Best Answer

You cannot use SUID root for shell scripts. Only real programs can be SUID root, shell scripts start with "#!" and the interpreter would have to run SUID and that does not work for some reason I didn't know

Take a look at sudo and install it! Edit /etc/sudoerrs, add a line like this:

www-data        ALL=NOPASSWD: /usr/local/sbin/iptables_packet_report.sh

Then just run

sudo /usr/local/sbin/iptables_packet_report.sh

from your code.

It should then not ask for the password, but evaluate the process automatically.

I'm quite sure that your error messages would also happen if you manually su into www-data and run it manually