Socket access to low numbered ports?

John Burton john.burton at jbmail.com
Sat Mar 20 11:54:06 EST 2004


Dan Boitnott wrote:
 > 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.

Well it does - thanks for that - except that setting the set uid bit on
the script doesn't seem to actually work. This is on gentoo linux.



More information about the Python-list mailing list