Python os.seteuid() Examples

The following are code examples for showing how to use os.seteuid(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: openhatch   Author: campbe13   File: platforms.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def set_effective_user(uid=None, gid=None):
    """Change process privileges to new user/group.

    If UID and GID is set the effective user/group is set.

    If only UID is set, the effective user is set, and the group is
    set to the users primary group.

    If only GID is set, the effective group is set.

    """
    uid = uid and parse_uid(uid)
    gid = gid and parse_gid(gid)

    if uid:
        # If GID isn't defined, get the primary GID of the user.
        if not gid and pwd:
            gid = pwd.getpwuid(uid).pw_gid
        setegid(gid)
        seteuid(uid)
    else:
        gid and setegid(gid) 
Example 2
Project: oa_qian   Author: sunqb   File: test_interrupt.py    Apache License 2.0 6 votes vote down vote up
def test_interrupted_systemcall(self):
        '''
        Make sure interrupted system calls don't break the world, since we
        can't control what all signals our connection thread will get
        '''
        if 'linux' not in platform:
            raise SkipTest('Unable to reproduce error case on'
                           ' non-linux platforms')

        path = 'interrupt_test'
        value = b"1"
        self.client.create(path, value)

        # set the euid to the current process' euid.
        # glibc sends SIGRT to all children, which will interrupt the
        # system call
        os.seteuid(os.geteuid())

        # basic sanity test that it worked alright
        assert self.client.get(path)[0] == value 
Example 3
Project: pycopia   Author: kdart   File: proctools.py    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 4
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.seteuid, 0)
        self.assertRaises(OverflowError, os.seteuid, 1<<32) 
Example 5
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __enter__(self):
        if os.geteuid() == 0:
            os.setegid(int(os.environ['SUDO_GID']))
            os.seteuid(int(os.environ['SUDO_UID']))
            self.was_sudo = True 
Example 6
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __exit__(self, type, value, traceback):
        if self.was_sudo:
            os.seteuid(0)
            os.setegid(0) 
Example 7
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __enter__(self):
        if not self.has_sudo:
            print_error('Permission denied')
            return
        if os.geteuid() != 0:
            os.seteuid(0)
            os.setegid(0)
            self.was_user = True 
Example 8
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __exit__(self, type, value, traceback):
        if self.was_user:
            os.setegid(int(os.environ['SUDO_GID']))
            os.seteuid(int(os.environ['SUDO_UID']))
            self.was_user = False 
Example 9
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __enter__(self):
        if os.geteuid() == 0:
            os.setegid(int(os.environ['SUDO_GID']))
            os.seteuid(int(os.environ['SUDO_UID']))
            self.was_sudo = True 
Example 10
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __enter__(self):
        if not self.has_sudo:
            print_error('Permission denied')
            return
        if os.geteuid() != 0:
            os.seteuid(0)
            os.setegid(0)
            self.was_user = True 
Example 11
Project: interact   Author: dongshengmu   File: util.py    MIT License 5 votes vote down vote up
def __exit__(self, type, value, traceback):
        if self.was_user:
            os.setegid(int(os.environ['SUDO_GID']))
            os.seteuid(int(os.environ['SUDO_UID']))
            self.was_user = False 
Example 12
Project: openhatch   Author: campbe13   File: platforms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def seteuid(uid):
    """Set effective user id."""
    uid = parse_uid(uid)
    if uid != os.getuid():
        os.seteuid(uid) 
Example 13
Project: PiFan   Author: Dualion   File: daemon.py    GNU General Public License v2.0 5 votes vote down vote up
def switchuser(cls, user, group):
        if group is not None:
            if isinstance(group, basestring):
                group = grp.getgrnam(group).gr_gid
            os.setegid(group)
        if user is not None:
            if isinstance(user, basestring):
                user = pwd.getpwnam(user).pw_uid
            os.seteuid(user)
            if "HOME" in os.environ:
                os.environ["HOME"] = pwd.getpwuid(user).pw_dir 
Example 14
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(OSError, os.seteuid, 0)
        self.assertRaises(OverflowError, os.seteuid, 1<<32) 
Example 15
Project: autopyfactory   Author: PanDAWMS   File: factory.py    Apache License 2.0 5 votes vote down vote up
def __checkroot(self): 
        """
        If running as root, drop privileges to --runas' account.
        """
        starting_uid = os.getuid()
        starting_gid = os.getgid()
        starting_uid_name = pwd.getpwuid(starting_uid)[0]

        hostname = socket.gethostname()
        
        if os.getuid() != 0:
            self.log.info("Already running as unprivileged user %s at %s" % (starting_uid_name, hostname))
            
        if os.getuid() == 0:
            try:
                runuid = pwd.getpwnam(self.options.runAs).pw_uid
                rungid = pwd.getpwnam(self.options.runAs).pw_gid
                os.chown(self.options.logfile, runuid, rungid)
                
                os.setgid(rungid)
                os.setuid(runuid)
                os.seteuid(runuid)
                os.setegid(rungid)

                self._changehome()
                self._changewd()

                self.log.info("Now running as user %d:%d at %s..." % (runuid, rungid, hostname))
                self._printenv()

            
            except KeyError as e:
                self.log.error('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))
                sys.exit(1)
                
            except OSError as e:
                self.log.error('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))
                sys.exit(1) 
Example 16
Project: autopyfactory   Author: PanDAWMS   File: factorylib.py    Apache License 2.0 5 votes vote down vote up
def __checkroot(self): 
        """
        If running as root, drop privileges to --runas' account.
        """
        starting_uid = os.getuid()
        starting_gid = os.getgid()
        starting_uid_name = pwd.getpwuid(starting_uid)[0]

        hostname = socket.gethostname()
        
        if os.getuid() != 0:
            self.log.info("Already running as unprivileged user %s at %s" % (starting_uid_name, hostname))
            
        if os.getuid() == 0:
            try:
                runuid = pwd.getpwnam(self.options.runAs).pw_uid
                rungid = pwd.getpwnam(self.options.runAs).pw_gid
                os.chown(self.options.logfile, runuid, rungid)
                
                os.setgid(rungid)
                os.setuid(runuid)
                os.seteuid(runuid)
                os.setegid(rungid)

                self._changehome()
                self._changewd()

                self.log.info("Now running as user %d:%d at %s..." % (runuid, rungid, hostname))
                self._printenv()

            
            except KeyError, e:
                self.log.error('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))
                sys.exit(1)
                
            except OSError, e:
                self.log.error('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))
                sys.exit(1) 
Example 17
Project: workload-collocation-agent   Author: intel   File: security.py    Apache License 2.0 5 votes vote down vote up
def __enter__(self):
        self.uid = os.geteuid()
        if self.uid != 0:
            os.seteuid(0)
            log.log(logger.TRACE, "Effective user id from {} to 0".format(self.uid)) 
Example 18
Project: workload-collocation-agent   Author: intel   File: security.py    Apache License 2.0 5 votes vote down vote up
def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            log.warning("Exception {} with message {} thrown".format(exc_type, exc_val))
        if self.uid != 0:
            os.seteuid(self.uid)
            log.log(logger.TRACE, "Effective user id from 0 to {}".format(self.uid))
            self.uid = 0 
Example 19
Project: hat   Author: heemayl   File: runner.py    GNU General Public License v3.0 5 votes vote down vote up
def run_command(self, command, euid, use_shell, job_id):
        '''Runs a command, and returns (exit_status, STDOUT, STDERR) tuple.'''
        try:
            command_ = command if use_shell else shlex.split(command)
            proc = subprocess.Popen(
                command_,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=use_shell,
                preexec_fn=lambda: os.seteuid(int(euid))  # Setting EUID
            )
        except Exception as err:
            # Setting `returncode` to 127
            returncode, stdout, stderr = 127, b'', bytes(str(err), 'utf-8')
        else:
            returncode, stdout, stderr = proc.wait(), *proc.communicate()
        finally:
            try:
                return (returncode, stdout, stderr)
            except UnboundLocalError:
                # Interactive or frame refreshing commands
                # are not allowed e.g. `top`
                error_msg = ('Interactive or screen refreshing'
                             ' commands are not allowed'
                )
                write_file(
                    self.daemon_log,
                    'id>{} : cmd>{} :: {}'.format(job_id, command, error_msg),
                    mode='at',
                )
                # raise HatRunnerException(error_msg) 
Example 20
Project: ironpython2   Author: IronLanguages   File: test_os.py    Apache License 2.0 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.seteuid, 0)
        self.assertRaises(OverflowError, os.seteuid, 1<<32) 
Example 21
Project: open-recipe   Author: dspray95   File: util.py    The Unlicense 5 votes vote down vote up
def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
    """
    Run the given function wrapped with seteuid/setegid calls.

    This will try to minimize the number of seteuid/setegid calls, comparing
    current and wanted permissions

    @param euid: effective UID used to call the function.
    @type euid: C{int}

    @type egid: effective GID used to call the function.
    @param egid: C{int}

    @param function: the function run with the specific permission.
    @type function: any callable

    @param *args: arguments passed to C{function}
    @param **kwargs: keyword arguments passed to C{function}
    """
    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return function(*args, **kwargs)
    else:
        if uid != 0 and (uid != euid or gid != egid):
            os.seteuid(0)
        if gid != egid:
            os.setegid(egid)
        if euid != 0 and (euid != uid or gid != egid):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if euid != 0 and (uid != euid or gid != egid):
                os.seteuid(0)
            if gid != egid:
                os.setegid(gid)
            if uid != 0 and (uid != euid or gid != egid):
                os.seteuid(uid) 
Example 22
Project: open-recipe   Author: dspray95   File: unix.py    The Unlicense 5 votes vote down vote up
def _runAsUser(self, f, *args, **kw):
        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:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
Example 23
Project: open-recipe   Author: dspray95   File: unix.py    The Unlicense 5 votes vote down vote up
def getPtyOwnership(self):
        ttyGid = os.stat(self.ptyTuple[2])[5]
        uid, gid = self.avatar.getUserGroupId()
        euid, egid = os.geteuid(), os.getegid()
        os.setegid(0)
        os.seteuid(0)
        try:
            os.chown(self.ptyTuple[2], uid, ttyGid)
        finally:
            os.setegid(egid)
            os.seteuid(euid) 
Example 24
Project: open-recipe   Author: dspray95   File: test_openssh_compat.py    The Unlicense 5 votes vote down vote up
def setUp(self):
        self.factory = OpenSSHFactory()
        self.keysDir = FilePath(self.mktemp())
        self.keysDir.makedirs()
        self.factory.dataRoot = self.keysDir.path
        self.moduliDir = FilePath(self.mktemp())
        self.moduliDir.makedirs()
        self.factory.moduliRoot = self.moduliDir.path

        self.keysDir.child("ssh_host_foo").setContent(b"foo")
        self.keysDir.child("bar_key").setContent(b"foo")
        self.keysDir.child("ssh_host_one_key").setContent(
            keydata.privateRSA_openssh)
        self.keysDir.child("ssh_host_two_key").setContent(
            keydata.privateDSA_openssh)
        self.keysDir.child("ssh_host_three_key").setContent(
            b"not a key content")

        self.keysDir.child("ssh_host_one_key.pub").setContent(
            keydata.publicRSA_openssh)

        self.moduliDir.child("moduli").setContent(b"""
#    $OpenBSD: moduli,v 1.xx 2016/07/26 12:34:56 jhacker Exp $
# Time Type Tests Tries Size Generator Modulus
20030501000000 2 6 100 2047 2 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF

""")

        self.mockos = MockOS()
        self.patch(os, "seteuid", self.mockos.seteuid)
        self.patch(os, "setegid", self.mockos.setegid) 
Example 25
Project: open-recipe   Author: dspray95   File: test_process.py    The Unlicense 5 votes vote down vote up
def seteuid(self, egid):
        """
        Mock C{os.seteuid}, store result.
        """
        self.seteuidCalls.append(egid) 
Example 26
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 27
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 28
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(OSError, os.seteuid, 0)
        self.assertRaises(TypeError, os.setegid, 'not an int')
        self.assertRaises(OverflowError, os.seteuid, self.UID_OVERFLOW) 
Example 29
Project: oss-ftp   Author: aliyun   File: authorizers.py    MIT License 5 votes vote down vote up
def impersonate_user(self, username, password):
            """Change process effective user/group ids to reflect
            logged in user.
            """
            try:
                pwdstruct = pwd.getpwnam(username)
            except KeyError:
                raise AuthorizerError(self.msg_no_such_user)
            else:
                os.setegid(pwdstruct.pw_gid)
                os.seteuid(pwdstruct.pw_uid) 
Example 30
Project: oss-ftp   Author: aliyun   File: authorizers.py    MIT License 5 votes vote down vote up
def terminate_impersonation(self, username):
            """Revert process effective user/group IDs."""
            os.setegid(PROCESS_GID)
            os.seteuid(PROCESS_UID) 
Example 31
Project: oss-ftp   Author: aliyun   File: authorizers.py    MIT License 5 votes vote down vote up
def impersonate_user(self, username, password):
            """Change process effective user/group ids to reflect
            logged in user.
            """
            try:
                pwdstruct = pwd.getpwnam(username)
            except KeyError:
                raise AuthorizerError(self.msg_no_such_user)
            else:
                os.setegid(pwdstruct.pw_gid)
                os.seteuid(pwdstruct.pw_uid) 
Example 32
Project: oss-ftp   Author: aliyun   File: authorizers.py    MIT License 5 votes vote down vote up
def terminate_impersonation(self, username):
            """Revert process effective user/group IDs."""
            os.setegid(PROCESS_GID)
            os.seteuid(PROCESS_UID) 
Example 33
Project: oss-ftp   Author: aliyun   File: test_os.py    MIT License 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.seteuid, 0)
        self.assertRaises(OverflowError, os.seteuid, 1<<32) 
Example 34
Project: Safejumper-for-Desktop   Author: proxysh   File: util.py    GNU General Public License v2.0 5 votes vote down vote up
def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
    """
    Run the given function wrapped with seteuid/setegid calls.

    This will try to minimize the number of seteuid/setegid calls, comparing
    current and wanted permissions

    @param euid: effective UID used to call the function.
    @type euid: C{int}

    @type egid: effective GID used to call the function.
    @param egid: C{int}

    @param function: the function run with the specific permission.
    @type function: any callable

    @param *args: arguments passed to C{function}
    @param **kwargs: keyword arguments passed to C{function}
    """
    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return function(*args, **kwargs)
    else:
        if uid != 0 and (uid != euid or gid != egid):
            os.seteuid(0)
        if gid != egid:
            os.setegid(egid)
        if euid != 0 and (euid != uid or gid != egid):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if euid != 0 and (uid != euid or gid != egid):
                os.seteuid(0)
            if gid != egid:
                os.setegid(gid)
            if uid != 0 and (uid != euid or gid != egid):
                os.seteuid(uid) 
Example 35
Project: Safejumper-for-Desktop   Author: proxysh   File: unix.py    GNU General Public License v2.0 5 votes vote down vote up
def _runAsUser(self, f, *args, **kw):
        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:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
Example 36
Project: Safejumper-for-Desktop   Author: proxysh   File: unix.py    GNU General Public License v2.0 5 votes vote down vote up
def getPtyOwnership(self):
        ttyGid = os.stat(self.ptyTuple[2])[5]
        uid, gid = self.avatar.getUserGroupId()
        euid, egid = os.geteuid(), os.getegid()
        os.setegid(0)
        os.seteuid(0)
        try:
            os.chown(self.ptyTuple[2], uid, ttyGid)
        finally:
            os.setegid(egid)
            os.seteuid(euid) 
Example 37
Project: Safejumper-for-Desktop   Author: proxysh   File: test_openssh_compat.py    GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.factory = OpenSSHFactory()
        self.keysDir = FilePath(self.mktemp())
        self.keysDir.makedirs()
        self.factory.dataRoot = self.keysDir.path
        self.moduliDir = FilePath(self.mktemp())
        self.moduliDir.makedirs()
        self.factory.moduliRoot = self.moduliDir.path

        self.keysDir.child("ssh_host_foo").setContent(b"foo")
        self.keysDir.child("bar_key").setContent(b"foo")
        self.keysDir.child("ssh_host_one_key").setContent(
            keydata.privateRSA_openssh)
        self.keysDir.child("ssh_host_two_key").setContent(
            keydata.privateDSA_openssh)
        self.keysDir.child("ssh_host_three_key").setContent(
            b"not a key content")

        self.keysDir.child("ssh_host_one_key.pub").setContent(
            keydata.publicRSA_openssh)

        self.moduliDir.child("moduli").setContent(b"""
#    $OpenBSD: moduli,v 1.xx 2016/07/26 12:34:56 jhacker Exp $
# Time Type Tests Tries Size Generator Modulus
20030501000000 2 6 100 2047 2 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF

19981111000000 2 6 100 1023 2 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF
        """)

        self.mockos = MockOS()
        self.patch(os, "seteuid", self.mockos.seteuid)
        self.patch(os, "setegid", self.mockos.setegid) 
Example 38
Project: Safejumper-for-Desktop   Author: proxysh   File: test_process.py    GNU General Public License v2.0 5 votes vote down vote up
def seteuid(self, egid):
        """
        Mock C{os.seteuid}, store result.
        """
        self.seteuidCalls.append(egid) 
Example 39
Project: teleport   Author: tp4a   File: test_process.py    Apache License 2.0 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 40
Project: teleport   Author: tp4a   File: test_process.py    Apache License 2.0 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 41
Project: deskOrg   Author: saleguas   File: test_process.py    MIT License 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 42
Project: deskOrg   Author: saleguas   File: test_process.py    MIT License 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 43
Project: FancyWord   Author: EastonLee   File: test_process.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 44
Project: FancyWord   Author: EastonLee   File: test_process.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 45
Project: salt-psu   Author: weswhet   File: mac_prefs.py    Apache License 2.0 5 votes vote down vote up
def _read_pref(name, domain, user, host, runas):
    '''
    helper function for reading the preference, either at the user level
    or system level
    '''
    if runas:
        try:
            # convert to uid for later use.
            uid = pwd.getpwnam(runas).pw_uid
        except KeyError:
            raise CommandExecutionError(
                'Set to runas user {}, this user'
                ' does not exist.'.format(runas)
            )
        # need to run as the user
        log.debug('Setting EUID to {}'.format(runas))
        os.seteuid(uid)

    if user:
        user_domain, host_domain = _get_user_and_host(user, host)
        value = Foundation.CFPreferencesCopyValue(name,
                                                  domain,
                                                  user_domain,
                                                  host_domain)
        os.seteuid(0)
        return value

    #need to bring ourselves back up to root
    path = '/var/root/Library/Preferences/'
    d_path = os.path.join(path, domain)
    log.debug('Reading key: "{}" in'
              ' domain: "{}" at "{}"'.format(name, domain, d_path))
    return Foundation.CFPreferencesCopyAppValue(name, domain) 
Example 46
Project: salt-psu   Author: weswhet   File: mac_prefs.py    Apache License 2.0 5 votes vote down vote up
def _set_pref(name, value, domain, user, host, runas):
    '''
    sets the pref for the user not at the app value level
    returns true or false if the preference was set correctly or not.
    '''
    if runas:
        try:
            # convert to uid for later use.
            uid = pwd.getpwnam(runas).pw_uid
        except KeyError:
            raise CommandExecutionError(
                'Set to runas user {}, this user'
                ' does not exist.'.format(runas)
            )
        # need to run as the user
        log.debug('Setting EUID to {}'.format(runas))
        os.seteuid(uid)
    if user:
        pref_user, pref_host = _get_user_and_host(user, host)
        path = '/Library/Preferences/'
        d_path = os.path.join(path, domain)
        log.debug('Settting key: "{}" to value: "{}" in '
                  'domain: "{}" in "{}"'.format(name, value, domain, d_path))
        try:
            set_val = Foundation.CFPreferencesSetValue(name,
                                                       value,
                                                       domain,
                                                       pref_user,
                                                       pref_host)
            Foundation.CFPreferencesAppSynchronize(domain)
            os.seteuid(0)
            return set_val
        except BaseException:
            log.warning('prefs._set_pref caught exception on user set.')
            return False
    path = '/var/root/Library/Preferences/'
    d_path = os.path.join(path, domain)
    log.debug('Settting key: "{}" to value: "{}" in'
              ' domain: "{}" in "{}"'.format(name, value, domain, d_path))
    Foundation.CFPreferencesSetAppValue(name, value, domain)
    return Foundation.CFPreferencesAppSynchronize(domain) 
Example 47
Project: ProcessFS   Author: mherrmann   File: test_process.py    MIT License 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 48
Project: ProcessFS   Author: mherrmann   File: test_process.py    MIT License 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 49
Project: vc3-master   Author: vc3-project   File: master.py    GNU General Public License v3.0 5 votes vote down vote up
def __checkroot(self): 
        """
        If running as root, drop privileges to --runas' account.
        """
        starting_uid = os.getuid()
        starting_gid = os.getgid()
        starting_uid_name = pwd.getpwuid(starting_uid)[0]

        hostname = socket.gethostname()
        
        if os.getuid() != 0:
            self.log.info("Already running as unprivileged user %s at %s" % (starting_uid_name, hostname))
            
        if os.getuid() == 0:
            try:
                runuid = pwd.getpwnam(self.options.runAs).pw_uid
                rungid = pwd.getpwnam(self.options.runAs).pw_gid
                os.chown(self.options.logfile, runuid, rungid)
                
                os.setgid(rungid)
                os.setuid(runuid)
                os.seteuid(runuid)
                os.setegid(rungid)

                self._changehome()
                self._changewd()

                self.log.info("Now running as user %d:%d at %s..." % (runuid, rungid, hostname))
                self._printenv()

            
            except KeyError, e:
                self.log.error('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))
                sys.exit(1)
                
            except OSError, e:
                self.log.error('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))
                sys.exit(1) 
Example 50
Project: IPTVProxy   Author: sfanous   File: privilege.py    MIT License 5 votes vote down vote up
def become_privileged_user(cls):
        try:
            os.setegid(cls._root_user_gid)
            os.seteuid(cls._root_user_uid)
        except AttributeError:
            pass 
Example 51
Project: IPTVProxy   Author: sfanous   File: privilege.py    MIT License 5 votes vote down vote up
def become_unprivileged_user(cls):
        try:
            os.setegid(cls._gid_of_user_invoking_sudo)
            os.seteuid(cls._uid_of_user_invoking_sudo)
        except AttributeError:
            pass 
Example 52
Project: script-languages   Author: exasol   File: authorizers.py    MIT License 5 votes vote down vote up
def impersonate_user(self, username, password):
            """Change process effective user/group ids to reflect
            logged in user.
            """
            try:
                pwdstruct = pwd.getpwnam(username)
            except KeyError:
                raise AuthorizerError(self.msg_no_such_user)
            else:
                os.setegid(pwdstruct.pw_gid)
                os.seteuid(pwdstruct.pw_uid) 
Example 53
Project: script-languages   Author: exasol   File: authorizers.py    MIT License 5 votes vote down vote up
def terminate_impersonation(self, username):
            """Revert process effective user/group IDs."""
            os.setegid(PROCESS_GID)
            os.seteuid(PROCESS_UID) 
Example 54
Project: weibo_twitter_earnings_analysis   Author: lynings   File: util.py    Apache License 2.0 5 votes vote down vote up
def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
    """
    Run the given function wrapped with seteuid/setegid calls.

    This will try to minimize the number of seteuid/setegid calls, comparing
    current and wanted permissions

    @param euid: effective UID used to call the function.
    @type euid: C{int}

    @type egid: effective GID used to call the function.
    @param egid: C{int}

    @param function: the function run with the specific permission.
    @type function: any callable

    @param *args: arguments passed to C{function}
    @param **kwargs: keyword arguments passed to C{function}
    """
    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return function(*args, **kwargs)
    else:
        if uid != 0 and (uid != euid or gid != egid):
            os.seteuid(0)
        if gid != egid:
            os.setegid(egid)
        if euid != 0 and (euid != uid or gid != egid):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if euid != 0 and (uid != euid or gid != egid):
                os.seteuid(0)
            if gid != egid:
                os.setegid(gid)
            if uid != 0 and (uid != euid or gid != egid):
                os.seteuid(uid) 
Example 55
Project: weibo_twitter_earnings_analysis   Author: lynings   File: unix.py    Apache License 2.0 5 votes vote down vote up
def _runAsUser(self, f, *args, **kw):
        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:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
Example 56
Project: weibo_twitter_earnings_analysis   Author: lynings   File: unix.py    Apache License 2.0 5 votes vote down vote up
def getPtyOwnership(self):
        ttyGid = os.stat(self.ptyTuple[2])[5]
        uid, gid = self.avatar.getUserGroupId()
        euid, egid = os.geteuid(), os.getegid()
        os.setegid(0)
        os.seteuid(0)
        try:
            os.chown(self.ptyTuple[2], uid, ttyGid)
        finally:
            os.setegid(egid)
            os.seteuid(euid) 
Example 57
Project: weibo_twitter_earnings_analysis   Author: lynings   File: test_openssh_compat.py    Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.factory = OpenSSHFactory()
        self.keysDir = FilePath(self.mktemp())
        self.keysDir.makedirs()
        self.factory.dataRoot = self.keysDir.path
        self.moduliDir = FilePath(self.mktemp())
        self.moduliDir.makedirs()
        self.factory.moduliRoot = self.moduliDir.path

        self.keysDir.child("ssh_host_foo").setContent(b"foo")
        self.keysDir.child("bar_key").setContent(b"foo")
        self.keysDir.child("ssh_host_one_key").setContent(
            keydata.privateRSA_openssh)
        self.keysDir.child("ssh_host_two_key").setContent(
            keydata.privateDSA_openssh)
        self.keysDir.child("ssh_host_three_key").setContent(
            b"not a key content")

        self.keysDir.child("ssh_host_one_key.pub").setContent(
            keydata.publicRSA_openssh)

        self.moduliDir.child("moduli").setContent(b"""
#    $OpenBSD: moduli,v 1.xx 2016/07/26 12:34:56 jhacker Exp $
# Time Type Tests Tries Size Generator Modulus
20030501000000 2 6 100 2047 2 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF

""")

        self.mockos = MockOS()
        self.patch(os, "seteuid", self.mockos.seteuid)
        self.patch(os, "setegid", self.mockos.setegid) 
Example 58
Project: weibo_twitter_earnings_analysis   Author: lynings   File: test_process.py    Apache License 2.0 5 votes vote down vote up
def seteuid(self, egid):
        """
        Mock C{os.seteuid}, store result.
        """
        self.seteuidCalls.append(egid) 
Example 59
Project: learn_python3_spider   Author: wistbean   File: util.py    MIT License 5 votes vote down vote up
def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
    """
    Run the given function wrapped with seteuid/setegid calls.

    This will try to minimize the number of seteuid/setegid calls, comparing
    current and wanted permissions

    @param euid: effective UID used to call the function.
    @type euid: C{int}

    @type egid: effective GID used to call the function.
    @param egid: C{int}

    @param function: the function run with the specific permission.
    @type function: any callable

    @param *args: arguments passed to C{function}
    @param **kwargs: keyword arguments passed to C{function}
    """
    uid, gid = os.geteuid(), os.getegid()
    if uid == euid and gid == egid:
        return function(*args, **kwargs)
    else:
        if uid != 0 and (uid != euid or gid != egid):
            os.seteuid(0)
        if gid != egid:
            os.setegid(egid)
        if euid != 0 and (euid != uid or gid != egid):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if euid != 0 and (uid != euid or gid != egid):
                os.seteuid(0)
            if gid != egid:
                os.setegid(gid)
            if uid != 0 and (uid != euid or gid != egid):
                os.seteuid(uid) 
Example 60
Project: learn_python3_spider   Author: wistbean   File: unix.py    MIT License 5 votes vote down vote up
def _runAsUser(self, f, *args, **kw):
        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:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
Example 61
Project: learn_python3_spider   Author: wistbean   File: unix.py    MIT License 5 votes vote down vote up
def getPtyOwnership(self):
        ttyGid = os.stat(self.ptyTuple[2])[5]
        uid, gid = self.avatar.getUserGroupId()
        euid, egid = os.geteuid(), os.getegid()
        os.setegid(0)
        os.seteuid(0)
        try:
            os.chown(self.ptyTuple[2], uid, ttyGid)
        finally:
            os.setegid(egid)
            os.seteuid(euid) 
Example 62
Project: learn_python3_spider   Author: wistbean   File: test_openssh_compat.py    MIT License 5 votes vote down vote up
def setUp(self):
        self.factory = OpenSSHFactory()
        self.keysDir = FilePath(self.mktemp())
        self.keysDir.makedirs()
        self.factory.dataRoot = self.keysDir.path
        self.moduliDir = FilePath(self.mktemp())
        self.moduliDir.makedirs()
        self.factory.moduliRoot = self.moduliDir.path

        self.keysDir.child("ssh_host_foo").setContent(b"foo")
        self.keysDir.child("bar_key").setContent(b"foo")
        self.keysDir.child("ssh_host_one_key").setContent(
            keydata.privateRSA_openssh)
        self.keysDir.child("ssh_host_two_key").setContent(
            keydata.privateDSA_openssh)
        self.keysDir.child("ssh_host_three_key").setContent(
            b"not a key content")

        self.keysDir.child("ssh_host_one_key.pub").setContent(
            keydata.publicRSA_openssh)

        self.moduliDir.child("moduli").setContent(b"""
#    $OpenBSD: moduli,v 1.xx 2016/07/26 12:34:56 jhacker Exp $
# Time Type Tests Tries Size Generator Modulus
20030501000000 2 6 100 2047 2 FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF

""")

        self.mockos = MockOS()
        self.patch(os, "seteuid", self.mockos.seteuid)
        self.patch(os, "setegid", self.mockos.setegid) 
Example 63
Project: learn_python3_spider   Author: wistbean   File: test_process.py    MIT License 5 votes vote down vote up
def seteuid(self, egid):
        """
        Mock C{os.seteuid}, store result.
        """
        self.seteuidCalls.append(egid) 
Example 64
Project: pysftpproxy   Author: rauburtin   File: server.py    MIT License 5 votes vote down vote up
def _runAsUser(self, f, *args, **kw):
        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:
            os.setegid(0)
            os.seteuid(0)
            os.setgroups(groups)
            os.setegid(egid)
            os.seteuid(euid)
        return r 
Example 65
Project: OpScripts   Author: ClockworkNet   File: v8.py    MIT License 5 votes vote down vote up
def _exec_cmd_base(cmd_args, cwd=None, uid=None, gids=None):
    """INTERNAL/PRIVATE
    Execute specified command with optional working directory, uid, and gids.

    Returns exit status, STDOUT, and STDERR.
    """
    try:
        int(gids)
        gids = [gids, ]
    except TypeError:
        pass
    if gids is not None:
        gids = list(gids)
        gids.sort()

    def switch_uid_gids():
        egids = os.getgroups()
        egids.sort()
        euid = os.geteuid()
        if gids is not None and gids != egids:
            os.setgroups(gids)
        if uid is not None and uid != euid:
            os.seteuid(uid)

    job = subprocess.Popen(cmd_args, cwd=cwd, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           preexec_fn=switch_uid_gids)
    exit_status = job.wait()
    stdout = job.stdout.read().strip().decode("utf-8")
    job.stdout.close()
    stderr = job.stderr.read().strip().decode("utf-8")
    job.stderr.close()
    return [exit_status, stdout, stderr] 
Example 66
Project: OpScripts   Author: ClockworkNet   File: v7.py    MIT License 5 votes vote down vote up
def _exec_cmd_base(cmd_args, cwd=None, uid=None, gids=None):
    """INTERNAL/PRIVATE
    Execute specified command with optional working directory, uid, and gids.

    Returns exit status, STDOUT, and STDERR.
    """
    try:
        int(gids)
        gids = [gids, ]
    except TypeError:
        pass
    if gids is not None:
        gids = list(gids)
        gids.sort()

    def switch_uid_gids():
        egids = os.getgroups()
        egids.sort()
        euid = os.geteuid()
        if gids is not None and gids != egids:
            os.setgroups(gids)
        if uid is not None and uid != euid:
            os.seteuid(uid)

    job = subprocess.Popen(cmd_args, cwd=cwd, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           preexec_fn=switch_uid_gids)
    exit_status = job.wait()
    stdout = job.stdout.read().strip().decode("utf-8")
    stderr = job.stderr.read().strip().decode("utf-8")
    return [exit_status, stdout, stderr] 
Example 67
Project: auto-selfcontrol   Author: andreasgrill   File: auto-selfcontrol.py    MIT License 5 votes vote down vote up
def set_selfcontrol_setting(key, value, username):
    """ sets a single default setting of SelfControl for the provied username """
    NSUserDefaults.resetStandardUserDefaults()
    originalUID = os.geteuid()
    os.seteuid(getpwnam(username).pw_uid)
    CFPreferencesSetAppValue(key, value, "org.eyebeam.SelfControl")
    CFPreferencesAppSynchronize("org.eyebeam.SelfControl")
    NSUserDefaults.resetStandardUserDefaults()
    os.seteuid(originalUID) 
Example 68
Project: auto-selfcontrol   Author: andreasgrill   File: auto-selfcontrol.py    MIT License 5 votes vote down vote up
def get_selfcontrol_settings(username):
    """ returns all default settings of SelfControl for the provided username """
    NSUserDefaults.resetStandardUserDefaults()
    originalUID = os.geteuid()
    os.seteuid(getpwnam(username).pw_uid)
    defaults = NSUserDefaults.standardUserDefaults()
    defaults.addSuiteNamed_("org.eyebeam.SelfControl")
    defaults.synchronize()
    result = defaults.dictionaryRepresentation()
    NSUserDefaults.resetStandardUserDefaults()
    os.seteuid(originalUID)
    return result 
Example 69
Project: BL-Bot   Author: IOIIIO   File: test_process.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000) 
Example 70
Project: BL-Bot   Author: IOIIIO   File: test_process.py    GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self) 
Example 71
Project: navdoon   Author: farzadghanei   File: collector.py    Apache License 2.0 5 votes vote down vote up
def _change_process_user_group(self):
        # type: () -> None
        if self.user:
            self._log("changing process user to {}".format(self.user))
            os.seteuid(self.user)
        if self.group:
            self._log("changing process group to {}".format(self.group))
            os.setegid(self.group) 
Example 72
Project: orbit-webdavd   Author: OrbitOS   File: operator.py    MIT License 5 votes vote down vote up
def begin(self, user):
        if self.counter > 1024:
            self.get_groups.cache_clear()
            self.counter = 0

        os.setgroups(self.get_groups(user))
        os.setegid(self.get_pwnam(user)[3])
        os.seteuid(self.get_pwnam(user)[2])
        os.umask(self.umask) 
Example 73
Project: orbit-webdavd   Author: OrbitOS   File: operator.py    MIT License 5 votes vote down vote up
def end(self, user):
        os.umask(0o022)
        os.seteuid(0)
        os.setegid(0)
        os.setgroups(self.get_groups("root")) 
Example 74
Project: mamonsu   Author: postgrespro   File: start.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _try_run_as_postgres(self):
        if platform.LINUX and os.getegid() == 0:
            try:
                uid = pwd.getpwnam('postgres').pw_uid
                os.seteuid(uid)
                return True
            except Exception as e:
                logging.error('Failed run as postgres: {0}'.format(e))
                pass
        return False 
Example 75
Project: mamonsu   Author: postgrespro   File: start.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _try_run_as_postgres(self):
        if platform.LINUX and os.getegid() == 0:
            try:
                uid = pwd.getpwnam('postgres').pw_uid
                os.seteuid(uid)
                return True
            except Exception as e:
                logging.error('Failed run as postgres: {0}'.format(e))
                pass
        return False 
Example 76
Project: open-recipe   Author: dspray95   File: util.py    The Unlicense 4 votes vote down vote up
def switchUID(uid, gid, euid=False):
    """
    Attempts to switch the uid/euid and gid/egid for the current process.

    If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
    this function will issue a L{UserWarning} and not raise an exception.

    @type uid: C{int} or L{None}
    @param uid: the UID (or EUID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type gid: C{int} or L{None}
    @param gid: the GID (or EGID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type euid: C{bool}
    @param euid: if True, set only effective user-id rather than real user-id.
                 (This option has no effect unless the process is running
                 as root, in which case it means not to shed all
                 privileges, retaining the option to regain privileges
                 in cases such as spawning processes. Use with caution.)
    """
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
        getuid = os.geteuid
    else:
        setuid = os.setuid
        setgid = os.setgid
        getuid = os.getuid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        if uid == getuid():
            uidText = (euid and "euid" or "uid")
            actionText = "tried to drop privileges and set{} {}".format(
                uidText, uid)
            problemText = "{} is already {}".format(uidText, getuid())
            warnings.warn("{} but {}; should we be root? Continuing.".format(
                          actionText, problemText))
        else:
            initgroups(uid, gid)
            setuid(uid) 
Example 77
Project: Safejumper-for-Desktop   Author: proxysh   File: util.py    GNU General Public License v2.0 4 votes vote down vote up
def switchUID(uid, gid, euid=False):
    """
    Attempts to switch the uid/euid and gid/egid for the current process.

    If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
    this function will issue a L{UserWarning} and not raise an exception.

    @type uid: C{int} or L{None}
    @param uid: the UID (or EUID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type gid: C{int} or L{None}
    @param gid: the GID (or EGID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type euid: C{bool}
    @param euid: if True, set only effective user-id rather than real user-id.
                 (This option has no effect unless the process is running
                 as root, in which case it means not to shed all
                 privileges, retaining the option to regain privileges
                 in cases such as spawning processes. Use with caution.)
    """
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
        getuid = os.geteuid
    else:
        setuid = os.setuid
        setgid = os.setgid
        getuid = os.getuid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        if uid == getuid():
            uidText = (euid and "euid" or "uid")
            actionText = "tried to drop privileges and set%s %s" % (uidText, uid)
            problemText = "%s is already %s" % (uidText, getuid())
            warnings.warn("%s but %s; should we be root? Continuing."
                          % (actionText, problemText))
        else:
            initgroups(uid, gid)
            setuid(uid) 
Example 78
Project: salt-psu   Author: weswhet   File: mac_prefs.py    Apache License 2.0 4 votes vote down vote up
def list_(name, user, host, runas=None, values=False):
    '''
    List all Keys in the given doamin.

    name
        The preference domain to get keys from.

    value
        Pass true to return a dictionary of the key value pairs.

    :rtype: list,dict

    CLI Example:

    .. code-block:: bash

        salt '*' prefs.list com.apple.ScreenSaver
        salt '*' prefs.list com.apple.ScreenSaver True
    '''

    log.debug('Gathering Key List for {}'.format(name))
    if (runas and not host) or (runas and not user)\
        or (runas and not user and not host):
        raise CommandExecutionError(
            'If using "runas" you must specify a "user" and "host" domains.'
        )
    if user and not host or host and not user:
        raise CommandExecutionError(
            'If using "host" or "user" you must specify both not just one.'
        )
    user_domain, host_domain = _get_user_and_host(user, host)
    if runas:
        try:
            # convert to uid for later use.
            uid = pwd.getpwnam(runas).pw_uid
        except KeyError:
            raise CommandExecutionError(
                'Set to runas user [{}], this user'
                ' does not exist.'.format(runas)
            )
        # need to run as the user
        log.debug('Setting EUID to [{}]'.format(runas))
        os.seteuid(uid)
    key_list = Foundation.CFPreferencesCopyKeyList(name, user_domain, host_domain)
    os.seteuid(0)
    con_key_list = _convert_pyobjc_objects(key_list)
    if not values:
        return con_key_list

    value_dict = dict()

    try:
        for item in con_key_list:
            value_dict[item] = read(item, name, user, host, runas)
    except TypeError:
        return None

    return value_dict 
Example 79
Project: weibo_twitter_earnings_analysis   Author: lynings   File: util.py    Apache License 2.0 4 votes vote down vote up
def switchUID(uid, gid, euid=False):
    """
    Attempts to switch the uid/euid and gid/egid for the current process.

    If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
    this function will issue a L{UserWarning} and not raise an exception.

    @type uid: C{int} or L{None}
    @param uid: the UID (or EUID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type gid: C{int} or L{None}
    @param gid: the GID (or EGID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type euid: C{bool}
    @param euid: if True, set only effective user-id rather than real user-id.
                 (This option has no effect unless the process is running
                 as root, in which case it means not to shed all
                 privileges, retaining the option to regain privileges
                 in cases such as spawning processes. Use with caution.)
    """
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
        getuid = os.geteuid
    else:
        setuid = os.setuid
        setgid = os.setgid
        getuid = os.getuid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        if uid == getuid():
            uidText = (euid and "euid" or "uid")
            actionText = "tried to drop privileges and set%s %s" % (uidText, uid)
            problemText = "%s is already %s" % (uidText, getuid())
            warnings.warn("%s but %s; should we be root? Continuing."
                          % (actionText, problemText))
        else:
            initgroups(uid, gid)
            setuid(uid) 
Example 80
Project: learn_python3_spider   Author: wistbean   File: util.py    MIT License 4 votes vote down vote up
def switchUID(uid, gid, euid=False):
    """
    Attempts to switch the uid/euid and gid/egid for the current process.

    If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}),
    this function will issue a L{UserWarning} and not raise an exception.

    @type uid: C{int} or L{None}
    @param uid: the UID (or EUID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type gid: C{int} or L{None}
    @param gid: the GID (or EGID) to switch the current process to. This
                parameter will be ignored if the value is L{None}.

    @type euid: C{bool}
    @param euid: if True, set only effective user-id rather than real user-id.
                 (This option has no effect unless the process is running
                 as root, in which case it means not to shed all
                 privileges, retaining the option to regain privileges
                 in cases such as spawning processes. Use with caution.)
    """
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
        getuid = os.geteuid
    else:
        setuid = os.setuid
        setgid = os.setgid
        getuid = os.getuid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        if uid == getuid():
            uidText = (euid and "euid" or "uid")
            actionText = "tried to drop privileges and set{} {}".format(
                uidText, uid)
            problemText = "{} is already {}".format(uidText, getuid())
            warnings.warn("{} but {}; should we be root? Continuing.".format(
                          actionText, problemText))
        else:
            initgroups(uid, gid)
            setuid(uid)