mirror of
https://github.com/altlinux/gpupdate.git
synced 2025-03-20 18:50:17 +03:00
util.users.with_privileges to drop privileges to specified user
This commit is contained in:
parent
d9a956da65
commit
fe9c6600c2
@ -1,5 +1,8 @@
|
||||
import os
|
||||
import pwd
|
||||
import logging
|
||||
|
||||
from .logging import slogm
|
||||
|
||||
def is_root():
|
||||
'''
|
||||
@ -32,3 +35,50 @@ def username_match_uid(username):
|
||||
|
||||
return False
|
||||
|
||||
def set_privileges(username, uid, gid, groups=list()):
|
||||
'''
|
||||
Set current process privileges
|
||||
'''
|
||||
|
||||
try:
|
||||
os.setegid(gid)
|
||||
except Exception as exc:
|
||||
print('setegid')
|
||||
try:
|
||||
os.seteuid(uid)
|
||||
except Exception as exc:
|
||||
print('seteuid')
|
||||
#try:
|
||||
# os.setgroups(groups)
|
||||
#except Exception as exc:
|
||||
# print('setgroups')
|
||||
|
||||
logging.debug(slogm('Set process permissions to UID {} and GID {} for user {}'.format(uid, gid, username)))
|
||||
|
||||
def with_privileges(username, func):
|
||||
'''
|
||||
Run supplied function with privileges for specified username.
|
||||
'''
|
||||
current_uid = os.getuid()
|
||||
current_groups = os.getgrouplist('root', 0)
|
||||
|
||||
if not 0 == current_uid:
|
||||
raise Exception('Not enough permissions to drop privileges')
|
||||
|
||||
user_uid = pwd.getpwnam(username).pw_uid
|
||||
user_gid = pwd.getpwnam(username).pw_gid
|
||||
user_groups = os.getgrouplist(username, user_gid)
|
||||
|
||||
# Drop privileges
|
||||
set_privileges(username, user_uid, user_gid, user_groups)
|
||||
|
||||
# We need to catch exception in order to be able to restore
|
||||
# privileges later in this function
|
||||
try:
|
||||
func()
|
||||
except Exception as exc:
|
||||
logging.debug(slogm(exc))
|
||||
|
||||
# Restore privileges
|
||||
set_privileges('root', current_uid, 0, current_groups)
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user