def change_to_user_group(self, insane=None): """ Change user of the running program. Just insult the admin if he wants root run (it can override). If change failed we sys.exit(2) """ if insane is None: insane = not self.idontcareaboutsecurity # TODO: change user on nt if os.name == 'nt': print("Sorry, you can't change user on this system") return if (self.user == 'root' or self.group == 'root') and not insane: print "What's ??? You want the application run under the root account?" print "I am not agree with it. If you really want it, put :" print "idontcareaboutsecurity=yes" print "in the config file" print "Exiting" sys.exit(2) uid = self.find_uid_from_name() gid = self.find_gid_from_name() if uid is None or gid is None: print "Exiting" sys.exit(2) try: # First group, then user :) os.setregid(gid, gid) os.setreuid(uid, uid) except OSError, e: print "Error : cannot change user/group to %s/%s (%s [%d])" % (self.user, self.group, e.strerror, e.errno) print "Exiting" sys.exit(2)
def drop_privileges(): if 'SUDO_GID' in os.environ: gid = int(os.environ['SUDO_GID']) os.setregid(gid, gid) if 'SUDO_UID' in os.environ: uid = int(os.environ['SUDO_UID']) os.setreuid(uid, uid)
def drop_privs(): try: new_uid = int(os.getenv('SUDO_UID')) new_gid = int(os.getenv('SUDO_GID')) except TypeError: # they were running directly from a root user and didn't have # sudo env variables print """[!] WARNING: Couldn't drop privileges! To avoid this error, run from a non-root user. You may also use sudo, from a non-root user. Continue? (y/n)""", if raw_input().lower()[0] == 'y': return die() debug.info('Dropping privileges to uid: {}, gid: {}'.format(new_uid, new_gid)) # drop group before user, because otherwise you're not privileged enough # to drop group os.setgroups([]) os.setregid(new_gid, new_gid) os.setreuid(new_uid, new_uid) # check to make sure we can't re-escalate try: os.seteuid(0) print '[!] WARNING: Failed to drop privileges! Continue? (y/n)', if raw_input().lower()[0] != 'y': die() except OSError: return
def demote(username): user = pwd.getpwnam(username) os.setgroups([]) os.setregid(user.pw_gid, user.pw_gid) os.setreuid(user.pw_uid, user.pw_uid)
def drop_privileges(user, group): if user is None: uid = os.getuid() elif user.lstrip("-").isdigit(): uid = int(user) else: uid = pwd.getpwnam(user).pw_uid if group is None: gid = os.getgid() elif group.lstrip("-").isdigit(): gid = int(group) else: gid = grp.getgrnam(group).gr_gid username = pwd.getpwuid(uid).pw_name # groupname = grp.getgrgid(gid).gr_name groups = [g for g in grp.getgrall() if username in g.gr_mem] os.setgroups(groups) if hasattr(os, 'setresgid'): os.setresgid(gid, gid, gid) else: os.setregid(gid, gid) if hasattr(os, 'setresuid'): os.setresuid(uid, uid, uid) else: os.setreuid(uid, uid)
def drop_priv(uid_name='nobody', gid_name='nogroup'): import os, pwd, grp xuid = os.getuid() xgid = os.getgid() xname = pwd.getpwuid(xuid).pw_name if os.getuid() != 0: return if xuid == 0: run_uid = pwd.getpwnam(uid_name).pw_uid run_gid = grp.getgrnam(gid_name).gr_gid try: os.setgroups([run_gid]) os.setgid(run_gid) os.setregid(run_gid, run_gid) except OSError, e: print "cannot set gid to %s" % gid_name try: os.setuid(run_uid) os.setreuid(run_uid, run_uid) except OSError, e: print "cannot set uid to %s" % uid_name
def initsecurity(config): idsetuid = None idsetgid = None if config.has_option("pygopherd", "setuid"): import pwd idsetuid = pwd.getpwnam(config.get("pygopherd", "setuid"))[2] if config.has_option("pygopherd", "setgid"): import grp idsetgid = grp.getgrnam(config.get("pygopherd", "setgid"))[2] if config.getboolean("pygopherd", "usechroot"): os.chroot(config.get("pygopherd", "root")) logger.log("Chrooted to " + config.get("pygopherd", "root")) config.set("pygopherd", "root", "/") if idsetuid != None or idsetgid != None: os.setgroups(()) logger.log("Supplemental group list cleared.") if idsetgid != None: os.setregid(idsetgid, idsetgid) logger.log("Switched to group %d" % idsetgid) if idsetuid != None: os.setreuid(idsetuid, idsetuid) logger.log("Switched to uid %d" % idsetuid)
def newPreExec(): preExec and preExec() os.setreuid(uid, uid) os.setregid(gid, gid) os.setsid() os.chdir(homeDir) os.umask(0)
def generate_file_name(self,from_user,file_name,path,queue,to_user=None): done=False counter=1 original_path=path original_file_name=file_name file_name="["+from_user+"]_"+file_name if to_user!=None: user_uid=pwd.getpwnam(to_user)[2] user_gid=pwd.getpwnam(to_user)[3] os.setregid(0, user_gid) os.setreuid(0, user_uid) while not done: if os.path.exists(path+file_name) or os.path.exists(path+"."+file_name): tmp_list=original_file_name.split(".") tmp_list[0]=tmp_list[0]+"_("+str(counter)+")" file_name=".".join(tmp_list) file_name="["+from_user+"]_"+file_name counter+=1 else: done=True f=open(path+"."+file_name,'w') f.close() queue.put(file_name)
def switchUserPreVeil(): if sys.platform in ["darwin", "linux2"]: preveil_pwuid = pwd.getpwnam("preveil") os.setregid(preveil_pwuid.pw_gid, preveil_pwuid.pw_gid) os.setreuid(preveil_pwuid.pw_uid, preveil_pwuid.pw_uid) elif "win32" == sys.platform: pass
def restorePrivs(self): # back to root first self._elevatePrivs() # then set saved privs = self.privStack.pop() os.setregid(privs["rgid"], privs["egid"]) setresuid(privs["ruid"], privs["euid"])
def drop_all_privileges(): # gconf needs both the UID and effective UID set. if 'SUDO_GID' in os.environ: gid = int(os.environ['SUDO_GID']) os.setregid(gid, gid) if 'SUDO_UID' in os.environ: uid = int(os.environ['SUDO_UID']) os.setreuid(uid, uid) os.environ['HOME'] = pwd.getpwuid(uid).pw_dir
def drop_all_privileges(self): # gconf needs both the UID and effective UID set. if "SUDO_GID" in os.environ: # gid = int(os.environ['SUDO_GID']) os.setregid(self.gid, self.gid) if "SUDO_UID" in os.environ: # uid = int(os.environ['SUDO_UID']) os.setreuid(self.uid, self.uid) os.environ["HOME"] = self.home
def setregid(space, rgid, egid): """ setregid(rgid, egid) Set the current process's real and effective group ids. """ try: os.setregid(rgid, egid) except OSError, e: raise wrap_oserror(space, e)
def set_regid(config): '''Change real and effective GID according to config.''' if config.daemon_gid is not None: try: os.setregid(config.daemon_gid, config.daemon_gid) except: logging.error('Error switching to group %d: %s', config.daemon_gid, sys.exc_info()[1]) raise
def drop_privileges(self): if os.geteuid() != 0: return user_name = os.getenv("SUDO_USER") pwnam = pwd.getpwnam(user_name) os.initgroups(user_name, pwnam.pw_gid) os.setregid(pwnam.pw_gid, pwnam.pw_gid) os.setreuid(pwnam.pw_uid, pwnam.pw_uid)
def _safe_child(to_exec, q, uid, gid): try: os.setgroups([]) os.setregid(gid, gid) os.setreuid(uid, uid) res = subprocess.check_output(to_exec, stderr=open(os.devnull, 'w')) q.put(res) except Exception as e: q.put(e)
def restorePrivs(self): # back to root first self._elevatePrivs() # then set saved privs = self.privStack.pop() os.environ.clear() os.environ.update(self.privEnviron.pop()) os.setregid(privs['rgid'], privs['egid']) setresuid(privs['ruid'], privs['euid'])
def setregid(space, rgid, egid): """ setregid(rgid, egid) Set the current process's real and effective group ids. """ check_uid_range(space, rgid) check_uid_range(space, egid) try: os.setregid(rgid, egid) except OSError, e: raise wrap_oserror(space, e)
def drop_all_privileges(self): # gconf needs both the UID and effective UID set. if 'SUDO_GID' in os.environ: # gid = int(os.environ['SUDO_GID']) print_debug("drop_all_privileges GID=%s" % self.gid) os.setregid(self.gid, self.gid) if 'SUDO_UID' in os.environ: # uid = int(os.environ['SUDO_UID']) print_debug("drop_all_privileges UID=%s HOME=%s" % (self.uid, self.home)) os.setreuid(self.uid, self.uid) os.environ['HOME'] = self.home
def drop_privs(self): """Set real UID and GID the same as effective UID and GID. To be used as the `preexec_fn` for `run_cmd` for commands that run durable jobs (not required for mkdir(1), but required for e.g. `mount.posixovl(8)`) """ IO.write("Setting real GID to %d" % os.getegid()) os.setregid(os.getegid(), -1) IO.write("Setting real UID to %d" % os.geteuid()) os.setreuid(os.geteuid(), -1) IO.write("All privileges dropped")
def dropPrivileges(uid, gid): try: os.setregid(gid, gid) os.setreuid(uid, uid) # niby zbedne ;> if os.getuid() != uid or os.getgid() != gid or os.geteuid( ) != uid or os.getegid() != gid: return False return True except: return False
def _drop_privileges(self): try: try: (ruid, euid, suid) = os.getresuid() (rgid, egid, sgid) = os.getresgid() except AttributeError, errmsg: ruid = os.getuid() rgid = os.getgid() if ruid == 0: # Means we can setreuid() / setregid() / setgroups() if rgid == 0: # Get group entry details try: (group_name, group_password, group_gid, group_members) = grp.getgrnam(conf.process_groupname) except KeyError: print >> sys.stderr, _("Group %s does not exist") % ( conf.process_groupname) sys.exit(1) # Set real and effective group if not the same as current. if not group_gid == rgid: log.debug( _("Switching real and effective group id to %d") % (group_gid), level=8) os.setregid(group_gid, group_gid) if ruid == 0: # Means we haven't switched yet. try: (user_name, user_password, user_uid, user_gid, user_gecos, user_homedir, user_shell) = pwd.getpwnam(conf.process_username) except KeyError: print >> sys.stderr, _("User %s does not exist") % ( conf.process_username) sys.exit(1) # Set real and effective user if not the same as current. if not user_uid == ruid: log.debug( _("Switching real and effective user id to %d") % (user_uid), level=8) os.setreuid(user_uid, user_uid)
def move_file(self,orig,dest,owner): user_uid=pwd.getpwnam(owner)[2] user_gid=pwd.getpwnam(owner)[3] os.chown(orig,user_uid,user_gid) os.setregid(0,user_gid) os.setreuid(0,user_uid) shutil.move(orig,dest) tmp=dest.split("/") tmp_file="." + tmp[len(tmp)-1] tmp_file_path="/".join(tmp[:len(tmp)-1]) + "/" + tmp_file os.remove(tmp_file_path)
def root_mode(quiet=True): root_uid = 0 root_gid = 0 try: os.setreuid(0, root_uid) os.setregid(0, root_gid) except OSError as e: msg = "Cannot escalate permissions to (uid=%s, gid=%s): %s" % (root_uid, root_gid, e) if quiet: LOG.warn(msg) else: raise excp.PermException(msg)
def jail(): os.nice(20) resource.setrlimit(resource.RLIMIT_CPU, (5, 5)) # max 5s cpu time resource.setrlimit(resource.RLIMIT_AS, (100*1024*1024, 100*1024*1024)) # max 100MB address space user = pwd.getpwnam('retex') uid, gid = user[2], user[3] os.chroot('/retex-jail') os.setregid(gid, gid) os.setreuid(uid, uid)
def drop_privileges(self): try: try: (ruid, euid, suid) = os.getresuid() (rgid, egid, sgid) = os.getresgid() except AttributeError, errmsg: ruid = os.getuid() rgid = os.getgid() if ruid == 0: # Means we can setreuid() / setregid() / setgroups() if rgid == 0: # Get group entry details try: ( group_name, group_password, group_gid, group_members ) = grp.getgrnam(conf.process_groupname) except KeyError: print >> sys.stderr, "Group %s does not exist" % (conf.process_groupname) sys.exit(1) # Set real and effective group if not the same as current. if not group_gid == rgid: log.debug("Switching real and effective group id to %d" % (group_gid), level=8) os.setregid(group_gid, group_gid) if ruid == 0: # Means we haven't switched yet. try: ( user_name, user_password, user_uid, user_gid, user_gecos, user_homedir, user_shell ) = pwd.getpwnam(conf.process_username) except KeyError: print >> sys.stderr, "User %s does not exist" % (conf.process_username) sys.exit(1) # Set real and effective user if not the same as current. if not user_uid == ruid: log.debug("Switching real and effective user id to %d" % (user_uid), level=8) os.setreuid(user_uid, user_uid)
def open_daemon(prob_user, prob_port, prob_entry, prob_home): pid = 0 try: pid = os.fork() except OSError as e: exit(1) if pid == 0: os.chdir(prob_home) user = pwd.getpwnam(prob_user) os.setregid(user.pw_gid, user.pw_gid) os.setreuid(user.pw_uid, user.pw_uid) os.execv('/usr/bin/socat', ['socat', 'tcp-listen:%d,fork,reuseaddr,bind=127.0.0.1' % prob_port, 'exec:%s,PTY,CTTY,raw,echo=0' % prob_entry]) return pid
def become(user): """Switch to another user (need to be root first).""" u = pwd.getpwnam(user) os.environ["LOGNAME"] = os.environ["USER"] = u.pw_name os.environ["PWD"] = os.getcwd() os.environ["HOME"] = u.pw_dir os.environ["SHELL"] = u.pw_shell os.setregid(u.pw_gid, u.pw_gid) try: os.initgroups(user, u.pw_gid) except OverflowError: pass # FIXME??? os.setreuid(u.pw_uid, u.pw_uid)
def do_as_user(username, func, *args, **kwargs): _, _, uid, gid, _, _, _ = getpwnam(username) pid = os.fork() if pid == 0: if os.getgid() != gid: os.setregid(gid, gid) if os.getuid() != uid: os.setreuid(uid, uid) func(*args, **kwargs) os._exit(0) else: os.waitpid(pid, 0)
def main(): # daemon mode if os.fork() == 0 : os.setsid() sys.stdin = open('/dev/null') if stdoutlog: sys.stdout = stdoutlog sys.stderr = stdoutlog if os.fork() == 0: ppid = os.getppid() while ppid != 1: time.sleep(1) ppid = os.getppid() else: os._exit(0) else: os.wait() sys.exit(1) pf = open(poptions.pidfile, 'w') pf.write('%d\n' % os.getpid()) pf.close() if poptions.setuid: gid = grp.getgrnam("nogroup").gr_gid os.setregid(gid, gid) uid = pwd.getpwnam("nobody").pw_uid os.setreuid(uid, uid) logging.config.fileConfig(poptions.config) # subproc mode signal.signal(signal.SIGTERM, sigTerm) while True: child = os.fork() if child == 0 : time.sleep (1) break sys.stdout.write("Forked subprocess: %d\n" % child) sys.stdout.flush() os.wait() # http://localhost:9010/update?runid=1234&message={'sources':'somejson} runnerfactory = RunnerFactory() port = config.getint('twister', 'port') reactor.listenTCP(port, runnerfactory) logger.info("Twister listening on port %d" % port) reactor.run() # this function never returns
def deescalate_sudo(): try: uid = os.environ.pop('SUDO_UID') gid = os.environ.pop('SUDO_GID') except KeyError: pass else: uid = int(uid) gid = int(gid) # username = pwd.getpwuid(uid).pw_name # groups = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem] os.setgroups([]) # for now loose supplementary groups os.setregid(int(gid), int(gid)) os.setreuid(int(uid), int(uid))
def start(self): self._stop_event.clear() self.logger = self.directory.create_normal_logger( self.general_cfg.gid, self.general_cfg.uid ) self.logger_error = self.directory.create_error_logger( self.general_cfg.gid, self.general_cfg.uid ) self.logger.info("starting server") self.spooler = wayround_i2p.mail.server.spool.SpoolWorker( self ) self.logger.info("configuring domains") for i in self.cfg['domains']: self.logger.info(" domain [{}]".format(i['domain'])) self.domains.append( Domain( self, wayround_i2p.mail.server.config.DomainConfig(i), self.callable_target_for_socket_pools ) ) for i in self.domains: i.start() if self.general_cfg.gid is not None: os.setregid( self.general_cfg.gid, self.general_cfg.gid ) if self.general_cfg.uid is not None: os.setreuid( self.general_cfg.uid, self.general_cfg.uid ) self.directory.get_spool_directory().makedirs() self.directory.get_permanent_memory().init() return
def run(): #Ensure that pre-setup tasks are taken care of. conf.init() #Start Web server. if conf.WEB_ENABLED: web_thread = web.WebService() web_thread.start() #Start DHCP server. dhcp_thread = dhcp.DHCPService() dhcp_thread.start() #Record PID. #noinspection PyBroadException try: pidfile = open(conf.PID_FILE, 'w') pidfile.write(str(os.getpid()) + '\n') pidfile.close() os.chown(conf.PID_FILE, conf.UID, conf.GID) except: logging.writeLog("Unable to write pidfile: %(file)s" % {'file': conf.PID_FILE,}) #Touch logfile. #noinspection PyBroadException try: open(conf.LOG_FILE, 'a').close() os.chown(conf.LOG_FILE, conf.UID, conf.GID) except: logging.writeLog("Unable to write pidfile: %(file)s" % {'file': conf.PID_FILE,}) #Set signal-handlers. signal.signal(signal.SIGHUP, _logHandler) signal.signal(signal.SIGTERM, _quitHandler) #Set proper permissions for execution os.setregid(conf.GID, conf.GID) os.setreuid(conf.UID, conf.UID) #Serve until interrupted. tick = 0 while True: time.sleep(1) tick += 1 if tick >= conf.POLLING_INTERVAL: #Perform periodic cleanup. dhcp_thread.pollStats() logging.emailTimeoutCooldown() tick = 0
def drop_privs(username): # check if we are root. If we are, drop privileges start_uid = os.getuid() if start_uid == 0: # NOTE: Must set gid first or you will get an # "Operation not permitted" error pwd_tuple = pwd.getpwnam(username) pw_uid = pwd_tuple[2] pw_gid = pwd_tuple[3] os.setregid(pw_gid, pw_gid) os.setreuid(pw_uid, pw_uid) else: # Not root so we can't change privileges so pass pass
def _check_access(self, user, path, ret_queue): user_info = pwd.getpwnam(user) # GROUP BEFORE UID !!!11 os.setregid(user_info.pw_gid, user_info.pw_gid) os.setreuid(user_info.pw_uid, user_info.pw_uid) status = False status = os.access(path, os.W_OK) # ACL CHECK COULD GO HERE # # ################### # ret_queue.put(status)
def inner(*args, **kwargs): current_proc = multiprocessing.current_process() logger.debug( "Changing permissions for process: {0} with PID: {1!s}".format( current_proc.name, current_proc.pid)) if sys.version > "2.7": ruid, euid, suid = os.getresuid() rgid, egid, sgid = os.getresgid() logger.debug( "UIDs before are: (ruid) {0}, (euid) {1}, (suid) {2}".format( ruid, euid, suid)) logger.debug( "GIDs before are: (rgid) {0}, (egid) {1}, (sgid) {2}".format( rgid, egid, sgid)) logger.debug("Setting all UIDs/GIDs to 0") # Make the actual permissions changes os.setresuid(0, 0, 0) os.setresgid(0, 0, 0) try: retval = func(*args, **kwargs) finally: # Restore original permissions os.setresgid(rgid, egid, sgid) os.setresuid(ruid, euid, suid) else: ruid = os.getuid() euid = os.geteuid() rgid = os.getgid() egid = os.getegid() logger.debug("UIDs before are: (ruid) {0}, (euid) {1}".format( ruid, euid)) logger.debug("GIDs before are: (rgid) {0}, (egid) {1}".format( rgid, egid)) logger.debug("Setting all UIDs/GIDs to 0") # Make the actual permissions changes os.setreuid(0, 0) os.setregid(0, 0) try: logger.debug("Setting all UIDs/GIDs to 0") retval = func(*args, **kwargs) finally: # Restore original permissions os.setregid(rgid, egid) os.setreuid(ruid, euid) return retval
def drop_all_privileges(): # gconf needs both the UID and effective UID set. global _dropped_privileges uid = os.environ.get('SUDO_UID') gid = os.environ.get('SUDO_GID') if uid is not None: uid = int(uid) set_groups_for_uid(uid) if gid is not None: gid = int(gid) os.setregid(gid, gid) if uid is not None: uid = int(uid) os.setreuid(uid, uid) os.environ['HOME'] = pwd.getpwuid(uid).pw_dir _dropped_privileges = None
def become_user(user=None): """ Change to run as the specified user. If 'None' then we just return. If we are already running as the given user, also do nothing and return. """ if user is None: return current_user = pwd.getpwuid(os.getuid()) if current_user[0] == user: return pwinfo = pwd.getpwnam(user) os.setregid(pwinfo[3], pwinfo[3]) os.setreuid(pwinfo[2], pwinfo[2]) return
def drop_all_privileges(): # gconf needs both the UID and effective UID set. global _dropped_privileges if 'SUDO_GID' in os.environ: gid = int(os.environ['SUDO_GID']) os.setregid(gid, gid) else: os.setregid(ASSUMED_GID, ASSUMED_GID) if 'SUDO_UID' in os.environ: uid = int(os.environ['SUDO_UID']) os.setreuid(uid, uid) os.environ['HOME'] = pwd.getpwuid(uid).pw_dir else: os.setreuid(ASSUMED_UID, ASSUMED_UID) os.environ['HOME'] = "/tmp" _dropped_privileges = None
def drop_all_privileges(): """ Drop root privileges """ # gconf needs both the UID and effective UID set. global _DROPPED_PRIVILEGES uid = os.environ.get('SUDO_UID') gid = os.environ.get('SUDO_GID') if uid is not None: uid = int(uid) set_groups_for_uid(uid) if gid is not None: gid = int(gid) os.setregid(gid, gid) if uid is not None: uid = int(uid) os.setreuid(uid, uid) os.environ['HOME'] = pwd.getpwuid(uid).pw_dir os.environ['LOGNAME'] = pwd.getpwuid(uid).pw_name _DROPPED_PRIVILEGES = None
def drop_privileges(user, group): """Drop privileges to specified user and group""" if group is not None: import grp gid = grp.getgrnam(group).gr_gid logger.debug("Dropping privileges to group {0}/{1}".format(group, gid)) try: os.setresgid(gid, gid, gid) except AttributeError: os.setregid(gid, gid) if user is not None: import pwd uid = pwd.getpwnam(user).pw_uid logger.debug("Dropping privileges to user {0}/{1}".format(user, uid)) try: os.setresuid(uid, uid, uid) except AttributeError: os.setreuid(uid, uid)
def droppriv(uid, gid, code=0): # Set group must be done before user. setregid(gid, gid) # Reduce supplementary groups setgroups([gid]) # Finally, set user. setreuid(uid, uid) # Test that we cannot re-root try: setuid(0) except OSError: pass else: if code: print >> stderr, RootEscalationError().message exit(code) else: raise RootEscalationError()
def user_mode(quiet=True): (sudo_uid, sudo_gid) = get_suids() if sudo_uid is not None and sudo_gid is not None: try: os.setregid(0, sudo_gid) os.setreuid(0, sudo_uid) except OSError: if quiet: LOG.warn("Cannot drop permissions to (user=%s, group=%s)" % (sudo_uid, sudo_gid)) else: raise else: msg = "Can not switch to user mode, no suid user id or group id" if quiet: LOG.warn(msg) else: raise excp.AnvilException(msg)
def daemonize(user=0, group=0): # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError as e: sys.stderr.write("Fork failed (#1): %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment # chdir -> don't prevent unmounting... os.chdir("/") # Create new process group with the process as leader os.setsid() # Set user/group depending on params if group: os.setregid(getgrnam(group)[2], getgrnam(group)[2]) if user: os.setreuid(getpwnam(user)[2], getpwnam(user)[2]) # do second fork try: pid = os.fork() if pid > 0: sys.exit(0) except OSError as e: sys.stderr.write("Fork failed (#2): %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) sys.stdout.flush() sys.stderr.flush() si = os.open("/dev/null", os.O_RDONLY) so = os.open("/dev/null", os.O_WRONLY) os.dup2(si, 0) os.dup2(so, 1) os.dup2(so, 2) os.close(si) os.close(so)
def root_mode(quiet=True): root_uid = getuid(ROOT_USER) root_gid = getgid(ROOT_USER) if root_uid is None or root_gid is None: msg = "Cannot escalate permissions to (user=%s) - does that user exist??" % (ROOT_USER) if quiet: LOG.warn(msg) else: raise excp.StackException(msg) else: try: LOG.debug("Escalating permissions to (user=%s, group=%s)" % (root_uid, root_gid)) os.setreuid(0, root_uid) os.setregid(0, root_gid) except OSError: if quiet: LOG.warn("Cannot escalate permissions to (user=%s, group=%s)" % (root_uid, root_gid)) else: raise
def root_mode(quiet=True): root_uid = getuid('root') root_gid = getgid('root') if root_uid is None or root_gid is None: msg = "Cannot escalate permissions to (user=root) - does that user exist??" if quiet: LOG.warn(msg) else: raise excp.AnvilException(msg) else: try: os.setreuid(0, root_uid) os.setregid(0, root_gid) except OSError: if quiet: LOG.warn("Cannot escalate permissions to (user=%s, group=%s)" % (root_uid, root_gid)) else: raise
def change_uidgid(logger=None, uid=None, gid=None): ''' Change the current effective GID and UID to those specified by uid and gid. ''' try: if gid: if os.getegid() != gid: if logger: logger.debug('Setting egid to %d\n' % gid) os.setregid(gid, gid) if uid: if os.geteuid() != uid: if logger: logger.debug('Setting euid to %d\n' % uid) os.setreuid(uid, uid) except OSError as o: raise getmailDeliveryError('change UID/GID to %s/%s failed (%s)' % (uid, gid, o))
def change_users_and_groups(mamaji_data): current_users = mamaji_data['current_users'] current_groups = mamaji_data['current_groups'] pending_users = mamaji_data['pending_users'] pending_groups = mamaji_data['pending_groups'] groups = mamaji_data['supplementary_groups'] if groups: os.setgroups(groups) group_types = [ k for k in ['rgid', 'egid', 'sgid'] if pending_groups[k] is not None ] group_types_len = len(group_types) if group_types_len == 3: setresgid(pending_groups['rgid'], pending_groups['egid'], pending_groups['sgid']) elif group_types_len == 2: if 'rgid' in group_types and 'egid' in group_types: os.setregid(pending_groups['rgid'], pending_groups['egid']) elif group_types_len == 1: if 'egid' in group_types: os.setegid(pending_groups['egid']) user_types = [ k for k in ['ruid', 'euid', 'suid'] if pending_users[k] is not None ] user_types_len = len(user_types) if user_types_len == 3: setresuid(pending_users['ruid'], pending_users['euid'], pending_users['suid']) elif user_types_len == 2: if 'ruid' in user_types and 'euid' in user_types: os.setreuid(pending_users['ruid'], pending_users['euid']) elif user_types_len == 1: if 'euid' in user_types: os.seteuid(pending_users['euid']) if pending_groups['gid'] is not None: os.setgid(pending_groups['gid']) if pending_users['uid'] is not None: os.setuid(pending_users['uid'])
def on_gid(self, args: Sequence[str], block: None): import grp gid = None if args[0].isnumeric(): gid = int(args[0]) else: gid = grp.getgrnam(args[0]).gr_gid self.prepare_list.setdefault( 10, [lambda: None, lambda: None])[1] = lambda: os.setregid(gid)
def preexec_fn(): if runas is not None: pent = pwd.getpwnam(runas) suplementary_gids = [ grp.getgrnam(group).gr_gid for group in suplementary_groups ] logger.debug('runas=%s (UID %d, GID %s)', runas, pent.pw_uid, pent.pw_gid) if suplementary_groups: for group, gid in zip(suplementary_groups, suplementary_gids): logger.debug('suplementary_group=%s (GID %d)', group, gid) os.setgroups(suplementary_gids) os.setregid(pent.pw_gid, pent.pw_gid) os.setreuid(pent.pw_uid, pent.pw_uid) if umask: os.umask(umask)
def dropped_privileges(passwd: pwd.struct_passwd): """ Context manager for temporarily switching real and effective UID and real and effective GID. """ logger.debug("Dropping privileges temporary to user %s", passwd.pw_name) # To handle multiple users with the same UID correctly, we obtain the # current user name with getpass saved_user = getpass.getuser() saved_uid = os.geteuid() saved_gid = os.getegid() os.initgroups(passwd.pw_name, passwd.pw_gid) os.setresuid(passwd.pw_uid, passwd.pw_uid, saved_uid) try: yield finally: os.seteuid(saved_uid) os.setreuid(saved_uid, saved_uid) os.setregid(saved_gid, saved_gid) os.initgroups(saved_user, saved_gid) logger.debug("Restoring previous privileges as user %s", saved_user)
def drop_privileges(username): """ Drop privileges from root to a non-privileged user. NOTE: Must be running as root to drop privileges. @type username: C{str} @param username: Unprivileged user that we are are going to run as. """ # check if we are root. If we are, drop privileges start_uid = os.getuid() if start_uid == 0: # NOTE: Must set gid first or you will get an # "Operation not permitted" error pwd_tuple = pwd.getpwnam(username) pw_uid = pwd_tuple[2] pw_gid = pwd_tuple[3] os.setregid(pw_gid, pw_gid) os.setreuid(pw_uid, pw_uid) else: # Not root so we can't change privileges so pass pass
def _fork(self, path, uid, gid, executable, args, environment, **kwargs): """ Fork and then exec sub-process. @param path: the path where to run the new process. @type path: C{str} @param uid: if defined, the uid used to run the new process. @type uid: C{int} @param gid: if defined, the gid used to run the new process. @type gid: C{int} @param executable: the executable to run in a new process. @type executable: C{str} @param args: arguments used to create the new process. @type args: C{list}. @param environment: environment used for the new process. @type environment: C{dict}. @param kwargs: keyword arguments to L{_setupChild} method. """ settingUID = (uid is not None) or (gid is not None) if settingUID: curegid = os.getegid() currgid = os.getgid() cureuid = os.geteuid() curruid = os.getuid() if uid is None: uid = cureuid if gid is None: gid = curegid # prepare to change UID in subprocess os.setuid(0) os.setgid(0) collectorEnabled = gc.isenabled() gc.disable() try: self.pid = os.fork() except: # Still in the parent process if collectorEnabled: gc.enable() raise else: if self.pid == 0: # pid is 0 in the child process # do not put *ANY* code outside the try block. The child process # must either exec or _exit. If it gets outside this block (due # to an exception that is not handled here, but which might be # handled higher up), there will be two copies of the parent # running in parallel, doing all kinds of damage. # After each change to this code, review it to make sure there # are no exit paths. try: # Stop debugging. If I am, I don't care anymore. sys.settrace(None) self._setupChild(**kwargs) self._execChild(path, settingUID, uid, gid, executable, args, environment) except: # If there are errors, bail and try to write something # descriptive to stderr. # XXX: The parent's stderr isn't necessarily fd 2 anymore, or # even still available # XXXX: however even libc assumes write(2, err) is a useful # thing to attempt try: stderr = os.fdopen(2, 'w') stderr.write( "Upon execvpe %s %s in environment %s\n:" % (executable, str(args), "id %s" % id(environment))) traceback.print_exc(file=stderr) stderr.flush() for fd in range(3): os.close(fd) except: pass # make *sure* the child terminates # Did you read the comment about not adding code here? os._exit(1) # we are now in parent process if collectorEnabled: gc.enable() self.status = -1 # this records the exit status of the child if settingUID: os.setregid(currgid, curegid) os.setreuid(curruid, cureuid)