"Operation not allowed" when disabling privileges using setuid () function

Why do these simple programs using os.setuid () / gid () fail? I am written in python, but I think this is not a relative language problem (in the end, the posix system call is still):

import os, pwd

if os.getenv("SUDO_UID") and os.getenv("SUDO_GID"):
  orig_uid=int(os.getenv("SUDO_UID"))
  orig_gid=int(os.getenv("SUDO_GID"))
else:
  pw = pwd.getpwnam("nobody")
  orig_uid = pw.pw_uid
  orig_gid = pw.pw_gid

print os.getuid(), os.getgid(), os.geteuid(), os.getegid(), orig_uid, orig_gid

os.setgid(orig_gid)
os.setuid(orig_uid)

It returns this exception:

$ sudo python provgid.py 
0 0 0 0 1000 1000
Traceback (most recent call last):
  File "provgid.py", line 15, in <module>
    os.setgid(orig_gid)
OSError: [Errno 1] Operation not permitted

What mistake?

+5
source share
2 answers

I fixed the use of this library

http://pypi.python.org/pypi/privilege/1.0

This safely reduces privileges from root to another user.

+2
source

CAP_SETGID GID. setuid() UID 0, setgid(). .

+19

All Articles