Dropping Root Permissions In Python
You won't be able to open a server on port 80 without root privileges, this is a restriction on the OS level. So the only solution is to drop root privileges after you have opened the port.
Here is a possible solution to drop root privileges in Python: Dropping privileges in Python. This is a good solution in general, but you'll also have to add os.setgroups([])
to the function to ensure that the group membership of the root user is not retained.
I copied and cleaned up the code a little bit, and removed logging and the exception handlers so it is left up to you to handle OSError
properly (it will be thrown when the process is not allowed to switch its effective UID or GID):
import os, pwd, grpdef drop_privileges(uid_name='nobody', gid_name='nogroup'): if os.getuid() != 0: # We're not root so, like, whatever dude return # Get the uid/gid from the name running_uid = pwd.getpwnam(uid_name).pw_uid running_gid = grp.getgrnam(gid_name).gr_gid # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(running_gid) os.setuid(running_uid) # Ensure a very conservative umask old_umask = os.umask(077)
I recommend using authbind
to start your Python program, so none of it has to run as root.
It is not a good idea to ask the user to enter his/her user-name and group whenever I need to drop privileges. Here is a slightly modified version of Tamás's code which will drop privileges and switch to the user who initiated the sudo command. I am assuming you are using sudo (if not, use Tamás's code).
#!/usr/bin/env python3import os, pwd, grp#Throws OSError exception (it will be thrown when the process is not allowed#to switch its effective UID or GID):def drop_privileges(): if os.getuid() != 0: # We're not root so, like, whatever dude return # Get the uid/gid from the name user_name = os.getenv("SUDO_USER") pwnam = pwd.getpwnam(user_name) # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(pwnam.pw_gid) os.setuid(pwnam.pw_uid) #Ensure a reasonable umask old_umask = os.umask(0o22)#Test by running...#./drop_privileges#sudo ./drop_privilegesif __name__ == '__main__': print(os.getresuid()) drop_privileges() print(os.getresuid())