Posted By

kangell on 03/20/08


Tagged

unix os user drop uid pwd super privileges


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wbowers


Drop Privileges


 / Published in: Python
 

  1. # Get the UID the application was started with
  2. # which must have been 'root' if you want this process
  3. # to have 'root' like abilities.
  4. privUID = os.geteuid()
  5. # Get the UID that the application should use for
  6. # most of its processing, 'nobody' is usually
  7. # a good choice.
  8. normalUID = pwd.getpwnam( 'nobody' )[2]
  9.  
  10. def runAsNormal():
  11. """Switch this process to normal privileges, we shouldn't be able to
  12. do anything naughty in this mode."""
  13. os.seteuid( normalUID )
  14. def runAsPrivileged():
  15. """Switch to super user privileges, here we can do anything we want."""
  16. os.seteuid( privUID )
  17.  
  18. # Once program has initialized, drop privileges
  19. runAsNormal()
  20.  
  21. # ... some normal application code...
  22.  
  23. # Do do something that requires super user privileges
  24. try:
  25. runAsPrivileged()
  26. # ... do the stuff we need to be super for
  27. finally:
  28. # Switch out of super mode and back to normal
  29. runAsNormal()

Report this snippet  

You need to login to post a comment.