Can i setuid for perl script?

Sumit Rathore picture Sumit Rathore · Feb 6, 2014 · Viewed 9.6k times · Source

I made a perl script to change owner of a file owned by some other user. Script is complete. My administrator save that in /sbin directory and set uid for it using chmod u+s name_of_script. But when i run this script it gives me error that chown operation is not permitted. I made a C program and it works by following same steps. So my question is if setuid is working for perl then i should not get that error because C code did not give me any error. So can i setuid for perl script or i should go with c code.

Don't tell me to ask administrator to change owner each time. Actually in server i have user name staging and i am hosting a joomla site in it. Now when i install some plugin then files related to that plugin are owned by www-data. So that's why i do not want to go to admin each time. Or you can give me some other solution also regarding my problem.

Thanks.

Answer

harmic picture harmic · Feb 6, 2014

Many unix systems (probably most modern ones) ignore the suid bit on interpreter scripts, as it opens up too many security holes.

However, if you are using perl < 5.12.0, you can run perl scripts with setuid set, and they will run as root. How it works is that when the normal perl interpreter runs, and detects that the file you are trying to execute has the setuid bit set, and it then executes a program called suidperl. Suidperl takes care of elevating the user's privileges, and starting up the perl interpreter in a super-secure mode. suidperl is itself running with setuid root.

One of the consequences of this is that taint mode is turned on automatically. Other additional checks are also performed. You will probably see messages like:

Insecure $ENV{PATH} while running setuid at ./foobar.pl line 3.

perlsec provides some good information about securing such scripts.

suidperl is often not installed by default. You may have to install it via a separate package. If it is not installed then you get this message:

Can't do setuid (cannot exec sperl)

Having said all of that - you would be much better off using sudo to execute actions with elevated privileges. It is much more secure as you can specify exactly what is allowed to be executed via the sudoers file.

As of perl 5.12.0, suidperl was dropped. As a result, if you want to run a perl script on perl >= 5.12.0 with setuid set, you would have to write your own C wrapper. Again I recommend sudo as a better alternative.