コード例 #1
0
 def _process_securely(self, operation, path, request, *args, **kw):
     user = request.user_object()
     groups = os.getgroups()
     is_root = not os.getuid()
     uid = os.geteuid()
     gid = os.getegid()
     if not is_root:
         msg = (
             "Framework is not running as root so effective uid "
             "and gid are not being changed prior to doing %s: "
             "%s" % (request.get_command(), path)
         )
         msglog.log("FileRequestHandler", msglog.types.WARN, msg)
     else:
         if self.debug:
             msg = "%s command: file %s, user %s" % (request.get_command(), path, user.name())
             msglog.log(self.name, msglog.types.DB, msg)
         os.setgroups(user.group_ids())
         os.setegid(user.gid())
         os.seteuid(user.uid())
     try:
         result = operation(path, request, *args, **kw)
     finally:
         if is_root:
             os.seteuid(uid)
             os.setegid(gid)
             os.setgroups(groups)
     return result
コード例 #2
0
ファイル: nxScript.py プロジェクト: AMDmi3/WPSDSCLinux
 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)
コード例 #3
0
ファイル: test_posix2.py プロジェクト: abhinavthomas/pypy
 def test_os_setgroups(self):
     os = self.posix
     raises(TypeError, os.setgroups, [2, 5, "hello"])
     try:
         os.setgroups(os.getgroups())
     except OSError:
         pass
コード例 #4
0
ファイル: server.py プロジェクト: nask0/poet
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
コード例 #5
0
ファイル: privs.py プロジェクト: jmullins/trpycore
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)
コード例 #6
0
ファイル: main.py プロジェクト: thedavecollins/bucky
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)
コード例 #7
0
ファイル: YamlDaemon.py プロジェクト: paramonov/yaml-server
    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)
コード例 #8
0
ファイル: server.py プロジェクト: rcherbonnier/rql_download
 def _runAsUser(self, f, *args, **kw):
     """ Method to logged-in a user.
     """
     user_is_root = os.getuid() == 0  # for tests
     if user_is_root:
         euid = os.geteuid()
         egid = os.getegid()
         groups = os.getgroups()
         uid, gid = self.getUserGroupId()
         os.setegid(0)
         os.seteuid(0)
         os.setgroups(self.getOtherGroups())
         os.setegid(gid)
         os.seteuid(uid)
     try:
         f = iter(f)
     except TypeError:
         f = [(f, args, kw)]
     try:
         for i in f:
             func = i[0]
             args = len(i) > 1 and i[1] or ()
             kw = len(i) > 2 and i[2] or {}
             r = func(*args, **kw)
     finally:
         if user_is_root:
             os.setegid(0)
             os.seteuid(0)
             os.setgroups(groups)
             os.setegid(egid)
             os.seteuid(euid)
     return r
コード例 #9
0
ファイル: worker.py プロジェクト: HasClass0/ajenti
    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()
        )
コード例 #10
0
    def run(self):
        if not self.runable:
            print 'Process not runable, returning'
            return False

        # Drop privileges
        os.setgroups([])
        os.setgid(self.gid)
        os.setuid(self.uid)

        ppid = os.getppid()
        while True:
            try:
                line = self.work_queue.get(timeout=0.5)
                if not line:
                    'Parent process is asking us to exit'
                    return True
                line = line.decode('utf-8').encode('ASCII', 'ignore')
            except KeyboardInterrupt:
                return False
            except UnicodeDecodeError:
                print 'Unicode Error, skipping entry'
                continue
            except QueueEmpty:
                if os.getppid() != ppid:
                    return False
                continue
            try:
                entry = SyslogEntry.from_line(line)
            except pyparsing.exceptions.Exception:
                continue
            self.process_entry(entry)
コード例 #11
0
ファイル: uploader.py プロジェクト: mindpool/bot-prakasha-ke
 def _runAsUser(self, f, *args, **kw):
     euid = os.geteuid()
     egid = os.getegid()
     groups = os.getgroups()[:16]
     uid, gid = self.getUserGroupId()
     os.setegid(0)
     os.seteuid(0)
     os.setgroups(self.getOtherGroups())
     os.setegid(gid)
     os.seteuid(uid)
     try:
         f = iter(f)
     except TypeError:
         f = [(f, args, kw)]
     try:
         for i in f:
             func = i[0]
             args = len(i)>1 and i[1] or ()
             kw = len(i)>2 and i[2] or {}
             r = func(*args, **kw)
     finally:
         os.setegid(0)
         os.seteuid(0)
         os.setgroups(groups)
         os.setegid(egid)
         os.seteuid(euid)
     return r
コード例 #12
0
ファイル: daemon.py プロジェクト: Acidburn0zzz/Tor2web-3.0
    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.rundir, c_uid, c_gid)
            os.chown(self.config.pidfile, c_uid, c_gid)

            for item in glob.glob(self.config.rundir + '/*'):
                os.chown(item, c_uid, c_gid)

            os.setgid(c_gid)
            os.setgroups(c_groups)
            os.setuid(c_uid)
コード例 #13
0
def drop_privileges(uid_name, gid_name):

    # We're not root, so everythings fine then..
    if os.getuid() != 0:
        return

    # Get the uid/gid from the name
    try:
        running_uid = pwd.getpwnam(uid_name).pw_uid
    except KeyError:
        e = 'Unable to drop privileges. No such user: {}'.format(uid_name)
        logger.critical(e)
        exit(e)
    try:
        running_gid = grp.getgrnam(gid_name).gr_gid
    except KeyError:
        e = 'Unable to drop privileges. No such group: {}'.format(gid_name)
        logger.critical(e)
        exit(e)

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(running_gid)
    os.setuid(running_uid)

    # Ensure a very conservative umask
    old_umask = os.umask(077)
コード例 #14
0
ファイル: knock-server.py プロジェクト: DanielSel/knock
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)
コード例 #15
0
ファイル: watchdog.py プロジェクト: etherparty/syndicate
def release_privileges( uid_name, gid_name ):
   
   if os.getuid() != 0:
      # not root, so nothing to do
      return 0
   
   # get desired uid/gid 
   try:
      running_pwd = pwd.getpwnam( uid_name )
      running_uid = running_pwd.pw_uid 
   except KeyError:
      log.error("No such user '%s'" % uid_name)
      return -errno.EINVAL
   
   try:
      running_grp = grp.getgrnam( gid_name )
      running_gid = running_grp.gr_gid
   except KeyError:
      log.error("No such group '%s'" % gid_name)
      return -errno.EINVAL 
   
   # unset groups 
   os.setgroups( [] )
   
   # set new uid/gid 
   os.setgid( running_gid )
   os.setuid( running_uid )
   
   return 0 
コード例 #16
0
 def __enter__(self):
   if self.uid:
     self.saved_uid = os.geteuid()
     self.saved_groups = os.getgroups()
     if self.uid:
       os.setgroups(self.saved_groups + [AID_INET])
       os.seteuid(self.uid)
コード例 #17
0
ファイル: misc.py プロジェクト: CaineQT/vmcloak
def resolve_parameters(args, defaults, types, drop_user=False):
    s = Configuration()

    if args.recommended_settings:
        s.from_file(os.path.join(VMCLOAK_ROOT, 'data', 'recommended.ini'))

    for settings in args.settings:
        s.from_file(settings)

    s.from_args(args)
    s.from_defaults(defaults)
    s.apply_types(types)

    if s.user and not drop_user:
        try:
            user = pwd.getpwnam(s.user)
            os.setgroups((user.pw_gid,))
            os.setgid(user.pw_gid)
            os.setuid(user.pw_uid)
            os.environ['HOME'] = user.pw_dir
        except KeyError:
            raise Exception('Invalid user specified to drop '
                            'privileges to: %s' % s.user)
        except OSError as e:
            raise Exception('Failed to drop privileges: %s' % e)

        # Resolve the parameters again, but this time without applying the
        # user argument. This way paths that use os.getenv('HOME') will be
        # correct.
        return resolve_parameters(args, defaults, types, drop_user=True)

    return s
コード例 #18
0
ファイル: service.py プロジェクト: ahale/brim
def droppriv(user, group=None, umask=0022):
    """
    Drops privileges to the user, group, and umask given, changes the
    process to session leader, and changes working directories to /.
    If a group is not given, the user's default group will be used.
    Will raise an Exception with an explanatory message if the user
    or group cannot be found or if permission is denied while
    attempting the switch.

    :param user: The user to switch to.
    :param group: The group to switch to; defaults to the default
                  group of the user.
    :param umask: The umask to set; defaults 0022.
    """
    if user or group:
        uid = geteuid()
        try:
            setgroups([])
        except OSError, err:
            if err.errno != EPERM:
                raise
        gid = getegid()
        if user:
            try:
                pw = getpwnam(user)
            except KeyError, err:
                raise Exception('Cannot switch to unknown user %r.' % user)
            uid = pw.pw_uid
            gid = pw.pw_gid
コード例 #19
0
ファイル: utility.py プロジェクト: PisiLinuxNew/comar-api
def changeUID(chuid):
    """Change to this chuid (user:group)"""
    c_user = chuid
    c_group = None
    if ":" in c_user:
        c_user, c_group = c_user.split(":", 1)
    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_group = grp.getgrgid(cpw.pw_gid).gr_name

    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.setgid(c_gid)
    os.setgroups(c_groups)
    os.setuid(c_uid)
コード例 #20
0
def set_user(uid, assign_all_groups):
    try:
        # Get user's default group and set it to current process to make sure
        # file permissions are inherited correctly
        # Solves issue with permission denied for JSON files
        gid = pwd.getpwuid(uid).pw_gid
        import grp
        os.setgid(gid)
        if assign_all_groups:
            # Added lines to assure read/write permission for groups
            user = pwd.getpwuid(uid).pw_name
            groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]

            os.setgroups(groups)
        os.setuid(uid)

    except OSError as e:
        if e.errno == errno.EPERM:
            sys.stderr.write("error: setuid(%d) failed: permission denied. Did you setup 'sudo' correctly for this script?\n" % uid)
            exit(1)
        else:
            pass

    if os.getuid() == 0:
        sys.stderr.write("error: UID is 0 (root) after changing user. This script should not be run as root. aborting.\n")
        exit(1)

    if os.geteuid() == 0:
        sys.stderr.write("error: EUID is 0 (root) after changing user. This script should not be run as root. aborting.\n")
        exit(1)
コード例 #21
0
ファイル: daemon.py プロジェクト: wiiiky/miserable
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)
コード例 #22
0
ファイル: droned-daemon.py プロジェクト: mleinart/droned
    def drop_privileges(self):
        """drop privileges, and terminate the parent process"""
        if self.DAEMONIZED:
            #Child kills parent ... hmm sounds like a greek tragedy.
            os.kill(self.parentPid, signal.SIGTERM)
            self.parentPid = 0 #just in case

        if os.getuid() != 0:
            # We're not root so, like, whatever dude
            return

        import config
        import grp
        import pwd
        # Get the uid/gid from the name
        running_uid = pwd.getpwnam(config.DRONED_USER).pw_uid
        running_gid = grp.getgrnam(config.DRONED_GROUP).gr_gid
        self.log('set uid/gid %d/%d\n' % (running_uid,running_gid))
  
        # Remove group privileges
        os.setgroups([])
  
        # Try setting the new uid/gid
        os.setgid(running_gid)
        os.setuid(running_uid)
        # let services know it is ok to start
        self.reactor.fireSystemEvent('priviledges')
        #prevent this from being called ever again
        self.drop_privileges = lambda: None
コード例 #23
0
ファイル: localpaste.py プロジェクト: kkfong/localpaste
def drop_privileges(uid_name='localpaste'):
    import os, pwd, grp
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        logerror("You cannot drop privileges if you are not root")

        # this isn't really true... if you have CAP_SETUID and CAP_SETGID, you still can, and then you need to drop caps instead
        # TODO: support caps, and allow non-root to use this function
        
        exit(1)

    # Get the uid/gid from the name
    target_user = pwd.getpwnam(uid_name)
    
    target_uid = target_user.pw_uid
    target_gid = target_user.pw_gid

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(target_gid)
    os.setuid(target_uid)

    # Ensure a very conservative umask
    old_umask = os.umask(0o077)
コード例 #24
0
ファイル: namespaces.py プロジェクト: pombredanne/shoebox
    def build(self):
        self.filesystem.check_root_dir()
        resolvconf = self.etc_resolv_conf()

        with self.user_namespace.setup_userns():
            namespaces = CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWIPC | CLONE_NEWUTS | CLONE_NEWPID
            if self.private_net:
                namespaces |= CLONE_NEWNET
                with self.private_net.setup_netns():
                    unshare(namespaces)
            else:
                unshare(namespaces)

        if self.hostname:
            sethostname(self.hostname)

        self.filesystem.build()
        if self.filesystem.special_fs:
            with open('/etc/hosts', 'w') as hosts:
                print >> hosts, self.etc_hosts()

            with open('/etc/resolv.conf', 'w') as resolv:
                print >> resolv, resolvconf

        drop_caps()
        os.setgroups([os.getgid()])
コード例 #25
0
ファイル: verify.py プロジェクト: bemehow/salt
def check_user(user):
    '''
    Check user and assign process uid/gid.
    '''
    if salt.utils.is_windows():
        return True
    if user == getpass.getuser():
        return True
    import pwd  # after confirming not running Windows
    try:
        pwuser = pwd.getpwnam(user)
        try:
            if hasattr(os, 'initgroups'):
                os.initgroups(user, pwuser.pw_gid)
            else:
                os.setgroups(salt.utils.get_gid_list(user, include_default=False))
            os.setgid(pwuser.pw_gid)
            os.setuid(pwuser.pw_uid)

        except OSError:
            msg = 'Salt configured to run as user "{0}" but unable to switch.'
            msg = msg.format(user)
            if is_console_configured():
                log.critical(msg)
            else:
                sys.stderr.write("CRITICAL: {0}\n".format(msg))
            return False
    except KeyError:
        msg = 'User not found: "{0}"'.format(user)
        if is_console_configured():
            log.critical(msg)
        else:
            sys.stderr.write("CRITICAL: {0}\n".format(msg))
        return False
    return True
コード例 #26
0
ファイル: main.py プロジェクト: corinnepritchard/dhcpkit
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))
コード例 #27
0
ファイル: util.py プロジェクト: GeopaymeEE/sqlchain
def drop2user(cfg):
    if ('user' in cfg) and (cfg['user'] != '') and (os.getuid() == 0):
        uid = pwd.getpwnam(cfg['user']).pw_uid
        os.setgroups([])
        os.setgid(uid)
        os.setuid(uid)
        os.umask(077) 
コード例 #28
0
ファイル: drop.py プロジェクト: nbari/my-sandbox
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        return

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_gid = grp.getgrnam(gid_name).gr_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
    new_umask = 0o077
    old_umask = os.umask(new_umask)

    print 'drop_privileges: Old mask: %s, new umask :%s' % \
        (oct(old_umask), oct(new_umask))

    final_uid = os.getuid()
    final_gid = os.getgid()

    print 'drop_privileges: running as %s/%s' % \
        (pwd.getpwuid(final_uid)[0],
         grp.getgrgid(final_gid)[0])
コード例 #29
0
ファイル: daemon.py プロジェクト: Beachy13/Tor2web
    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)
コード例 #30
0
ファイル: utils.py プロジェクト: aligature/GateOne
def drop_privileges(uid='nobody', gid='nogroup', supl_groups=None):
    """
    Drop privileges by changing the current process owner/group to
    *uid*/*gid* (both may be an integer or a string).  If *supl_groups* (list)
    is given the process will be assigned those values as its effective
    supplemental groups.  If *supl_groups* is None it will default to using
    'tty' as the only supplemental group.  Example::

        drop_privileges('gateone', 'gateone', ['tty'])

    This would change the current process owner to gateone/gateone with 'tty' as
    its only supplemental group.

    .. note:: On most Unix systems users must belong to the 'tty' group to create new controlling TTYs which is necessary for 'pty.fork()' to work.

    .. tip:: If you get errors like, "OSError: out of pty devices" it likely means that your OS uses something other than 'tty' as the group owner of the devpts filesystem.  'mount | grep pts' will tell you the owner.
    """
    import pwd, grp
    running_gid = gid
    if not isinstance(uid, int):
        # Get the uid/gid from the name
        running_uid = pwd.getpwnam(uid).pw_uid
    running_uid = uid
    if not isinstance(gid, int):
        running_gid = grp.getgrnam(gid).gr_gid
    if supl_groups:
        for i, group in enumerate(supl_groups):
            # Just update in-place
            if not isinstance(group, int):
                supl_groups[i] = grp.getgrnam(group).gr_gid
        try:
            os.setgroups(supl_groups)
        except OSError, e:
            logging.error(_('Could not set supplemental groups: %s' % e))
            exit()
コード例 #31
0
ファイル: plugins.py プロジェクト: redchillypowder/autosub-1
    def start(self):
        # uid/gid
        def current_ids():
            """Return the current (uid, gid) if available."""
            name, group = None, None
            if pwd:
                name = pwd.getpwuid(os.getuid())[0]
            if grp:
                group = grp.getgrgid(os.getgid())[0]
            return name, group

        if self.finalized:
            if not (self.uid is None and self.gid is None):
                self.bus.log('Already running as uid: %r gid: %r' %
                             current_ids())
        else:
            if self.uid is None and self.gid is None:
                if pwd or grp:
                    self.bus.log('uid/gid not set', level=30)
            else:
                self.bus.log('Started as uid: %r gid: %r' % current_ids())
                if self.gid is not None:
                    os.setgid(self.gid)
                    os.setgroups([])
                if self.uid is not None:
                    os.setuid(self.uid)
                self.bus.log('Running as uid: %r gid: %r' % current_ids())

        # umask
        if self.finalized:
            if self.umask is not None:
                self.bus.log('umask already set to: %03o' % self.umask)
        else:
            if self.umask is None:
                self.bus.log('umask not set', level=30)
            else:
                old_umask = os.umask(self.umask)
                self.bus.log('umask old: %03o, new: %03o' %
                             (old_umask, self.umask))

        self.finalized = True
コード例 #32
0
ファイル: serve.py プロジェクト: cganote/pulsar
 def change_user_group(self, user, group):
     if not user and not group:
         return
     import pwd, grp
     uid = gid = None
     if group:
         try:
             gid = int(group)
             group = grp.getgrgid(gid).gr_name
         except ValueError:
             import grp
             try:
                 entry = grp.getgrnam(group)
             except KeyError:
                 raise BadCommand("Bad group: %r; no such group exists" %
                                  group)
             gid = entry.gr_gid
     try:
         uid = int(user)
         user = pwd.getpwuid(uid).pw_name
     except ValueError:
         try:
             entry = pwd.getpwnam(user)
         except KeyError:
             raise BadCommand("Bad username: %r; no such user exists" %
                              user)
         if not gid:
             gid = entry.pw_gid
         uid = entry.pw_uid
     if self.verbose > 0:
         print('Changing user to %s:%s (%s:%s)' %
               (user, group or '(unknown)', uid, gid))
     if hasattr(os, 'initgroups'):
         os.initgroups(user, gid)
     else:
         os.setgroups(
             [e.gr_gid for e in grp.getgrall() if user in e.gr_mem] + [gid])
     if gid:
         os.setgid(gid)
     if uid:
         os.setuid(uid)
コード例 #33
0
ファイル: tuhi-live.py プロジェクト: whot/tuhi
def drop_privileges():
    sys.stderr.write('dropping privileges\n')

    os.setgroups([])
    gid = int(os.getenv('SUDO_GID'))
    uid = int(os.getenv('SUDO_UID'))
    pwname = os.getenv('SUDO_USER')
    os.setresgid(gid, gid, gid)
    os.initgroups(pwname, gid)
    os.setresuid(uid, uid, uid)

    pw = pwd.getpwuid(uid)
    path = os.environ['PATH']
    display = os.environ['DISPLAY']

    # we completely clear the environment and start a new and controlled one
    os.environ.clear()
    os.environ['XDG_RUNTIME_DIR'] = f'/run/user/{uid}'
    os.environ['HOME'] = pw.pw_dir
    os.environ['PATH'] = path
    os.environ['DISPLAY'] = display
コード例 #34
0
ファイル: config.py プロジェクト: aouyar/pgbarman-code
 def _enforce_user(self):
     '''Set the correct user'''
     try:
         pw = pwd.getpwnam(self.user)
     except:
         msg = "ERROR: the configured user %r does not exists" % self.user
         raise SystemExit(msg)
     if pw.pw_uid == os.getuid():
         return
     try:
         os.setgroups(
             [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem] +
             [pw.pw_gid])
         os.setgid(pw.pw_gid)
         os.setuid(pw.pw_uid)
         os.setegid(pw.pw_gid)
         os.seteuid(pw.pw_uid)
     except:
         msg = "ERROR: please run barman as %r user" % self.user
         raise SystemExit(msg)
     os.environ['HOME'] = pw.pw_dir
コード例 #35
0
def initial_program_setup_root():
    if (cadm_gid == 0):
        print("I am not willing to run in group root")
        os.exit(1)
    if (cadm_uid == 0):
        print("I am not willing to run as root")
        os.exit(1)

    try:
        os.mkdir(lockFileDir)
        os.chown(lockFileDir, cadm_uid, cadm_gid)
    except OSError as err:
        print("cannot mkdir " + lockFileName + " {0}\n)".format(err))

    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigint_handler)

    groups = [997, 999]  # gpio and spi
    os.setgroups(groups)
    os.setgid(cadm_gid)
    os.setuid(cadm_uid)
コード例 #36
0
ファイル: utils.py プロジェクト: vrautela/treadmill-workdir
def drop_privileges(uid_name='nobody'):
    """Drop root privileges."""
    if os.getuid() != 0:
        # We're not root, nothing to do.
        return

    # Get the uid/gid from the name
    (running_uid, _gid) = get_uid_gid(uid_name)

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setuid(running_uid)

    # Ensure a very conservative umask
    os.umask(0o77)

    # TODO: probably redundant, as it will not have access to the
    #                cred cache anyway.
    os.environ['KRB5CCNAME'] = 'FILE:/no_such_krbcc'
コード例 #37
0
    def preexec_fn():
        if runas is not None:
            pent = pwd.getpwnam(runas)

            suplementary_gids = [
                grp.getgrnam(group).gr_gid for group in suplementary_groups
            ]

            root_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):
                    root_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)
コード例 #38
0
def switch_user(name="softwarecollections"):
    """Change the current user to the specified one.

    Keyword arguments:
        name: The name (login) of the user to switch to.
        Must exists on the system.
    """

    user = pwd.getpwnam(name)
    groups = [g.gr_gid for g in grp.getgrall() if user.pw_name in g.gr_mem]

    # Execution context
    os.setgid(user.pw_gid)
    os.setgroups(groups)
    os.setuid(user.pw_uid)

    # Environment
    os.environ.update(USER=user.pw_name,
                      LOGNAME=user.pw_name,
                      HOME=user.pw_dir,
                      SHELL=user.pw_shell)
コード例 #39
0
def drop_privileges(uid_name='alpha', gid_name='alpha'):
    """ Drop privileges of current process to given user and group """

    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        return

    # Get the uid/gid from the name
    pwstruct = pwd.getpwnam(uid_name)
    running_uid = pwstruct.pw_uid
    running_gid = pwstruct.pw_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
    old_umask = os.umask(077)
コード例 #40
0
def drop_privileges(uid_name , gid_name):
    logtime = time.strftime("%Y-%m-%dT%H:%M:%S",time.localtime(time.time())) + str(time.time()-int(time.time()))[1:8]
    eprint(logtime + " [PID " + str(os.getpid()) + "]" + " ...trying to Drop root priviliges...")

    if os.getuid() != 0: # if not root do nothing
        eprint(logtime + " [PID " + str(os.getpid()) + "]" + " ...nothing to do. Running with UID: " + str(os.getuid()) + " GID: "  + str(os.getgid()))
        return

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_gid = grp.getgrnam(gid_name).gr_gid

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(running_gid)
    os.setuid(running_uid)
    eprint(logtime + " [PID " + str(os.getpid()) + "]" + " ...done. Running with UID: "  + str(os.getuid()) + " GID: "  + str(os.getgid()))

    return
コード例 #41
0
def set_user(uid, assign_all_groups):
    try:
        # Get user's default group and set it to current process to make sure file permissions are inherited correctly
        # Solves issue with permission denied for JSON files
        gid = pwd.getpwuid(uid).pw_gid
        import grp
        os.setgid(gid)
        if assign_all_groups:
            # Added lines to assure read/write permission for groups
            user = pwd.getpwuid(uid).pw_name
            groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]

            os.setgroups(groups)
        os.setuid(uid)

    except OSError, e:
        if e.errno == errno.EPERM:
            sys.stderr.write( "error: setuid(%d) failed: permission denied. Did you setup 'sudo' correctly for this script?\n" % uid )
            exit(1)
        else:
            pass
コード例 #42
0
 def demote(self):
     # demote root user to any specified user or group
     try:
         if os.getuid() == 0:
             # drop supplementary groups
             os.setgroups([])
             if self.group:
                 try:
                     os.setgid(self.the_grp.gr_gid)
                 except Exception, ex:
                     logging.critical("failed to set group to \"%s\" [%s]" %
                                      (self.group, str(ex)))
                     sys.exit(1)
             if self.user:
                 try:
                     the_pwd = pwd.getpwnam(self.user)
                     os.setuid(self.the_pwd.pw_uid)
                 except Exception, ex:
                     logging.critical("failed to set user to \"%s\" [%s]" %
                                      (self.user, str(ex)))
                     sys.exit(1)
コード例 #43
0
ファイル: procutils.py プロジェクト: pycopia/devtest
def run_as(pwent, umask=0o22):
    """Drop privileges to given user's password entry, and set up
    environment. Assumes the parent process has root privileges.
    """
    os.umask(umask)
    home = pwent.home
    try:
        os.chdir(home)
    except OSError:
        os.chdir("/")
    # drop privs to user
    os.setgroups(pwent.groups)
    os.setgid(pwent.gid)
    os.setegid(pwent.gid)
    os.setuid(pwent.uid)
    os.seteuid(pwent.uid)
    os.environ["HOME"] = home
    os.environ["USER"] = pwent.name
    os.environ["LOGNAME"] = pwent.name
    os.environ["SHELL"] = pwent.shell
    os.environ["PATH"] = "/bin:/usr/bin:/usr/local/bin"
コード例 #44
0
ファイル: progress.py プロジェクト: sui84/PandorboxPython27
    def _child(self, path):
        # Avoid running lintian as root
        try:
            os.setgroups([self.transaction.gid])
        except OSError:
            pass
        os.setgid(self.transaction.gid)
        os.setuid(self.transaction.uid)

        if platform.dist()[1] == "debian":
            profile = "debian/aptdaemon"
        else:
            profile = "ubuntu/aptdaemon"
        # If HOME isn't set lintian won't try to load user profiles
        os.unsetenv("HOME")

        lintian_path = apt_pkg.config.find_file("Dir::Bin::Lintian",
                                                "/usr/bin/lintian")
        os.execlp(lintian_path, lintian_path, "--no-cfg", "--fail-on-warnings",
                  "--profile", profile, path)
        os._exit(1)
コード例 #45
0
def set_sups(target_sups):
    """
    This is designed to give us a layer of abstraction from the system calls.
    It also accommodates FreeBSD's idiosyncrasy (which is POSIX-compliant) of
    keeping the egid in the supplementary groups list.
    It also makes an effort to not call the setgroups routine if the target
    group list is identical to the current one in force.
    """
    global os_kernel
    if os_kernel == 'FreeBSD':
        target_sups = [os.getegid()] + target_sups
    if os.geteuid() == 0:
        # This will raise an OSError exception if it fails
        os.setgroups(target_sups)
    else:
        cur_sups = get_sups()
        # This will probably fail
        if not eql_sups(cur_sups, target_sups):
            # This will raise an OSError exception if it fails
            os.setgroups(target_sups)
    return True
コード例 #46
0
ファイル: util.py プロジェクト: pearlboy/Static-UPnP
def drop_privileges(self, uid_name, gid_name):
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        self.logger.info("Not running as root. Cannot drop permissions.")
        return

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_gid = grp.getgrnam(gid_name).gr_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
    old_umask = os.umask(0o077)
    self.logger.info("Changed permissions to: %s: %i, %s, %i" %
                     (uid_name, running_uid, gid_name, running_gid))
コード例 #47
0
ファイル: daemon.py プロジェクト: rkialashaki/fuglu
    def drop_privs(self,
                   username='******',
                   groupname='nobody',
                   keep_supplemental_groups=True):
        """Drop privileges of the current process to specified unprivileged user and group. If keep_supplemental_groups is True,
        the process will also be associated with all groups the unprivileged user belongs to.
        """
        try:
            running_uid = pwd.getpwnam(username).pw_uid
            running_gid = grp.getgrnam(groupname).gr_gid
        except Exception:
            raise Exception(
                'Can not drop privileges, user %s or group %s does not exist' %
                (username, groupname))
        new_umask = 0o077
        os.umask(new_umask)

        os.setgid(running_gid)
        if keep_supplemental_groups:
            os.setgroups(self._get_group_ids(username))
        os.setuid(running_uid)
コード例 #48
0
ファイル: daemon.py プロジェクト: nagyistge/kopano-core
def change_process_owner(uid, gid):
    """ Change the owning UID and GID of this process.

        Sets the GID then the UID of the process (in that order, to
        avoid permission errors) to the specified `gid` and `uid`
        values. Requires appropriate OS privileges for this process.

        """
    try:
        # KC custom modification of python-daemon.
        # If we cannot get rid of the groups, leave them.
        try:
            os.setgroups([])
        except Exception as exc:
            pass
        os.setgid(gid)
        os.setuid(uid)
    except Exception as exc:
        error = DaemonOSEnvironmentError(
            "Unable to change process owner (%(exc)s)" % vars())
        raise error
コード例 #49
0
def test_keep_groups():
    if os.getuid() != 0:
        return 77
    oldgroups = os.getgroups()
    out = ""
    try:
        os.setgroups([1, 2, 3, 4, 5])
        conf = base_config()
        conf['process']['args'] = ['/init', 'cat', '/proc/self/status']
        add_all_namespaces(conf)
        conf['annotations'] = {}
        conf['annotations']['run.oci.keep_original_groups'] = "1"
        out, _ = run_and_get_output(conf)
    finally:
        os.setgroups(oldgroups)

    proc_status = parse_proc_status(out)
    ids = proc_status['Groups'].split()
    if len(ids) == 0:
        return -1
    return 0
コード例 #50
0
ファイル: mockmail.py プロジェクト: ziozzang/mockmail
def _dropPrivileges(config, init_chroot=None):
    """ @param init_chroot Callback function to call before creating the chroot """
    uid = None
    if config['dropuser'] is not None:
        uname = config['dropuser']
        gname = config['dropgroup']

        if isinstance(uname, int):
            uid = uname
            if gname is None:
                gname = pwd.getpwuid(uid).pw_gid
        else:
            pw = pwd.getpwnam(uname)
            uid = pw.pw_uid
            if gname is None:
                gname = pw.pw_gid

        if isinstance(gname, int):
            gid = gname
        else:
            gid = grp.getgrnam(gname).gr_gid

    if config['chroot']:
        if config['chroot_mkdir']:
            if not os.path.exists(config['chroot']):
                os.mkdir(config['chroot'], 0o700)

        if config['workarounds']:
            _workaround_preload_codecs()

        os.chroot(config['chroot'])
        os.chdir('/')

    if init_chroot:
        init_chroot()

    if uid is not None:
        os.setgroups([])
        os.setgid(gid)
        os.setuid(uid)
コード例 #51
0
def setuidgid(uid, gid):
    if not POSIX:
        return
    log = get_util_logger()
    if os.getuid()!=uid or os.getgid()!=gid:
        #find the username for the given uid:
        from pwd import getpwuid
        try:
            username = getpwuid(uid).pw_name
        except KeyError:
            raise Exception("uid %i not found" % uid)
        #set the groups:
        if hasattr(os, "initgroups"):   # python >= 2.7
            os.initgroups(username, gid)
        else:
            import grp      #@UnresolvedImport
            groups = [gr.gr_gid for gr in grp.getgrall() if (username in gr.gr_mem)]
            os.setgroups(groups)
    #change uid and gid:
    try:
        if os.getgid()!=gid:
            os.setgid(gid)
    except OSError as e:
        log.error("Error: cannot change gid to %i:", gid)
        if os.getgid()==0:
            #don't run as root!
            raise
        log.error(" %s", e)
        log.error(" continuing with gid=%i", os.getgid())
    try:
        if os.getuid()!=uid:
            os.setuid(uid)
    except OSError as e:
        log.error("Error: cannot change uid to %i:", uid)
        if os.getuid()==0:
            #don't run as root!
            raise
        log.error(" %s", e)
        log.error(" continuing with uid=%i", os.getuid())
    log("new uid=%s, gid=%s", os.getuid(), os.getgid())
コード例 #52
0
ファイル: taskmasterd.py プロジェクト: demvy/taskmaster
    def drop_priviledges(self, user):
        if user is None:
            return "No user specified to setuid to!"

        try:
            uid = int(user)
        except ValueError:
            try:
                pwrec = pwd.getpwnam(user)
            except KeyError:
                return "Can't find username %r" % user
            uid = pwrec[2]
        else:
            try:
                pwrec = pwd.getpwuid(uid)
            except KeyError:
                return "Can't find uid %r" % uid

        current_uid = os.getuid()
        if current_uid == uid:
            return ""
        if current_uid != 0:
            return "Can't drop privilege as nonroot user"

        gid = pwrec[3]
        if hasattr(os, 'setgroups'):
            user = pwrec[0]
            groups = [grprec[2] for grprec in grp.getgrall() if user in
                      grprec[3]]
            groups.insert(0, gid)
            try:
                os.setgroups(groups)
            except OSError:
                return 'Could not set groups of effective user'
        try:
            os.setgid(gid)
        except OSError:
            return 'Could not set group id of effective user'
        os.setuid(uid)
        return "User set for the process"
コード例 #53
0
def EnterSandbox(user: str, group: str) -> None:
    """Enters the sandbox.

  Drops root privileges, by changing the user and group.

  Args:
    user: New UNIX user name to run as. If empty then the user is not changed.
    group: New UNIX group name to run as. If empty then the group is not
      changed.
  """
    if not (user or group):
        return

    # Disable networking and IPC by creating new (empty) namespaces for the
    # current process.
    libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
    unshare = getattr(libc, "unshare", None)
    if unshare:
        unshare.argtypes = [ctypes.c_int]
        unshare.restype = ctypes.c_int

        def Unshare(flags: int) -> None:
            res = unshare(flags)
            if res == 0:
                return
            error = ctypes.get_errno()
            if error != errno.EINVAL:
                raise Error(f"unshare({flags}) failed with error {error}.")

        Unshare(CLONE_NEWNET)
        Unshare(CLONE_NEWIPC)

    if group:
        gid = grp.getgrnam(group).gr_gid
        os.setgroups([gid])
        os.setresgid(gid, gid, gid)

    if user:
        uid = pwd.getpwnam(user).pw_uid
        os.setresuid(uid, uid, uid)
コード例 #54
0
ファイル: verify.py プロジェクト: steverweber/salt
def check_user(user):
    """
    Check user and assign process uid/gid.
    """
    if salt.utils.platform.is_windows():
        return True
    if user == salt.utils.user.get_user():
        return True

    # after confirming not running Windows
    pwuser = _get_pwnam(user)

    try:
        if hasattr(os, "initgroups"):
            os.initgroups(user, pwuser.pw_gid)  # pylint: disable=minimum-python-version
        else:
            os.setgroups(salt.utils.user.get_gid_list(user, include_default=False))
        os.setgid(pwuser.pw_gid)
        os.setuid(pwuser.pw_uid)

        # We could just reset the whole environment but let's just override
        # the variables we can get from pwuser
        if "HOME" in os.environ:
            os.environ["HOME"] = pwuser.pw_dir

        if "SHELL" in os.environ:
            os.environ["SHELL"] = pwuser.pw_shell

        for envvar in ("USER", "LOGNAME"):
            if envvar in os.environ:
                os.environ[envvar] = pwuser.pw_name

    except OSError:
        msg = 'Salt configured to run as user "{}" but unable to switch.'.format(user)
        if is_console_configured():
            log.critical(msg)
        else:
            sys.stderr.write("CRITICAL: {}\n".format(msg))
        return False
    return True
コード例 #55
0
ファイル: hook.py プロジェクト: bergzand/ldaptrigger
    def _dropToUser(self, user, group):
        rtn = False
        cur_user = os.getuid()
        cur_group = os.getgid()
        print user
        if user:
            try:
                running_uid = pwd.getpwnam(user).pw_uid
            except KeyError as e:
                self.loghandle.critical(e)
        else:
            running_uid = cur_user
        if group:
            try:
                running_gid = grp.getgrnam(group).gr_gid
            except KeyError as e:
                self.loghandle.critical(e)
        else:
            running_gid = cur_group
        # Remove group privileges
        # Ensure a very conservative umask
        old_umask = os.umask(077)
        if os.getuid() != 0:
            if cur_user != running_uid:
                self.loghandle.critical(
                    'Not running as root, unable to drop to configged user')

            elif cur_group != running_gid:
                self.loghandle.critical(
                    'Not running as root, unable to drop to configged group')
            else:
                rtn = True
        else:
            os.setgroups([])
            os.setgid(running_gid)
            os.setuid(running_uid)
            self.loghandle.info('Dropped to %s:%s', user, group)
            rtn = True
        return rtn
コード例 #56
0
    def _drop_privileges(self):
        if os.getuid() != 0:
            # we are not root, so we cant drop privs
            logger.warn(
                "we are not starting up as root. this should be impossible!")
            return

        # get uid/gid of user we want to become
        uid = getpwnam(self.user).pw_uid
        gid = getgrnam(self.group).gr_gid

        # try setting the uid
        try:
            os.setgroups([])
            os.setgid(gid)
            os.setuid(uid)
        except:
            logger.warn("unable to drop privileges to %s:%s [%d:%d]" %
                        (self.user, self.group, uid, gid))
        else:
            logger.debug("successfully dropped privileges to %s:%s [%d:%d]" %
                         (self.user, self.group, uid, gid))
コード例 #57
0
def setup_uid_manager(mockgid):
    unprivUid = os.getuid()
    unprivGid = os.getgid()

    # sudo
    if os.environ.get("SUDO_UID") is not None:
        unprivUid = int(os.environ['SUDO_UID'])
        os.setgroups((mockgid, ))
        unprivGid = int(os.environ['SUDO_GID'])

    # consolehelper
    if os.environ.get("USERHELPER_UID") is not None:
        unprivUid = int(os.environ['USERHELPER_UID'])
        unprivName = pwd.getpwuid(unprivUid).pw_name
        secondary_groups = [
            g.gr_gid for g in grp.getgrall() if unprivName in g.gr_mem
        ]
        os.setgroups([mockgid] + secondary_groups)
        unprivGid = pwd.getpwuid(unprivUid)[3]

    uidManager = mockbuild.uid.UidManager(unprivUid, unprivGid)
    return uidManager
コード例 #58
0
def drop_privileges(uid_name, gid_name='nogroup'):

    # Get the uid/gid from the name
    running_uid = pwd.getpwnam(uid_name).pw_uid
    running_uid_home = pwd.getpwnam(uid_name).pw_dir
    running_gid = grp.getgrnam(gid_name).gr_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
    old_umask = os.umask(77)

    if os.getuid() == running_uid and os.getgid() == running_gid:
        # could be useful
        os.environ['HOME'] = running_uid_home
        return True
    return False
コード例 #59
0
ファイル: daemonize.py プロジェクト: zhuzhuxia480/callcenter
def daemon(user, group, path='/', pidfile='/tmp/%s.pid' % __default_servicename__, other_groups=()):
    '''
    Daemonizes current application.
    '''
    # Get uid and gid from user and group names
    uid = int(pwd.getpwnam(user)[2])
    gid = int(grp.getgrnam(group)[2])
    # Get ID of other groups
    other_groups_id = []
    for name in other_groups:
        try:
            other_groups_id.append(int(grp.getgrnam(name)[2]) )
        except:
            pass
    # First fork
    pid = gevent.fork()
    if not pid == 0:
        os._exit(0)
    # Creates a session and sets the process group ID
    os.setsid()
    # Second fork
    pid = gevent.fork()
    if not pid == 0:
        os._exit(0)
    # Change directoty
    os.chdir(path)
    # Set umask
    os.umask(0)
    # Write pidfile
    open(pidfile, 'w').write(str(os.getpid()))
    # Set group and groups
    os.setgid(gid)
    if other_groups_id:
        os.setgroups(other_groups_id)
    # Set user
    os.setuid(uid)
    # Redirect stdout/stderr to /dev/null
    sys.stdout = sys.stderr = open(os.devnull, 'a+')
    gevent.reinit()
コード例 #60
0
ファイル: rqutil.py プロジェクト: shrinidhi666/OpenCue
def permissionsUser(uid, gid):
    """Sets the effective gid/uid to supplied values"""
    if platform.system() == 'Windows':
        return
    if os.getuid() != 0:
        return
    PERMISSIONS.acquire()
    __becomeRoot()
    try:
        username = pwd.getpwuid(uid).pw_name
        usergroups =  [g.gr_gid for g in grp.getgrall() if username in g.gr_mem]

        if rqconstants.LAUNCH_FRAME_USER_GID:
            groups = [rqconstants.LAUNCH_FRAME_USER_GID] + usergroups
        else:
            groups = usergroups

        os.setgroups(groups)
    except Exception:
        pass
    os.setegid(gid)
    os.seteuid(uid)