Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Operation not permitted" on using os.setuid( ) [python]

I'm trying to build a platform to launch some scripts. This scripts are placed in home folder of each user. Every launch should be done with each user id so, I'm doing, for each user, this:

user_id = pwd.getpwnam( user )[ 3 ]
user_home = pwd.getpwnam( user )[ 5 ]

os.chdir( user_home )
os.setuid( user_id )

subprocess.Popen( shlex.split( "user_script.py" ) )

But, when python trys to do os.setuid( user_id ) it raise this exception:

Traceback (most recent call last):
  File "launcher.py", line XX, in <module>

OSError: [Errno 1] Operation not permitted

By the way, the user who starts this script is in the root group (on GNU/linux OS) and it has all the root privileges.

If I try to launch the same code with root user I get a different error:

OSError: [Errno 13] Permission denied

If someone can help me to understand what's happening please...

like image 751
carlesh Avatar asked Sep 23 '11 12:09

carlesh


2 Answers

Only root can do a setuid, being in the root-group is not enough.

like image 107
ott-- Avatar answered Oct 21 '22 13:10

ott--


Only superuser can change uid whenever it feels like it, just adding the user to the root group is not enough.

setuid(2) for example mentions:

 The setuid() system call is permitted if the specified ID is equal to the
 real user ID or the effective user ID of the process, or if the effective
 user ID is that of the super user.

On Linux, there's also:

   Under Linux, setuid() is implemented like the POSIX version with the 
   _POSIX_SAVED_IDS feature.  This allows a set-user-ID (other than  root)
   program to drop all of its user privileges, do some un-privileged work, and
   then reengage the original effective user ID in a secure manner.

I don't even know if Python directly implements this, but it's not exactly what you want anyway.

So the short answer is: Start the initial process as root.

If you're worried about security, start two processes, one as root, one as non-privileged user, and have the non-privileged process communicate with the root process with a socket. This is a more advanced setup though...

like image 35
Martin Tournoij Avatar answered Oct 21 '22 13:10

Martin Tournoij