Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Python Script as Root (seteuid vs c-wrapper)

I have a quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges.

At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I would have to set the setuid bit on Python itself, which I assume is big no no. From what I can tell, this would also be the case if using sudo, which I really would like to avoid.

At this point, I'm considering just writing a C wrapper the uses seteuid and calls my python script as root, passing the necessary arguments to it.

Is this the correct thing to do or should I be looking at something else?

like image 583
kwl34 Avatar asked Oct 03 '11 18:10

kwl34


2 Answers

sudo does not require setuid bit on Python. You can enable sudo for one command only, no arguments:

 www          ALL=(ALL)       NOPASSWD:  /root/bin/reload-stuff.py ""

This would be secure if your script does not take any arguments, cannot be overridden by www user, and sudo does "env_reset" (the default in most distros).

You can accept arguments, but be very careful with them -- do not take output filenames, make sure you verify all inputs. In this case, remove "" from the end of sudo line.

like image 198
theamk Avatar answered Oct 21 '22 03:10

theamk


The correct thing is called privilege separation: clearly identify minimal set of tasks which have to be done on elevated privileges. Write a separate daemon and an as much limited as possible way of communicating the task to do. Run this daemon as another user with elevated privileges. A bit more work, but also more secure.

EDIT: using a setuid-able wrapper will also satisfy the concept of privilege separation, although I recommend having the web server chrooted and mounting the chrooted file system nosuid (which would defeat that).

like image 23
knitti Avatar answered Oct 21 '22 02:10

knitti