Python os.setgid() Examples

The following are 30 code examples of os.setgid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: SetEnvironment.py    From Resetter with GNU General Public License v3.0 6 votes vote down vote up
def createDirs(self):
        uid_change = pwd.getpwnam(self.user).pw_uid
        gid_change = pwd.getpwnam(self.user).pw_gid
        pidx = os.fork()
        if pidx == 0:
            try:
                os.setgid(gid_change)
                os.setuid(uid_change)
                if not os.path.exists(self.directory):
                    os.makedirs(self.directory)
                os.chdir(self.directory)
                man_dir = os.path.abspath("manifests")
                userlists_dir = os.path.abspath("userlists")
                self.copy(self.manifests, man_dir)
                self.copy(self.userlists, userlists_dir)
            finally:
                os._exit(0)
        os.waitpid(pidx, 0) 
Example #2
Source File: subprocess.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def demote(self, uid, gid):
        def fn_uid_gid():
            os.setgid(gid)
            os.setuid(uid)

        def fn_uid():
            os.setuid(uid)

        def fn_gid():
            os.setgid(gid)

        def fn_nop():
            pass

        if uid and gid:
            return fn_uid_gid
        elif uid:
            return fn_uid
        elif gid:
            return fn_gid
        return fn_nop 
Example #3
Source File: test_process.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_mockPTYSetUidInParent(self):
        """
        Try creating a PTY process with setting its uid, in the parent path: it
        should switch to root before fork, then restore initial uid/gids.
        """
        self.mockos.child = False
        cmd = '/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        oldPTYProcess = process.PTYProcess
        try:
            process.PTYProcess = DumbPTYProcess
            reactor.spawnProcess(p, cmd, ['ouch'], env=None,
                                 usePTY=True, uid=8080)
        finally:
            process.PTYProcess = oldPTYProcess
        self.assertEquals(self.mockos.actions,
            [('setuid', 0), ('setgid', 0), ('fork', False),
             ('setregid', 1235, 1234), ('setreuid', 1237, 1236), 'waitpid']) 
Example #4
Source File: wsdd.py    From wsdd with MIT License 6 votes vote down vote up
def drop_privileges(uid, gid):
    try:
        if gid is not None:
            os.setgid(gid)
            os.setegid(gid)
            logger.debug('switched uid to {}'.format(uid))

        if uid is not None:
            os.setuid(uid)
            os.seteuid(uid)
            logger.debug('switched gid to {}'.format(gid))

        logger.info('running as {} ({}:{})'.format(args.user, uid, gid))
    except Exception as e:
        logger.error('dropping privileges failed: {}'.format(e))
        return False

    return True 
Example #5
Source File: local.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_preexec_fn(self, cluster):  # pragma: nocover
        # Borrowed and modified from jupyterhub/spawner.py
        pwnam = getpwnam(cluster.username)
        uid = pwnam.pw_uid
        gid = pwnam.pw_gid
        groups = [g.gr_gid for g in grp.getgrall() if cluster.username in g.gr_mem]
        workdir = cluster.state["workdir"]

        def preexec():
            os.setgid(gid)
            try:
                os.setgroups(groups)
            except Exception as e:
                print("Failed to set groups %s" % e, file=sys.stderr)
            os.setuid(uid)
            os.chdir(workdir)

        return preexec 
Example #6
Source File: process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #7
Source File: test_process.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_mockSetUid(self):
        """
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        """
        cmd = '/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, ['ouch'], env=None,
                                 usePTY=False, uid=8080)
        except SystemError:
            self.assert_(self.mockos.exited)
            self.assertEquals(self.mockos.actions,
                [('setuid', 0), ('setgid', 0), ('fork', False),
                  ('switchuid', 8080, 1234), 'exec', 'exit'])
        else:
            self.fail("Should not be here") 
Example #8
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_mockSetUid(self):
        """
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=False, uid=8080)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8080, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #9
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_mockPTYSetUid(self):
        """
        Try creating a PTY process with setting its uid: it's almost the same
        path as the standard path, but with a C{switchUID} call before the
        exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=True, uid=8081)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), 'setsid', ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8081, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #10
Source File: systemctl3.py    From vanilla-docker with MIT License 6 votes vote down vote up
def shutil_setuid(user = None, group = None):
    """ set fork-child uid/gid (returns pw-info env-settings)"""
    if group:
        import grp
        gid = grp.getgrnam(group).gr_gid
        os.setgid(gid)
        logg.debug("setgid %s '%s'", gid, group)
    if user:
        import pwd
        pw = pwd.getpwnam(user)
        if not group:
            gid = pw.pw_gid
            os.setgid(gid)
            logg.debug("setgid %s", gid)
        uid = pw.pw_uid
        os.setuid(uid)
        logg.debug("setuid %s '%s'", uid, user)
        home = pw.pw_dir
        shell = pw.pw_shell
        logname = pw.pw_name
        return { "USER": user, "LOGNAME": logname, "HOME": home, "SHELL": shell }
    return {} 
Example #11
Source File: ext_daemon.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def switch(self):
        """
        Switch the current process's user/group to ``self.user``, and
        ``self.group``.  Change directory to ``self.dir``, and write the
        current pid out to ``self.pid_file``.
        """
        # set the running uid/gid
        LOG.debug('setting process uid(%s) and gid(%s)' %
                  (self.user.pw_uid, self.group.gr_gid))
        os.setgid(self.group.gr_gid)
        os.setuid(self.user.pw_uid)
        os.environ['HOME'] = self.user.pw_dir
        os.chdir(self.dir)
        if self.pid_file and os.path.exists(self.pid_file):
            raise exc.FrameworkError("Process already running (%s)" %
                                     self.pid_file)
        else:
            self._write_pid_file() 
Example #12
Source File: proctools.py    From pycopia with Apache License 2.0 6 votes vote down vote up
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"
    return None 
Example #13
Source File: utils.py    From barman with GNU General Public License v3.0 6 votes vote down vote up
def drop_privileges(user):
    """
    Change the system user of the current python process.

    It will only work if called as root or as the target user.

    :param string user: target user
    :raise KeyError: if the target user doesn't exists
    :raise OSError: when the user change fails
    """
    pw = pwd.getpwnam(user)
    if pw.pw_uid == os.getuid():
        return
    groups = [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem]
    groups.append(pw.pw_gid)
    os.setgroups(groups)
    os.setgid(pw.pw_gid)
    os.setuid(pw.pw_uid)
    os.environ['HOME'] = pw.pw_dir 
Example #14
Source File: acehttp.py    From HTTPAceProxy with GNU General Public License v3.0 6 votes vote down vote up
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    try: import pwd, grp
    except ImportError: return False # Windows

    # 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(int('077', 8))
    value = (os.getuid() == running_uid and os.getgid() == running_gid)
    if value:  # could be useful
       os.environ['HOME'] = running_uid_home
       logger.info('Changed permissions to: %s: %i, %s, %i' % (uid_name, running_uid, gid_name, running_gid))
    return value 
Example #15
Source File: process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #16
Source File: fwaudit.py    From fwaudit with GNU General Public License v2.0 6 votes vote down vote up
def set_groups(path, new_uid, new_gid, verbose=True):
    '''For sudo case, set GID to non-SuperUser value.'''
    if not app_state['sudo_based_usage']:
        debug('set_groups: called for non-sudo use')
        return False
    try:
        debug('Changing file owner: file=' + path + ', uid=' + str(new_uid))
        new_gid_list = []
        new_gid_list = os.getgroups()
        if verbose:
            debug('os.getgroups: new_gid_list: ' + str(new_gid_list))
        os.setgroups([])
        if verbose:
            debug('calling os.setgroups(' + str(new_gid_list) + ')..')
        # os.setgroups(new_gid_list)  # XXX macOS: ValueError: too many groups
        os.setgroups([new_gid_list[0]])  # XXX macOS: ValueError: too many groups
        if verbose:
            debug('calling os.setgid(' + str(new_gid) + ')..')
        os.setgid(new_gid)
    except OSError as e:
        critical(e, 'Unable to to update UID on file: ' + path)
        sys.exc_info()
        log('Exception ' + str(e.errno) + ': ' + str(e))
        return False
    return True 
Example #17
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_mockSetUid(self):
        """
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=False, uid=8080)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8080, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #18
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_mockPTYSetUid(self):
        """
        Try creating a PTY process with setting its uid: it's almost the same
        path as the standard path, but with a C{switchUID} call before the
        exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=True, uid=8081)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), 'setsid', ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8081, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #19
Source File: ext_daemon.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def switch(self):
        """
        Switch the current process's user/group to ``self.user``, and
        ``self.group``.  Change directory to ``self.dir``, and write the
        current pid out to ``self.pid_file``.
        """
        # set the running uid/gid
        LOG.debug('setting process uid(%s) and gid(%s)' %
                  (self.user.pw_uid, self.group.gr_gid))
        os.setgid(self.group.gr_gid)
        os.setuid(self.user.pw_uid)
        os.environ['HOME'] = self.user.pw_dir
        os.chdir(self.dir)
        if self.pid_file and os.path.exists(self.pid_file):
            raise exc.FrameworkError("Process already running (%s)" %
                                     self.pid_file)
        else:
            self._write_pid_file() 
Example #20
Source File: daemon.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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:
        os.setgid(gid)
        os.setuid(uid)
    except Exception, exc:
        error = DaemonOSEnvironmentError(
            "Unable to change file creation mask (%(exc)s)"
            % vars())
        raise error 
Example #21
Source File: _privdrop_unix.py    From py_daemoniker with The Unlicense 6 votes vote down vote up
def _setgroup(group):
    ''' Normalizes group to a gid and sets the current gid, or does 
    nothing if group is None.
    '''
    if group is None:
        return
        
    # Normalize group to gid
    elif isinstance(group, str):
        gid = grp.getgrnam(group).gr_gid
    # The group is already a gid.
    else:
        gid = group
        
    try:
        os.setgid(gid)
    except OSError:
        self.logger.error('Unable to change group.')
        sys.exit(1) 
Example #22
Source File: irc.py    From localslackirc with GNU General Public License v3.0 6 votes vote down vote up
def su() -> None:
    """
    switch user. Useful when starting localslackirc
    as a service as root user.
    """
    if sys.platform.startswith('win'):
        return

    # Nothing to do, already not root
    if os.getuid() != 0:
        return

    username = environ.get('PROCESS_OWNER', 'nobody')
    userdata = pwd.getpwnam(username)
    os.setgid(userdata.pw_gid)
    os.setegid(userdata.pw_gid)
    os.setuid(userdata.pw_uid)
    os.seteuid(userdata.pw_uid) 
Example #23
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_mockErrorInForkRestoreUID(self):
        """
        If C{os.fork} raises an exception and a UID change has been made, the
        previous UID and GID are restored.
        """
        self.mockos.raiseFork = OSError(errno.EAGAIN, None)
        protocol = TrivialProcessProtocol(None)
        self.assertRaises(OSError, reactor.spawnProcess, protocol, None,
                          uid=8080)
        self.assertEqual(self.mockos.actions,
            [('setuid', 0), ('setgid', 0), ("fork", False),
             ('setregid', 1235, 1234), ('setreuid', 1237, 1236)]) 
Example #24
Source File: daemon.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # 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) 
Example #25
Source File: daemon.py    From ssr-ml with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # 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) 
Example #26
Source File: common.py    From certidude with MIT License 5 votes vote down vote up
def drop_privileges():
    from certidude import config
    import pwd
    _, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
    restricted_groups = []
    restricted_groups.append(gid)

    # PAM needs access to /etc/shadow
    if config.AUTHENTICATION_BACKENDS == {"pam"}:
        import grp
        name, passwd, num, mem = grp.getgrnam("shadow")
        click.echo("Adding current user to shadow group due to PAM authentication backend")
        restricted_groups.append(num)

    os.setgroups(restricted_groups)
    os.setgid(gid)
    os.setuid(uid)
    click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
        (getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
    os.umask(0o007) 
Example #27
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_mockSetUidInParent(self):
        """
        Try creating a process with setting its uid, in the parent path: it
        should switch to root before fork, then restore initial uid/gids.
        """
        self.mockos.child = False
        cmd = '/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        reactor.spawnProcess(p, cmd, ['ouch'], env=None,
                             usePTY=False, uid=8080)
        self.assertEquals(self.mockos.actions,
            [('setuid', 0), ('setgid', 0), ('fork', False),
             ('setregid', 1235, 1234), ('setreuid', 1237, 1236), 'waitpid']) 
Example #28
Source File: common.py    From canari3 with GNU General Public License v3.0 5 votes vote down vote up
def uproot():
    if os.name == 'posix' and not os.geteuid():
        login = getuser()

        if login != 'root':
            import pwd
            click.echo(
                'Why are you using root to run this command? You should be using %s! Bringing you down...' % login,
                err=True
            )
            user = pwd.getpwnam(login)
            os.setgid(user.pw_gid)
            os.setuid(user.pw_uid) 
Example #29
Source File: daemon.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # 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) 
Example #30
Source File: changer.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def run_package_reporter(self):
        """
        Run the L{PackageReporter} if there were successfully completed tasks.
        """
        if self.handled_tasks_count == 0:
            # Nothing was done
            return

        if os.getuid() == 0:
            os.setgid(grp.getgrnam("landscape").gr_gid)
            os.setuid(pwd.getpwnam("landscape").pw_uid)
        command = find_reporter_command(self._config)
        if self._config.config is not None:
            command += " -c %s" % self._config.config
        os.system(command)