Python os.setegid() Examples

The following are 30 code examples of os.setegid(). 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: pamauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def callIntoPAM(service, user, conv):
    """A testing hook.
    """
    pam = PAM.pam()
    pam.start(service)
    pam.set_item(PAM.PAM_USER, user)
    pam.set_item(PAM.PAM_CONV, conv)
    gid = os.getegid()
    uid = os.geteuid()
    os.setegid(0)
    os.seteuid(0)
    try:
        pam.authenticate() # these will raise
        pam.acct_mgmt()
        return 1
    finally:
        os.setegid(gid)
        os.seteuid(uid) 
Example #2
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 #3
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 #4
Source File: bdistutils.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def get_cdv_change_code():
    
        # cdv won't run on the dev machines as root.  nfs does not allow
        # root access to mounted drives.  --Dave
        if os.getuid() == 0 and getuid_for_path(".") != 0:
            seteugid_to_login()
    
        # fragile. XXXX
        l = os.popen("cdv history -c 1").readlines()[0].split(" ")
        if os.getuid() == 0:
            os.seteuid(0)
            #os.setegid(oldgid)
    
        l = [x.strip() for x in l if x.strip() != '']  # remove empty strings.
        x,code,x,x,x,x,dow,mo,dom,t,y = l
        month = "%.2d" % (months.index(mo)+1)
        dom = "%.2d" % int(dom)    # single digit day of month like 3 becomes 03
        t = "_".join(t.split(':')) # convert ':' to underscores in time.
        return y+"_"+month+"_"+dom+"_"+t+"_"+code 
Example #5
Source File: bdistutils.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def get_cdv_change_code():
    
        # cdv won't run on the dev machines as root.  nfs does not allow
        # root access to mounted drives.  --Dave
        if os.getuid() == 0 and getuid_for_path(".") != 0:
            seteugid_to_login()
    
        # fragile. XXXX
        l = os.popen("cdv history -c 1").readlines()[0].split(" ")
        if os.getuid() == 0:
            os.seteuid(0)
            #os.setegid(oldgid)
    
        l = [x.strip() for x in l if x.strip() != '']  # remove empty strings.
        x,code,x,x,x,x,dow,mo,dom,t,y = l
        month = "%.2d" % (months.index(mo)+1)
        dom = "%.2d" % int(dom)    # single digit day of month like 3 becomes 03
        t = "_".join(t.split(':')) # convert ':' to underscores in time.
        return y+"_"+month+"_"+dom+"_"+t+"_"+code 
Example #6
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 #7
Source File: identity.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def validatePublicKey(self, pubKeyString):
        home = os.path.expanduser('~%s/.ssh/' % self.name)
        if home[0] == '~': # couldn't expand
            return defer.fail(Unauthorized('not valid user'))
        uid, gid = os.geteuid(), os.getegid()
        ouid, ogid = pwd.getpwnam(self.name)[2:4]
        os.setegid(ogid)
        os.seteuid(ouid)
        for file in ['authorized_keys', 'authorized_keys2']:
            if os.path.exists(home+file):
                lines = open(home+file).readlines()
                for l in lines:
                    try:
                        l2 = l.split()
                        if len(l2) < 2:
                            continue
                        if base64.decodestring(l2[1])==pubKeyString:
                            os.setegid(gid)
                            os.seteuid(uid)
                            return defer.succeed('')
                    except binascii.Error:
                        pass # we caught an ssh1 key
        os.setegid(gid)
        os.seteuid(uid)
        return defer.fail(error.ConchError('not valid key')) 
Example #8
Source File: snappy.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def change_user(username, effective=False):
    """Change running user, by default to the non-root user."""
    running_uid = pwd.getpwnam(username).pw_uid
    running_gid = grp.getgrnam(username).gr_gid
    os.setgroups([])
    if effective:
        os.setegid(running_gid)
        os.seteuid(running_uid)
    else:
        os.setgid(running_gid)
        os.setuid(running_uid) 
Example #9
Source File: app.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def setEUID(self):
        """Retrieve persistent uid/gid pair (if possible) and set the current
        process's euid/egid.
        """
        try:
            os.setegid(self.gid)
            os.seteuid(self.uid)
        except (AttributeError, OSError):
            pass
        else:
            log.msg('set euid/egid %s/%s' % (self.uid, self.gid)) 
Example #10
Source File: bdistutils.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def seteugid_to_login():
        """set effective user id and effective group id to the user and group ids
           of the user logged into this terminal."""
        uid = pwd.getpwnam(os.getlogin())[2]  # search /etc/passwd for uid and
        gid = pwd.getpwnam(os.getlogin())[3]  # gid of user logged into this
                                              # terminal.
        os.setegid(gid)
        os.seteuid(uid)                       # Is there a better way? --Dave 
Example #11
Source File: factory.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def getPrivateKeys(self):
        ks = {}
        euid,egid = os.geteuid(), os.getegid()
        os.setegid(0) # gain priviledges
        os.seteuid(0)
        for file in os.listdir(self.dataRoot):
            if file[:9] == 'ssh_host_' and file[-4:]=='_key':
                try:
                    k = keys.getPrivateKeyObject(self.dataRoot+'/'+file)
                    t = keys.objectType(k)
                    ks[t] = k
                except Exception, e:
                    log.msg('bad private key file %s: %s' % (file, e)) 
Example #12
Source File: authorizers.py    From pyftpdlib with 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 #13
Source File: test_os.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_setegid(self):
                if os.getuid() != 0:
                    self.assertRaises(os.error, os.setegid, 0)
                self.assertRaises(OverflowError, os.setegid, 1<<32) 
Example #14
Source File: daemon.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __exit__(self, *args):
            if self._olduid is None or self._oldgid is None:
                return

            try:
                os.setegid(self._oldgid)
                os.seteuid(self._olduid)

            except Exception:
                raise error.SnmpfwdError(
                    'setegid()/seteuid() failed for %s/%s: %s' % (
                        self._oldgid, self._olduid, sys.exc_info()[1])) 
Example #15
Source File: unix.py    From BitTorrent with GNU General Public License v3.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 #16
Source File: unix.py    From BitTorrent with GNU General Public License v3.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 #17
Source File: checkers.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def requestAvatarId(self, credentials):
        if pwd:
            try:
                cryptedPass = pwd.getpwnam(credentials.username)[1]
            except KeyError:
                return defer.fail(UnauthorizedLogin())
            else:
                if cryptedPass not in ['*', 'x'] and \
                    verifyCryptedPassword(cryptedPass, credentials.password):
                    return defer.succeed(credentials.username)
        if shadow:
            gid = os.getegid()
            uid = os.geteuid()
            os.setegid(0)
            os.seteuid(0)
            try:
                shadowPass = shadow.getspnam(credentials.username)[1]
            except KeyError:
                os.setegid(gid)
                os.seteuid(uid)
                return defer.fail(UnauthorizedLogin())
            os.setegid(gid)
            os.seteuid(uid)
            if verifyCryptedPassword(shadowPass, credentials.password):
                return defer.succeed(credentials.username)
            return defer.fail(UnauthorizedLogin())
        
        return defer.fail(UnauthorizedLogin()) 
Example #18
Source File: test_os.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def test_setegid(self):
                if os.getuid() != 0:
                    self.assertRaises(os.error, os.setegid, 0)
                self.assertRaises(OverflowError, os.setegid, 1<<32) 
Example #19
Source File: bdistutils.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def seteugid_to_login():
        """set effective user id and effective group id to the user and group ids
           of the user logged into this terminal."""
        uid = pwd.getpwnam(os.getlogin())[2]  # search /etc/passwd for uid and
        gid = pwd.getpwnam(os.getlogin())[3]  # gid of user logged into this
                                              # terminal.
        os.setegid(gid)
        os.seteuid(uid)                       # Is there a better way? --Dave 
Example #20
Source File: daemon.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def main():
    #change to data directory if needed
    os.chdir("/root/data")
    #redirect outputs to a logfile
    sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
    #ensure the that the daemon runs a normal user
    os.setegid(103)     #set group first "pydaemon"
    os.seteuid(103)     #set user "pydaemon"
    #start the user program here:
    USERPROG() 
Example #21
Source File: rack_script.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_group():
    # Ensure that we're running as the `maas` group.
    try:
        gr_maas = grp.getgrnam("maas")
    except KeyError:
        raise SystemExit("No such group: maas")
    else:
        os.setegid(gr_maas.gr_gid) 
Example #22
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_setegid(self):
        if os.getuid() != 0 and not HAVE_WHEEL_GROUP:
            self.assertRaises(OSError, os.setegid, 0)
        self.assertRaises(OverflowError, os.setegid, 1<<32) 
Example #23
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def setegid(self, egid):
        """
        Mock C{os.setegid}, store result.
        """
        self.setegidCalls.append(egid) 
Example #24
Source File: unix.py    From python-for-android with 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 #25
Source File: checkers.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def requestAvatarId(self, credentials):
        if pwd:
            try:
                cryptedPass = pwd.getpwnam(credentials.username)[1]
            except KeyError:
                return defer.fail(UnauthorizedLogin("invalid username"))
            else:
                if cryptedPass not in ['*', 'x'] and \
                    verifyCryptedPassword(cryptedPass, credentials.password):
                    return defer.succeed(credentials.username)
        if shadow:
            gid = os.getegid()
            uid = os.geteuid()
            os.setegid(0)
            os.seteuid(0)
            try:
                shadowPass = shadow.getspnam(credentials.username)[1]
            except KeyError:
                os.setegid(gid)
                os.seteuid(uid)
                return defer.fail(UnauthorizedLogin("invalid username"))
            os.setegid(gid)
            os.seteuid(uid)
            if verifyCryptedPassword(shadowPass, credentials.password):
                return defer.succeed(credentials.username)
            return defer.fail(UnauthorizedLogin("invalid password"))

        return defer.fail(UnauthorizedLogin("unable to verify password")) 
Example #26
Source File: util.py    From python-for-android with 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 #27
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def switchUID(uid, gid, euid=False):
    if euid:
        setuid = os.seteuid
        setgid = os.setegid
    else:
        setuid = os.setuid
        setgid = os.setgid
    if gid is not None:
        setgid(gid)
    if uid is not None:
        initgroups(uid, gid)
        setuid(uid) 
Example #28
Source File: region_script.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def set_group():
    # Ensure that we're running as the `maas` group.
    try:
        gr_maas = grp.getgrnam("maas")
    except KeyError:
        raise SystemExit("No such group: maas")
    else:
        os.setegid(gr_maas.gr_gid) 
Example #29
Source File: test_os.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_setegid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.setegid, 0)
        self.assertRaises(TypeError, os.setegid, 'not an int')
        self.assertRaises(OverflowError, os.setegid, 1<<32) 
Example #30
Source File: test_process.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self)