"Operation not permitted" while dropping privileges using setuid() function
Asked Answered
V

2

9

Why this simple programs that use os.setuid()/gid() fails? Is written in python but I think that is not a language relative problem (at the end are all the same posix system call):

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 is the error?

Vince answered 14/1, 2011 at 15:32 Comment(0)
V
2

I've fixed using this library

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

That securely drop privileges from root to another user.

Vince answered 15/1, 2011 at 17:18 Comment(1)
Package not downloadable; github home page is missing.Tasker
C
26

Only the superuser or processes with the CAP_SETGID capability are allowed to set the GID. After the setuid() call, the effective UID isn't 0 any more, so you are not allowed to call setgid(). Try to reorder the two calls.

Clingy answered 14/1, 2011 at 15:37 Comment(3)
If i swap the two calls setgid() and setuid(), prints the same message.Vince
@Emilio: I can't reproduce this behaviour. It works for me when calling setgid() first -- of course after becoming root via sudo. When calling setuid() first, I get the same error you get.Clingy
Can be some apparmor configuration? One time i couldn't execute 'tcpdump' from a python script because of it (and i was root).Vince
V
2

I've fixed using this library

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

That securely drop privileges from root to another user.

Vince answered 15/1, 2011 at 17:18 Comment(1)
Package not downloadable; github home page is missing.Tasker

© 2022 - 2024 — McMap. All rights reserved.