This is a bit more difficult than you might expect. First of all, Python provides os.setuid()
and os.setguid()
to change the current user/group of the running script and you can create a context manager to do your bidding for you and automatically revert back to the currently executing user:
import os
class UnixUser(object):
def __init__(self, uid, gid=None):
self.uid = uid
self.gid = gid
def __enter__(self):
self.cache = os.getuid(), os.getgid() # cache the current UID and GID
if self.gid is not None: # GID change requested as well
os.setgid(self.gid)
os.setuid(self.uid) # set the UID for the code within the `with` block
def __exit__(self, exc_type, exc_val, exc_tb):
# optionally, deal with the exception
os.setuid(self.cache[0]) # revert back to the original UID
os.setgid(self.cache[1]) # revert back to the original GID
And to test it:
def test():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
test() # executes as the current user
with UnixUser(105):
test() # executes as the user with UID: 105
You can even create a neat decorator to select that some functions should always execute as another user:
def as_unix_user(uid, gid=None): # optional group
def wrapper(func):
def wrapped(*args, **kwargs):
with UnixUser(uid, gid):
return func(*args, **kwargs) # execute the function
return wrapped
return wrapper
def test1():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
@as_unix_user(105)
def test2():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
test1() # executes as the current user
test2() # executes as the user with UID: 105
The kicker? Next to not being thread-safe, it will only work if both the current user, and the user you want to execute the function as, have CAP_SETUID
and, optionally, CAP_SETGID
capabilities.
You can get away with having only one user with these capabilities run the main script and then fork when necessary, changing the UID/GID only on the forked process:
import os
def as_unix_user(uid, gid=None): # optional group
def wrapper(func):
def wrapped(*args, **kwargs):
pid = os.fork()
if pid == 0: # we're in the forked process
if gid is not None: # GID change requested as well
os.setgid(gid)
os.setuid(uid) # set the UID for the code within the `with` block
func(*args, **kwargs) # execute the function
os._exit(0) # exit the child process
return wrapped
return wrapper
def test1():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
@as_unix_user(105)
def test2():
print("Current UID: {}".format(os.getuid())) # prints the UID of the executing user
test1() # executes as the current user
test2() # executes as the user with UID: 105
The kicker here? You don't get the return data from the forked function. If you need it, you'll have to pipe it back to the parent process and then wait in the parent for it to finish. You'll also need to choose a format to pass the data between processes (if simple enough, I'd recommend JSON or resort back to native pickle
)...
At that point, you're already doing half of what the subprocess
module is doing so you might as well just launch your function as a subprocess and be done with it. If you have to go through such hoops to achieve your desired result, chances are your original design is at fault. In your case - why not just provide the permissions to the current user to access the DB? The user will need to have the capabilities to switch to another user who can so you're not gaining anything in terms of security from it - you're only complicating your life.