Today, I’m going to show you how to drop from the root user to an unprivileged user in Python for the purpose of running a Tornado app.
First make a system user for your project to run as. In my example,
I’ll be using projectuser
as the username. Creating this user can be done like so:
1
|
|
Now, in your script that is responsible for starting your Tornado app, you likely have something that probably looks like the following:
1 2 3 4 |
|
What we need to do now is define a user to run as and then drop
privileges using a call to setuid
. We can do this by replacing the above with:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
And voila, your app should now run as the user you defined! Do note that
only the root user can call setuid
. As a result, your script now needs
to be run using sudo
or from an upstart startup script, for example.
One caveat is that you won’t be able to use port numbers below 1024
since you are dropping to an unprivileged user before binding to the
port. I think there’s a way to get around this by replacing
http_server.listen()
with http_server.bind()
, http_server.start()
,
and dropping privileges between those calls, but this remains untested
for now. Alternatively, you could use the respective proxy modules for
Lighttpd or nginx to listen on privileged ports.