def setuid(): """ Change user. Change to a less privileged user.Unless you're using it incorrectly -- inwhich case, don't use it. :raises SystemExit: Exit code :py:obj:`os.EX_USAGE` when a configuration error occurs or :py:obj:`os.EX_NOPERM` when a permission error occurs. .. note:: MUST be called AFTER setgid, not before. """ config = Config() try: uid = pwd.getpwnam(config.user).pw_uid os.setuid(uid) except KeyError: logger.error("User '%s' does not exist.", config.user) raise SystemExit(os.EX_USAGE) except PermissionError: logger.error( "You do not have permission to switch to user '%s'.", config.user ) raise SystemExit(os.EX_NOPERM)
def SetIDs_callback(): if gid is not -1: os.setgroups([gid]) os.setgid(gid) if uid is not -1: os.setuid(uid) os.environ["HOME"] = os.path.expanduser("~" + User)
def preexec_fn(): streams = [sys.stdin] if self.close_child_stdout: streams.append(sys.stdout) if self.close_child_stderr: streams.append(sys.stderr) self._null_streams(streams) os.setsid() for limit, value in self.rlimits.items(): res = getattr(resource, 'RLIMIT_%s' % limit.upper(), None) if res is None: raise ValueError('unknown rlimit "%s"' % limit) # TODO(petef): support hard/soft limits resource.setrlimit(res, (value, value)) if self.gid: try: os.setgid(self.gid) except OverflowError: if not ctypes: raise # versions of python < 2.6.2 don't manage unsigned int for # groups like on osx or fedora os.setgid(-ctypes.c_int(-self.gid).value) if self.uid: os.setuid(self.uid)
def setuser(username): if not username: return import pwd import grp try: pwrec = pwd.getpwnam(username) except KeyError: sys.stderr.write('user not found: %s\n' % username) raise user = pwrec[0] uid = pwrec[2] gid = pwrec[3] cur_uid = os.getuid() if uid == cur_uid: return if cur_uid != 0: sys.stderr.write('can not set user as nonroot user\n') # will raise later # inspired by supervisor if hasattr(os, 'setgroups'): groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]] groups.insert(0, gid) os.setgroups(groups) os.setgid(gid) os.setuid(uid)
def drop_privileges(self, uid_name=None, gid_name=None): """ Drop privileges Found in https://github.com/zedshaw/python-lust/blob/master/lust/unix.py """ if os.getuid() != 0: self.logger.warning("Must be root to drop privileges!") return # Get the uid/gid from the name. If no group given, then derive group from uid_name if uid_name is None: uid_name = "nobody" # builtin default is nobody running_uid = pwd.getpwnam(uid_name).pw_uid if gid_name is None: running_gid = pwd.getpwnam(uid_name).pw_gid else: running_gid = grp.getgrnam(gid_name).gr_gid self.logger.debug("Running as %r.%r" % (running_uid, running_gid)) # Remove group privileges os.setgroups([]) # Try setting the new uid/gid os.setgid(running_gid) os.setuid(running_uid) # Ensure a very conservative umask os.umask(077)
def lookup(self, params): if self.gid >= 0: os.setgid(self.gid) if self.uid >= 0: os.setuid(self.uid) try: user, domain = params['username'].split('@', 1) except ValueError: user, domain = params['username'], self.defaultdomain def repl(m): l = m.group(2) r = m.group(3) c = m.group(4) if c == '%': return '%' elif c == 'u': s = user elif c == 'd': s = domain if l: l = int(l) if r: r = int(r[1:]) return s[l:l+r] else: return s[:l] else: return s username = path_re.sub(repl, self.path) return username
def shell(self): self.callee = utils.User(name='nobody') assert self.callee is not None try: os.chdir(self.path or self.callee.dir) except: pass env = os.environ # User has been auth with ssl or is the same user as server # or login is explicitly turned off if ( not tornado.options.options.unsecure and tornado.options.options.login and not ( self.socket.local and self.caller == self.callee and server == self.callee )): # User is authed by ssl, setting groups try: os.initgroups(self.callee.name, self.callee.gid) os.setgid(self.callee.gid) os.setuid(self.callee.uid) except: print('The server must be run as root ' 'if you want to log as different user\n') sys.exit(1) args = [tornado.options.options.shell or self.callee.shell] args.append('-q') args.append('--lf') args.append('/dev/pts/2') os.execvpe(args[0], args, env)
def check_user(user, log): ''' Check user and assign process uid/gid. ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): return True if user == getpass.getuser(): return True import pwd # after confirming not running Windows try: p = pwd.getpwnam(user) try: os.setgid(p.pw_gid) os.setuid(p.pw_uid) except OSError: if user == 'root': msg = 'Sorry, the salt must run as root. http://xkcd.com/838' else: msg = 'Salt must be run from root or user "{0}"'.format(user) log.critical(msg) return False except KeyError: msg = 'User not found: "{0}"'.format(user) log.critical(msg) return False return True
def SendMail(self): pid = os.fork() if pid > 0: return if pid == 0: os.setuid(1001) os.system('/home/enet/Shell/Mail/do_main.sh')
def run_as_user(user): if os.getuid() != 0: raise NonRootException('this program must to be started as root') user_info = pwd.getpwnam(config.run_user) uid = user_info[2] os.setuid(uid)
def drop_privileges(): """Drop root privileges down to the specified SETUID_USER. N.B. DO NOT USE THE logging MODULE FROM WITHIN THIS FUNCTION. This function is run in forked processes right before it calls exec, but the fork may have occured while a different thread had locked the log. Since it's a forked process, the log will be locked forever in the subprocess and thus a logging.X may block forever. """ we_are_root = os.getuid() == 0 if not we_are_root: print >>sys.stdout, "[INFO] Not running as root, skipping privilege drop" return try: pw = pwd.getpwnam(SETUID_USER) except: print >>sys.stderr, "[ERROR] Couldn't get user information for user " + SETUID_USER raise try: gr = grp.getgrnam(SETGID_GROUP) except: print >>sys.stderr, "[ERROR] Couldn't get group information for group " + SETGID_GROUP raise # gid has to be set first os.setgid(gr.gr_gid) os.setuid(pw.pw_uid)
def change_uid(self): c_user = self.config.uid c_group = self.config.gid if os.getuid() == 0: cpw = pwd.getpwnam(c_user) c_uid = cpw.pw_uid if c_group: cgr = grp.getgrnam(c_group) c_gid = cgr.gr_gid else: c_gid = cpw.pw_gid c_groups = [] for item in grp.getgrall(): if c_user in item.gr_mem: c_groups.append(item.gr_gid) if c_gid not in c_groups: c_groups.append(c_gid) os.chown(self.config.datadir, c_uid, c_gid) os.chown(self.config.rundir, c_uid, c_gid) os.chown(self.config.pidfile, c_uid, c_gid) for root, _, filenames in os.walk(self.config.datadir): for filename in filenames: os.chown(os.path.join(root, filename), c_uid, c_gid) for root, _, filenames in os.walk(self.config.rundir): for filename in filenames: os.chown(os.path.join(root, filename), c_uid, c_gid) os.setgid(c_gid) os.setgroups(c_groups) os.setuid(c_uid)
def startServices(extras=None): os.setuid(0) if extras is None: ui.info(_("Starting services")) import dbus try: bus = dbus.SystemBus() except dbus.DBusException: ui.error(_("Cannot connect to DBus, services won't be started")) return # Almost everything depends on logger, so start manually startService("sysklogd") if extras: for service in extras: try: startService(service) except dbus.DBusException: pass return # Give login screen a headstart if config.get("head_start"): startService(config.get("head_start")) if not config.get("safe"): services = getServices(bus) for service in services: readyService(service)
def change_user(uid, gid, euid=False): # TODO: validate uid/gid, do root checks, etc. os.setgid(gid) if not euid: os.setuid(uid) else: os.seteuid(uid)
def drop_privileges (self): """returns true if we are left with insecure privileges""" # os.name can be ['posix', 'nt', 'os2', 'ce', 'java', 'riscos'] if os.name not in ['posix',]: return False uid = os.getuid() gid = os.getgid() if uid and gid: return False try: user = pwd.getpwnam(self.user) nuid = int(user.pw_uid) ngid = int(user.pw_uid) except KeyError: return True # not sure you can change your gid if you do not have a pid of zero try: if not gid: os.setgid(ngid) if not uid: os.setuid(nuid) return False except OSError: return True
def parse_args(self, only_front = False): """ Parse command-line arguments. """ args = jnt_parse_args(only_front=only_front) self.options = vars(args) self.action = args.command self.args = args self.stdout_path = os.path.join(self.options['log_dir'], self.options['service'] + "_out.log") self.stderr_path = os.path.join(self.options['log_dir'], self.options['service'] + "_err.log") self.pidfile_path = os.path.join(self.options['pid_dir'], self.options['service'] + ".pid") if self.options['user'] and self.options['user'] != "": self.userid = pwd.getpwnam(self.options['user']).pw_uid if self.userid != os.getuid(): #print self.userid os.setuid(self.userid) try: os.makedirs(self.options['pid_dir']) os.makedirs(self.options['home_dir']) os.makedirs(self.options['conf_dir']) os.makedirs(self.options['log_dir']) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST: pass else: raise if self.action not in self.action_funcs: self._usage_exit(args)
def setuid(user): if not hasattr(os, 'getuid'): return # People can remove this check if they're really determined if user is None: if os.getuid(): return raise ValueError, _("Can't run as root!") if os.getuid(): print _('WARNING: ignoring "-u" argument, not root') return try: import pwd except ImportError: raise ValueError, _("Can't change users - no pwd module") try: try: uid = int(user) except ValueError: uid = pwd.getpwnam(user)[2] else: pwd.getpwuid(uid) except KeyError: raise ValueError, _("User %(user)s doesn't exist")%locals() os.setuid(uid)
def __init__(self, config, config_files=None, config_dirs=None, managed=None): config = clcommon.config.update(DEFAULT_CONFIG, config) self.config, _args = clcommon.config.load(config, config_files, config_dirs, False) config = self.config['clcommon']['server'] if config['daemonize']: if os.fork() > 0: exit(0) os.setsid() null = open('/dev/null') os.dup2(null.fileno(), 0) os.dup2(null.fileno(), 1) os.dup2(null.fileno(), 2) clcommon.log.setup(self.config) self._parent = os.getpid() if config['pid_file'] is not None: pid_file = open(config['pid_file'], 'w') pid_file.write('%d' % self._parent) if config['group'] is not None: os.setgid(grp.getgrnam(config['group']).gr_gid) if config['user'] is not None: os.setuid(pwd.getpwnam(config['user']).pw_uid) self.log = clcommon.log.get_log('clcommon_server', config['log_level']) self._children = {} self._stopping = False if managed is None: self.managed = [] else: self.managed = [method(self.config) for method in managed]
def change_process_owner(uid, gid, initgroups=False): """ Change the owning UID, GID, and groups of this process. :param uid: The target UID for the daemon process. :param gid: The target GID for the daemon process. :param initgroups: If true, initialise the supplementary groups of the process. :return: ``None``. Sets the owning GID and UID of the process (in that order, to avoid permission errors) to the specified `gid` and `uid` values. If `initgroups` is true, the supplementary groups of the process are also initialised, with those corresponding to the username for the target UID. All these operations require appropriate OS privileges. If permission is denied, a ``DaemonOSEnvironmentError`` is raised. """ try: username = get_username_for_uid(uid) except KeyError: # We don't have a username to pass to ‘os.initgroups’. initgroups = False try: if initgroups: os.initgroups(username, gid) else: os.setgid(gid) os.setuid(uid) except Exception as exc: error = DaemonOSEnvironmentError( "Unable to change process owner ({exc})".format(exc=exc)) raise error
def run_as_root(args, stdin=None): if stdin is not None: pipe_r, pipe_w = os.pipe() else: pipe_r, pipe_w = None, None pid = os.fork() if pid == 0: if pipe_r is not None: # setup stdin pipe os.dup2(pipe_r, 0) os.close(pipe_r) os.close(pipe_w) os.seteuid(0) os.setuid(0) try: os.execv(args[0], args) except: os._exit(127) else: if pipe_r is not None: os.close(pipe_r) os.write(pipe_w, stdin) os.close(pipe_w) wpid, sts = os.waitpid(pid, 0) code = sts_result(sts) if code != 0: raise MyException("%r: exited with result %d"% (args, code))
def main(argv): parser = argparse.ArgumentParser(description='osdial_remote_agents - Simulates presence of both remote and virtual agents.') parser.add_argument('-v', '--verbose', action='count', default=0, help='Increases verbosity.', dest='verbose') parser.add_argument('--version', action='version', version='%(prog)s %(ver)s' % {'prog':PROGNAME,'ver':VERSION}) parser.add_argument('--debug', action='store_true', help='Run in debug mode.',dest='debug') parser.add_argument('-t', '--test', action='store_true', help='Run in test mode.',dest='test') parser.add_argument('-d', '--daemon', action='store_true', help='Puts process in daemon mode.',dest='daemon') parser.add_argument('-l', '--logLevel', action='store', default='INFO', choices=['CRITICAL','ERROR','WARNING','INFO','DEBUG'], help='Sets the level of output verbosity.', dest='loglevel') parser.add_argument('--delay', action='store', default=2, help='delay per loop, in seconds (default 2)', dest='delay') opts = parser.parse_args(args=argv) newargs = vars(opts) for arg in newargs: opt[arg] = newargs[arg] if not opt['delay']: opt['delay'] = 2 opt['delay'] = int(opt['delay']) * 1000 try: if os.getuid() == 0: astpwd = pwd.getpwnam('asterisk'); os.setgid(astpwd.pw_gid) os.setuid(astpwd.pw_uid) except KeyError, e: pass
def drop_privileges(user: pwd.struct_passwd, group: grp.struct_group, permanent: bool = True): """ Drop root privileges and change to something more safe. :param user: The tuple with user info :param group: The tuple with group info :param permanent: Whether we want to drop just the euid (temporary), or all uids (permanent) """ # Restore euid=0 if we have previously changed it if os.geteuid() != 0 and os.getuid() == 0: restore_privileges() if os.geteuid() != 0: raise RuntimeError("Not running as root: cannot change uid/gid to {}/{}".format(user.pw_name, group.gr_name)) # Remove group privileges os.setgroups([]) if permanent: os.setgid(group.gr_gid) os.setuid(user.pw_uid) else: os.setegid(group.gr_gid) os.seteuid(user.pw_uid) # Ensure a very conservative umask os.umask(0o077) if permanent: logger.debug("Permanently dropped privileges to {}/{}".format(user.pw_name, group.gr_name)) else: logger.debug("Dropped privileges to {}/{}".format(user.pw_name, group.gr_name))
def demote(self, uid): try: username = pwd.getpwuid(uid).pw_name gid = pwd.getpwuid(uid).pw_gid except KeyError: username = None gid = uid if os.getuid() == uid: return else: if os.getuid() != 0: logging.warn('Running as a limited user, setuid() unavailable!') return logging.info( 'Worker %s is demoting to UID %s / GID %s...', os.getpid(), uid, gid ) groups = [ g.gr_gid for g in grp.getgrall() if username in g.gr_mem or g.gr_gid == gid ] os.setgroups(groups) os.setgid(gid) os.setuid(uid) logging.info( '...done, new EUID %s EGID %s', os.geteuid(), os.getegid() )
def drop_privs(username, groupname, umask=None): """Drop process privileges to specified user and group. Privileges will only be dropped if current uid is root. Args: username: drop user privileges to username groupname: drop group privilegs to groupname umask: if provided, process umask will be changed accordingly. """ #If not root, nothing to drop. if os.getuid() != 0: return uid = pwd.getpwnam(username).pw_uid gid = grp.getgrnam(groupname).gr_gid #Remove groups os.setgroups([]) #Set gid and uid os.setgid(gid) os.setuid(uid) #Set umask if provided if umask is not None: os.umask(umask)
def dropPrivileges(): nobody = pwd.getpwnam('nobody') adm = grp.getgrnam('adm') os.setgroups([adm.gr_gid]) os.setgid(adm.gr_gid) os.setuid(nobody.pw_uid)
def daemonize(username=""): if os.fork() != 0: os._exit(0) os.setsid() if username: uid = pwd.getpwnam(username)[2] os.setuid(uid) if os.fork() != 0: os._exit(0) # create the pidfile pidfile = file(settings.PIDFILE, "w") pidfile.write("%d\n" % os.getpid()) pidfile.close() # register a cleanup callback pidfile = os.path.abspath(settings.PIDFILE) def delpidfile(): os.remove(pidfile) atexit.register(delpidfile) def delpidfileonSIGTERM(a, b): sys.exit() signal.signal(signal.SIGTERM, delpidfileonSIGTERM) # os.chdir("/") f = os.open(os.devnull, os.O_RDONLY) os.dup2(f, sys.stdin.fileno()) os.close(f) f = os.open(os.devnull, os.O_WRONLY) os.dup2(f, sys.stdout.fileno()) os.close(f) f = os.open(os.devnull, os.O_WRONLY) os.dup2(f, sys.stderr.fileno()) os.close(f)
def setup_container_users(): r""" Create container users and setup SSH access. """ log.info("setting up users in the containter") check_call("addgroup --gid {GID} {group}") check_call("adduser --uid {server_ID} --ingroup {group} --gecos '' " "--disabled-password {server}") check_call("adduser --uid {worker_ID} --ingroup {group} --gecos '' " "--disabled-password {worker}") shome = os.path.join("/home", users["server"]) whome = os.path.join("/home", users["worker"]) os.chdir(shome) os.setegid(users["GID"]) os.seteuid(users["server_ID"]) os.mkdir(".ssh", 0o700) check_call("ssh-keygen -q -N '' -f .ssh/id_rsa") os.chdir(whome) os.setuid(0) os.seteuid(users["worker_ID"]) os.mkdir(".ssh", 0o700) files_to_lock = ".ssh .bashrc .bash_profile .bash_logout .profile" check_call("touch " + files_to_lock) os.setuid(0) shutil.copy2(os.path.join(shome, ".ssh/id_rsa.pub"), ".ssh/authorized_keys") os.chown(".ssh/authorized_keys", users["worker_ID"], users["GID"]) # Get the localhost in the known_hosts file. check_call("su -l {server} -c " "'ssh -q -oStrictHostKeyChecking=no {worker}@localhost whoami'") for f in files_to_lock.split(): check_call("chattr -R +i " + f)
def run(self): self.logger.info("Starting Snort alert processor main thread...") try: os.setuid(int(self.options.uid)) except OSError: self.logger.error("Could not change user for Snort alert processor") return try: os.remove(self.options.unsock) except OSError: pass self.queue_processor.start() self.logger.debug("Binding UNIX socket for Snort alerts at " + self.options.unsock) try: self.server = SnortAlertServer(self.logger, self.options.unsock, SnortAlertHandler) self.server.serve_forever() except: self.logger.error("Could not start Snort processor (detailed log message follows):") self.logger.error(sys.exc_info()) sys.exc_clear() self.stop()
def main(): if args.group and len(args.group) > 0: gid = grp.getgrnam(args.group[0]) os.setgid(gid[2]) if args.user and len(args.user) > 0: print("Switching to user %s" % args.user[0]) uid = pwd.getpwnam(args.user[0])[2] os.setuid(uid) global pending pubsub = PubSubClient() pubsub.url = config.get("Servers", "pubsub") pubsub.start() logging.warn("Service restarted, checking for updates in all tracked repos") for option in config.options("Tracking"): repo = config.get("Tracking", option) path = option pending[repo] = path while True: updatePending() time.sleep(3)
def daemonize(keepfd=None, chdir='/'): os.umask(0) if chdir: os.chdir(chdir) else: os.chdir('/') os.setgid(os.getgid()) # relinquish elevations os.setuid(os.getuid()) # relinquish elevations # Double fork to daemonize if os.fork() > 0: os._exit(0) # Parent exits os.setsid() # Obtain new process group if os.fork() > 0: os._exit(0) # Parent exits # Signal handling signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) # Close open files maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if maxfd == resource.RLIM_INFINITY: maxfd = 256 for fd in reversed(range(maxfd)): try: if fd != keepfd: os.close(fd) except OSError: _, exc, _ = sys.exc_info() if exc.errno != errno.EBADF: raise # Redirect I/O to /dev/null os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno()) os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno()) os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
def start(self): super(Web, self).start() # Steps taken from http://www.faqs.org/faqs/unix-faq/programmer/faq/ # Section 1.7 if self.options.ensure_value("fork", None): # fork() so the parent can exit, returns control to the command line # or shell invoking the program. if os.fork(): os._exit(0) # setsid() to become a process group and session group leader. os.setsid() # fork() again so the parent, (the session group leader), can exit. if os.fork(): os._exit(0) # chdir() to esnure that our process doesn't keep any directory in # use that may prevent a filesystem unmount. import deluge.configmanager os.chdir(deluge.configmanager.get_config_dir()) if self.options.pidfile: open(self.options.pidfile, "wb").write("%d\n" % os.getpid()) if self.options.ensure_value("group", None): if not self.options.group.isdigit(): import grp self.options.group = grp.getgrnam(self.options.group)[2] os.setuid(self.options.group) if self.options.ensure_value("user", None): if not self.options.user.isdigit(): import pwd self.options.user = pwd.getpwnam(self.options.user)[2] os.setuid(self.options.user) import server self.__server = server.DelugeWeb() if self.options.base: self.server.base = self.options.base if self.options.port: self.server.port = self.options.port if self.options.ensure_value("ssl", None): self.server.https = self.options.ssl if self.options.profile: import hotshot hsp = hotshot.Profile( deluge.configmanager.get_config_dir("deluge-web.profile")) hsp.start() self.server.install_signal_handlers() self.server.start() if self.options.profile: hsp.stop() hsp.close() import hotshot.stats stats = hotshot.stats.load( deluge.configmanager.get_config_dir("deluge-web.profile")) stats.strip_dirs() stats.sort_stats("time", "calls") stats.print_stats(400)
def set_ids(): os.setgid(user_gid) os.setuid(user_uid)
def f(): os.setuid(os.getuid()) return os.getuid()
def start_services(extras=None): """Sends start signals to the required services through D-Bus.""" import dbus os.setuid(0) try: bus = dbus.SystemBus() except dbus.DBusException: UI.error(_("Cannot connect to DBus, services won't be started")) return if extras: # Start only the services given in extras for service in extras: try: manage_service(service, "start") except dbus.DBusException: pass else: # Start network service first try: manage_service("NetworkManager", "ready") except Exception, error: UI.warn(_("Unable to start network:\n %s") % error) # Almost everything depends on logger, so start manually manage_service("rsyslog", "start") if not wait_bus("/dev/log", stream=False, timeout=15): UI.warn(_("Cannot start system logger")) # Mount remote filesystems if any mount_remote_filesystems() if not CONFIG.get("safe"): UI.info(_("Starting services")) services = get_service_list(bus) # Remove already started services services = set(services).difference(["rsyslog", "NetworkManager"]) # Give login screen a headstart head_start = CONFIG.get("head_start") run_head_start = head_start and head_start in services # Decide whether we'll stop plymouth or not stop_plymouth = "off" in get_kernel_option("xorg") or \ not run_head_start if run_head_start: manage_service(head_start, "ready") services.remove(head_start) # Run other services for service in services: manage_service(service, "ready") if stop_plymouth: # Stop plymouth SPLASH.quit(retain_splash=False) # Close the handle bus.close()
def shed_privileges(): if gid is not None: os.setgid(gid) if uid is not None: os.setuid(uid)
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info path = dir + '/' + rest i = path.find('/', len(dir) + 1) while i >= 0: nextdir = path[:i] nextrest = path[i + 1:] scriptdir = self.translate_path(nextdir) if os.path.isdir(scriptdir): dir, rest = nextdir, nextrest i = path.find('/', len(dir) + 1) else: break # find an explicit query string, if present. rest, _, query = rest.partition('?') # dissect the part after the directory name into a script name & # a possible additional path, to be stored in PATH_INFO. i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(HTTPStatus.NOT_FOUND, "No such CGI script (%r)" % scriptname) return if not os.path.isfile(scriptfile): self.send_error(HTTPStatus.FORBIDDEN, "CGI script is not a plain file (%r)" % scriptname) return ispy = self.is_python(scriptname) if self.have_fork or not ispy: if not self.is_executable(scriptfile): self.send_error( HTTPStatus.FORBIDDEN, "CGI script is not executable (%r)" % scriptname) return # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html # XXX Much of the following could be prepared ahead of time! env = copy.deepcopy(os.environ) env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD'] = self.command uqrest = urllib.parse.unquote(rest) env['PATH_INFO'] = uqrest env['PATH_TRANSLATED'] = self.translate_path(uqrest) env['SCRIPT_NAME'] = scriptname env['QUERY_STRING'] = query env['REMOTE_ADDR'] = self.client_address[0] authorization = self.headers.get("authorization") if authorization: authorization = authorization.split() if len(authorization) == 2: import base64, binascii env['AUTH_TYPE'] = authorization[0] if authorization[0].lower() == "basic": try: authorization = authorization[1].encode('ascii') authorization = base64.decodebytes(authorization).\ decode('ascii') except (binascii.Error, UnicodeError): pass else: authorization = authorization.split(':') if len(authorization) == 2: env['REMOTE_USER'] = authorization[0] # XXX REMOTE_IDENT if self.headers.get('content-type') is None: env['CONTENT_TYPE'] = self.headers.get_content_type() else: env['CONTENT_TYPE'] = self.headers['content-type'] length = self.headers.get('content-length') if length: env['CONTENT_LENGTH'] = length referer = self.headers.get('referer') if referer: env['HTTP_REFERER'] = referer accept = self.headers.get_all('accept', ()) env['HTTP_ACCEPT'] = ','.join(accept) ua = self.headers.get('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = filter(None, self.headers.get_all('cookie', [])) cookie_str = ', '.join(co) if cookie_str: env['HTTP_COOKIE'] = cookie_str # XXX Other HTTP_* headers # Since we're setting the env in the parent, provide empty # values to override previously set values for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH', 'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'): env.setdefault(k, "") self.send_response(HTTPStatus.OK, "Script output follows") self.flush_headers() decoded_query = query.replace('+', ' ') if self.have_fork: # Unix -- fork as we should args = [script] if '=' not in decoded_query: args.append(decoded_query) nobody = nobody_uid() self.wfile.flush() # Always flush before forking pid = os.fork() if pid != 0: # Parent pid, sts = os.waitpid(pid, 0) # throw away additional data [see bug #427345] while select.select([self.rfile], [], [], 0)[0]: if not self.rfile.read(1): break exitcode = os.waitstatus_to_exitcode(sts) if exitcode: self.log_error(f"CGI script exit code {exitcode}") return # Child try: try: os.setuid(nobody) except OSError: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) os.execve(scriptfile, args, env) except: self.server.handle_error(self.request, self.client_address) os._exit(127) else: # Non-Unix -- use subprocess import subprocess cmdline = [scriptfile] if self.is_python(scriptfile): interp = sys.executable if interp.lower().endswith("w.exe"): # On Windows, use python.exe, not pythonw.exe interp = interp[:-5] + interp[-4:] cmdline = [interp, '-u'] + cmdline if '=' not in query: cmdline.append(query) self.log_message("command: %s", subprocess.list2cmdline(cmdline)) try: nbytes = int(length) except (TypeError, ValueError): nbytes = 0 p = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if self.command.lower() == "post" and nbytes > 0: data = self.rfile.read(nbytes) else: data = None # throw away additional data [see bug #427345] while select.select([self.rfile._sock], [], [], 0)[0]: if not self.rfile._sock.recv(1): break stdout, stderr = p.communicate(data) self.wfile.write(stdout) if stderr: self.log_error('%s', stderr) p.stderr.close() p.stdout.close() status = p.returncode if status: self.log_error("CGI script exit status %#x", status) else: self.log_message("CGI script exited OK")
def setuid(uid): """Version of :func:`os.setuid` supporting usernames.""" os.setuid(parse_uid(uid))
#!/usr/bin/python # -*- coding: utf-8 -*- try: import pwd import os os.setgid(pwd.getpwnam('apache').pw_gid) os.setuid(pwd.getpwnam('apache').pw_uid) except: pass import sys import os from multiprocessing import freeze_support, Manager, Pool import X.settings BASE_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(BASE_DIR) X.settings.DEBUG = False os.environ['DJANGO_SETTINGS_MODULE'] = 'X.settings' def start_channle_process(pid, req_queue, rsp_queue, interval): from sms.serv.smsmanager import ChannleProcess p = ChannleProcess(pid, req_queue, rsp_queue, interval) p.run() def start_daemon_process(req_queue, rsp_queue, interval, main=False):
def _proc_setup(): if pwrec: os.setgid(pwrec.pw_gid) os.setuid(pwrec.pw_uid)
def preexec(self): """Setuid in subprocess right before command is invoked.""" if self.run_as != 'root': os.setuid(_getuid(self.run_as))
def main(): parser = optparse.OptionParser() parser.add_option("-v", action = "store_true", dest = "version", default = "", help = "show version number") parser.add_option("-i", dest = "interface", default = "", help = "set listen interface (default: 0.0.0.0)") parser.add_option("-p", dest = "port", default = "8022", help = "set listen port (default: 8022)") parser.add_option("-c", dest = "cmd", default = None, help = "set shell command (default: ssh localhost)") parser.add_option("-t", dest = "term", default = "xterm-color", help = "set terminal emulation string (default: xterm-color)") parser.add_option("-l", action = "store_true", dest = "log", default = 0, help = "output connection log to stderr (default: quiet)") parser.add_option("-d", action = "store_true", dest = "daemon", default = 0, help = "run as daemon in the background") parser.add_option("-P", dest = "pidfile", default = "/var/run/webshell.pid", help = "set pidfile (default: /var/run/webshell.pid)") parser.add_option("-u", dest = "uid", help = "set daemon user id") parser.add_option("--ssl-disable", action = "store_false", dest = "ssl_enabled", default = 1, help = "disable SSL, set listen interface to localhost") parser.add_option("--ssl-cert", dest = "ssl_cert", default = "webshell.pem", help = "set SSL certificate file (default: webshell.pem)") parser.add_option("--www-dir", dest = "www_dir", default = "www", help = "set WebShell www path (default: www)") (o, a) = parser.parse_args() if o.version: print 'WebShell ' + version sys.exit(0) # Parameter validation try: o.port = int(o.port) except ValueError: print 'Invalid parameters' sys.exit(0) if (not openssl_installed) & o.ssl_enabled: print 'The python SSL extensions seem to be not installed.' print 'You can run WebShell without SSL encryption with the --ssl-disable command line switch.' sys.exit(0) if not o.ssl_enabled: if len(o.interface) == 0: o.interface='localhost' # Daemon mode if o.daemon: pid = os.fork() if pid == 0: # os.setsid() ? os.setpgrp() nullin = file('/dev/null', 'r') nullout = file('/dev/null', 'w') os.dup2(nullin.fileno(), sys.stdin.fileno()) os.dup2(nullout.fileno(), sys.stdout.fileno()) os.dup2(nullout.fileno(), sys.stderr.fileno()) if os.getuid() == 0 and o.uid: try: os.setuid(int(o.uid)) except: os.setuid(pwd.getpwnam(o.uid).pw_uid) else: try: file(o.pidfile, 'w+').write(str(pid) + '\n') except: pass sys.exit(0) # Run server try: server_address = (o.interface, o.port) httpd = SecureHTTPServer(server_address, WebShellRequestHandler, o.cmd, o.term, o.ssl_enabled, o.ssl_cert, o.www_dir) if httpd.socket is None: print 'There is a problem with OpenSSL. Make sure the certificates\' path and content are correct.' sys.exit(0) sa = httpd.socket.getsockname() if not o.daemon: scheme = 'http' if o.ssl_enabled: scheme += 's' print 'WebShell (%s) at %s, port %s' % (scheme, sa[0], sa[1]) httpd.serve_forever() except KeyboardInterrupt: httpd.stop() print 'Stopped'
def result(): report_ids('starting demotion') os.setgroups(user_groups) os.setgid(user_gid) os.setuid(user_uid) report_ids('finished demotion')
try: pwd.getpwnam(username) return True except KeyError: return False def does_uid_exist(uid): try: pwd.getpwuid(uid) return True except KeyError: return False if __name__ == '__main__': if HOST_UID != os.geteuid(): if not does_uid_exist(HOST_UID): username = HOST_USER while does_username_exist(username): username += '0' home_dir = '/home/%s' % username subprocess.check_call([ 'useradd', '-d', home_dir, '-m', username, '-u', str(HOST_UID) ]) os.environ['HOME'] = '/home/%s' % pwd.getpwuid(HOST_UID).pw_name os.setuid(HOST_UID) os.execvp(sys.argv[1], sys.argv[1:])
# Become nobody classname = options.classname if "." in classname: lastdot = classname.rfind(".") mod = __import__(classname[:lastdot], globals(), locals(), [""]) classname = classname[lastdot + 1:] else: import __main__ as mod class_ = getattr(mod, classname) proxy = class_((options.localhost, options.localport), (options.remotehost, options.remoteport)) if options.setuid: try: import pwd except ImportError: print >> sys.stderr, \ 'Cannot import module "pwd"; try running with -n option.' sys.exit(1) nobody = pwd.getpwnam('nobody')[2] try: os.setuid(nobody) except OSError, e: if e.errno != errno.EPERM: raise print >> sys.stderr, \ 'Cannot setuid "nobody"; try running with -n option.' sys.exit(1) try: asyncore.loop() except KeyboardInterrupt: pass
# -*- coding: utf-8 -*- # coding:utf-8 import os import time import threading import base as Base import master as Judge import tdmaker as TdMaker os.setuid(1000) __author__ = 'lancelrq' def JudegService(): Base.log("[Judgement]评测机服务已经启动!") while (True and (not Judge.safeExit)): Judge.work() time.sleep(1) Base.log("评测服务...[OK]") def tdmaker(): Base.log("[TDMaker]测试数据生成器服务已经启动!") while True and (not TdMaker.safeExit): TdMaker.work() time.sleep(3) Base.log("测试数据生成器服务...[OK]") if __name__ == '__main__':
def switch_uid_gid(): if gid is not None: os.setgid(gid) if uid is not None: os.setuid(uid)
def main(): parser = optparse.OptionParser() parser.add_option( "-n", "--hostname", dest="ip", default="localhost", help="Set the hostname on which to listen for connections") parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option( "-c", "--command", dest="cmd", default=None, help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log", default=0, help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-P", "--pidfile", dest="pidfile", default="/var/run/ajaxterm.pid", help="set the pidfile (default: /var/run/ajaxterm.pid)") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html", help="default index file (default: ajaxterm.html)") parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id") parser.add_option( "-s", "--serverport", dest="serverport", help="Use a different port than 22 to connect to the ssh server") (o, a) = parser.parse_args() if o.daemon: pid = os.fork() if pid == 0: #os.setsid() ? os.setpgrp() nullin = file('/dev/null', 'r') nullout = file('/dev/null', 'w') os.dup2(nullin.fileno(), sys.stdin.fileno()) os.dup2(nullout.fileno(), sys.stdout.fileno()) os.dup2(nullout.fileno(), sys.stderr.fileno()) if os.getuid() == 0 and o.uid: try: os.setuid(int(o.uid)) except: os.setuid(pwd.getpwnam(o.uid).pw_uid) else: try: file(o.pidfile, 'w+').write(str(pid) + '\n') except: pass print 'AjaxTerm at http://%s:%s/ pid: %d' % (o.ip, o.port, pid) sys.exit(0) else: print 'AjaxTerm at http://%s:%s/' % (o.ip, o.port) at = AjaxTerm(o.cmd, o.index_file, o.serverport) # f=lambda:os.system('firefox http://localhost:%s/&'%o.port) # qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None) try: qweb.QWebWSGIServer(at, ip=o.ip, port=int(o.port), threaded=0, log=o.log).serve_forever() except KeyboardInterrupt, e: sys.excepthook(*sys.exc_info())
def _pre_exec(): # TODO: Look at the security of this very, very carefully os.setgid(uid) os.setuid(uid)
def _changeUid(): try: os.setuid(threadLocal.uid) except Exception: logger.warn("can not switch user for running command.")
def grab_privileges(): try: os.setuid(0) os.setgid(0) except Exception: pass
def main(argv): """ Run the program. """ # Set up logging. See the logging module docs. logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(message)s", level=logging.INFO) # Parse command-line arguments. Make sure to give our docstring as program # help. parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("configFile", type=argparse.FileType("r"), help="configuration file of hosts to read") parser.add_argument("--noWait", action="store_true", help="look up dynamic peers once and exit") parser.add_argument("--adminInfo", help="use this file to load the cjdns admin password") # Parse all the command-line arguments options = parser.parse_args(argv[1:]) while True: try: # Connect to the router, using the specified admin info file, if # given. cjdns = connectWithAdminInfo(path=options.adminInfo) break except socket.error: # Connection probably refused. Retry in a bit logging.error("Error connecting to cjdns. Retrying in 1 minute...") time.sleep(60) # Drop root if we have it. We can't do it before we load the admin info # file, for the use case where that file is root-only. try: # Switch group to nogroup os.setgid(grp.getgrnam("nogroup").gr_gid) # Switch user to nobody os.setuid(pwd.getpwnam("nobody").pw_uid) # Announce we dropped privs logging.info("Dropped privileges: running as {}:{}".format( pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0])) except (OSError, KeyError): # Complain we couldn't drop privs right logging.warning("Could not drop privileges: running as {}:{}".format( pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0])) # Now we can load the config file. It is now required. # Maker a new parser to parse the config file parsedConfig = ConfigParser.SafeConfigParser() # Be case sensitive parsedConfig.optionxform = str # Read the config from the file parsedConfig.readfp(options.configFile) # Make a new watcher on the cjdroute connection, with the config from the # config file. This automatically looks up all the peers and tries to # connect to them once. watcher = DynamicEndpointWatcher(cjdns, parsedConfig) if options.noWait or os.environ.get('nowait', False): # We're not supposed to wait. Quit while we're ahead sys.exit(0) else: # Monitor for unresponsive nodes. This will loop until cjdns restarts, # at which point it will throw an exception. watcher.run()
def start(foreground, root, config_file): """ Run the Wazuh API. If another Wazuh API is running, this function fails. The `stop` command should be used first. This function exits with 0 if success or 2 if failed because the API was already running. Arguments --------- foreground : bool If the API must be daemonized or not root : bool If true, the daemon is run as root. Normally not recommended for security reasons config_file : str Path to the API config file """ configuration.api_conf.update(configuration.read_yaml_config(config_file=args.config_file)) api_conf = configuration.api_conf cors = api_conf['cors'] log_path = api_conf['logs']['path'] ssl_context = None if api_conf['https']['enabled'] and os.path.exists(api_conf['https']['key']) and \ os.path.exists(api_conf['https']['cert']): try: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS) if api_conf['https']['use_ca']: ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.load_verify_locations(api_conf['https']['ca']) ssl_context.load_cert_chain(certfile=api_conf['https']['cert'], keyfile=api_conf['https']['key']) except ssl.SSLError as e: raise APIError(2003, details='Private key does not match with the certificate') except OSError as e: if e.errno == 22: raise APIError(2003, details='PEM phrase is not correct') # Drop privileges to ossec if not root: if api_conf['drop_privileges']: os.setgid(common.ossec_gid()) os.setuid(common.ossec_uid()) # Foreground/Daemon if not foreground: print(f"Starting API in background") pyDaemonModule.pyDaemon() pyDaemonModule.create_pid('wazuh-apid', os.getpid()) set_logging(log_path=log_path, debug_mode=api_conf['logs']['level'], foreground_mode=args.foreground) # set correct permissions on api.log file if os.path.exists(os.path.join(common.ossec_path, log_path)): os.chown(os.path.join(common.ossec_path, log_path), common.ossec_uid(), common.ossec_gid()) os.chmod(os.path.join(common.ossec_path, log_path), 0o660) # Load the SPEC file into memory to use as a reference for future calls wazuh.security.load_spec() asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) app = connexion.AioHttpApp(__name__, host=api_conf['host'], port=api_conf['port'], specification_dir=os.path.join(api_path[0], 'spec'), options={"swagger_ui": False, 'uri_parser_class': APIUriParser}, only_one_api=True ) app.add_api('spec.yaml', arguments={'title': 'Wazuh API', 'protocol': 'https' if api_conf['https']['enabled'] else 'http', 'host': api_conf['host'], 'port': api_conf['port'] }, strict_validation=True, validate_responses=True, pass_context_arg_name='request', options={"middlewares": [response_postprocessing, set_user_name, security_middleware]}) # Enable CORS if cors['enabled']: cors = aiohttp_cors.setup(app.app, defaults={ cors['source_route']: aiohttp_cors.ResourceOptions( expose_headers=cors['expose_headers'], allow_headers=cors['allow_headers'], allow_credentials=cors['allow_credentials'] ) }) # Configure CORS on all endpoints. for route in list(app.app.router.routes()): cors.add(route) # Enable cache plugin setup_cache(app.app) # Enable swagger UI plugin setup_swagger(app.app, ui_version=3, swagger_url='/ui', swagger_from_file=os.path.join(app.specification_dir, 'spec.yaml')) # Configure https if api_conf['https']['enabled']: # Generate SSC if it does not exist and HTTPS is enabled if not os.path.exists(api_conf['https']['key']) or \ not os.path.exists(api_conf['https']['cert']): logger = logging.getLogger('wazuh') logger.info('HTTPS is enabled but cannot find the private key and/or certificate. ' 'Attempting to generate them.') private_key = generate_private_key(api_conf['https']['key']) logger.info(f"Generated private key file in WAZUH_PATH/{to_relative_path(api_conf['https']['key'])}.") generate_self_signed_certificate(private_key, api_conf['https']['cert']) logger.info(f"Generated certificate file in WAZUH_PATH/{to_relative_path(api_conf['https']['cert'])}.") if ssl_context is None: try: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS) if api_conf['https']['use_ca']: ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.load_verify_locations(api_conf['https']['ca']) ssl_context.load_cert_chain(certfile=api_conf['https']['cert'], keyfile=api_conf['https']['key']) except ssl.SSLError: raise APIError(2003, details='Private key does not match with the certificate') except IOError: raise APIError(2003, details='Please, ensure if path to certificates is correct in the configuration ' f'file WAZUH_PATH/{to_relative_path(CONFIG_FILE_PATH)}') app.run(port=api_conf['port'], host=api_conf['host'], ssl_context=ssl_context, access_log_class=alogging.AccessLogger, use_default_access_log=True )
def result(): """ Set UID and GID attributes """ os.setgid(user_gid) os.setuid(user_id)
gid = None if type(UID) == type(""): uid = pwd.getpwnam(UID)[2] gid = pwd.getpwnam(UID)[3] elif type(UID) == type(1): uid = pwd.getpwuid(UID)[2] gid = pwd.getpwuid(UID)[3] else: raise KeyError try: if gid is not None: try: os.setgid(gid) except OSError: pass os.setuid(uid) except OSError: pass except KeyError: zLOG.LOG("z2", zLOG.ERROR, ("can't find UID %s" % UID)) except: pass # if it hasn't failed at this point, create a .pid file. if not READ_ONLY: pf = open(PID_FILE, 'w') pid = str(os.getpid()) try: pid = str(os.getppid()) + ' ' + pid except: pass
def preexec(): os.setgid(passwd.pw_gid) os.setuid(uid)
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option( "-c", "--command", dest="cmd", default=None, help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log", default=0, help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-P", "--pidfile", dest="pidfile", default="/var/run/achilterm.pid", help="set the pidfile (default: /var/run/achilterm.pid)") parser.add_option("-i", "--index", dest="index_file", default="achilterm.html", help="default index file (default: achilterm.html)") parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id") (o, a) = parser.parse_args() if o.daemon: pid = os.fork() if pid == 0: #os.setsid() ? os.setpgrp() nullin = file('/dev/null', 'r') nullout = file('/dev/null', 'w') os.dup2(nullin.fileno(), sys.stdin.fileno()) os.dup2(nullout.fileno(), sys.stdout.fileno()) os.dup2(nullout.fileno(), sys.stderr.fileno()) if os.getuid() == 0 and o.uid: try: os.setuid(int(o.uid)) except: os.setuid(pwd.getpwnam(o.uid).pw_uid) else: try: file(o.pidfile, 'w+').write(str(pid) + '\n') except: pass print 'AchilTerm at http://localhost:%s/ pid: %d' % (o.port, pid) sys.exit(0) else: print 'AchilTerm at http://localhost:%s/' % o.port at = AchilTerm(o.cmd, o.index_file) try: wsgiref.simple_server.make_server('localhost', int(o.port), at).serve_forever() except KeyboardInterrupt, e: sys.excepthook(*sys.exc_info())
if not os.path.exists(parent): os.makedirs(parent) self.chown(parent) def set_uid(self): """Drop root privileges""" if self.gid: try: os.setgid(self.gid) except OSError, (code, message): sys.exit("can't setgid(%d): %s, %s" % (self.gid, code, message)) if self.uid: try: os.setuid(self.uid) except OSError, (code, message): sys.exit("can't setuid(%d): %s, %s" % (self.uid, code, message)) def chown(self, fn): """Change the ownership of a file to match the daemon uid/gid""" if self.uid or self.gid: uid = self.uid if not uid: uid = os.stat(fn).st_uid gid = self.gid if not gid: gid = os.stat(fn).st_gid try:
os.setgid(group.gr_gid) if user.pw_uid == os.getuid(): return groups = [group.gr_gid] maxgroups = os.sysconf('SC_NGROUPS_MAX') for group, password, lgid, users in grp.getgrall(): if user.pw_name in users: groups.append(lgid) if len(groups) >= maxgroups: break unset = True while unset: try: os.setgroups(groups) except ValueError: if len(groups) > 1: del groups[-1] else: raise RuntimeError('failed to set group access list') except OSError, exception: if exception.args[0] == errno.EINVAL and len(groups) > 1: del groups[-1] else: raise RuntimeError('failed to set group access list') else: unset = False else: os.setuid(user.pw_uid)
def _change_uid(self): try: if self._threadLocal is not None: os.setuid(self._threadLocal.uid) except Exception: _logger.warn("can not switch user for running command.")
None, None, ['']).WSGIServer flup_app = wsgi_app if options.unquote: from trac.web.fcgi_frontend import FlupMiddleware flup_app = FlupMiddleware(flup_app) ret = server_cls(flup_app, bindAddress=server_address).run() sys.exit(42 if ret else 0) # if SIGHUP exit with status 42 try: if options.daemonize: daemon.daemonize(pidfile=options.pidfile, progname='tracd', umask=options.umask) if options.group is not None: os.setgid(options.group) if options.user is not None: os.setuid(options.user) if options.autoreload: def modification_callback(file): print >> sys.stderr, 'Detected modification of %s, ' \ 'restarting.' % file autoreload.main(serve, modification_callback) else: serve() except OSError, e: print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) sys.exit(1) except KeyboardInterrupt: pass