"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:开发者_Go百科
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...
Only root can do a setuid, being in the root-group is not enough.
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...
OSError: [Errno 1] Operation not permitted
indicates the user who starts the script has insufficient privileges. Being in the root group is not enough, it actually needs the CAP_SETUID
capability.
OSError: [Errno 13] Permission denied
is probably an unrelated error. You should have a look at its stacktrace.
The line
subprocess.Popen( shlex.split( "user_script.py" ) )
confuses me in manifold ways.
- The
shlex.split()
seems to be redundant, as there is nothing to split. - Better put
Popen()
's parameter in a list. - If
user_script.py
has no execute permissions, even root cannot do that.
you also use setuid permission . That is give ,
chmod 4755 script.py
Now even from normal user if you execute the program it will switch as that particular use. You won't get any permission issues .
精彩评论