Socket access to low numbered ports?

Dan Boitnott danslists at fastmail.fm
Sat Mar 20 11:27:38 EST 2004


John Burton wrote:
> Has anyone got any suggestion on the best way to allow my program to
> listen on those socket without runing as root when doing anything else?
> Ideally I want this to be portable so the same program still runs on
> windows.

The standard practice is to make the program setuid, be root just long 
enough to bind to the socket, then change to an unprivileged user (like 
"daemon").  The idea is to run as little code as root as possible.

You can make a program suid root like this:

# chown root.root myprog.py
# chmod a+s myprog.py

And you can change users in Python like this:

----------------
import os
os.setreuid(2, 2)
----------------

UID 2 is normally the daemon user.  If you want to use a different user 
you can refer to the /etc/passwd file.

You may also want to run as the user who spawned the program in the 
first place:

----------------
import os
uid = os.getuid()    # Gets the "real" UID

# Do your socket binding

os.setreuid(uid, uid)
----------------

Hope this helps.

Dan Boitnott
dan at lclinux.org



More information about the Python-list mailing list