Python os.seteuid() Examples
The following are 30
code examples of os.seteuid().
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: irc.py From localslackirc with GNU General Public License v3.0 | 6 votes |
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 #2
Source File: test_checkers.py From python-for-android with Apache License 2.0 | 6 votes |
def test_checkKeyAsRoot(self): """ If the key file is readable, L{SSHPublicKeyDatabase.checkKey} should switch its uid/gid to the ones of the authenticated user. """ keyFile = self.sshDir.child("authorized_keys") keyFile.setContent(self.content) # Fake permission error by changing the mode keyFile.chmod(0000) self.addCleanup(keyFile.chmod, 0777) # And restore the right mode when seteuid is called savedSeteuid = os.seteuid def seteuid(euid): keyFile.chmod(0777) return savedSeteuid(euid) self.patch(os, "seteuid", seteuid) user = UsernamePassword("user", "password") user.blob = "foobar" self.assertTrue(self.checker.checkKey(user)) self.assertEquals(self.mockos.seteuidCalls, [0, 1, 0, os.getuid()]) self.assertEquals(self.mockos.setegidCalls, [2, os.getgid()])
Example #3
Source File: test_checkers.py From python-for-android with Apache License 2.0 | 6 votes |
def setUp(self): self.checker = SSHPublicKeyDatabase() self.key1 = base64.encodestring("foobar") self.key2 = base64.encodestring("eggspam") self.content = "t1 %s foo\nt2 %s egg\n" % (self.key1, self.key2) self.mockos = MockOS() self.mockos.path = FilePath(self.mktemp()) self.mockos.path.makedirs() self.sshDir = self.mockos.path.child('.ssh') self.sshDir.makedirs() userdb = UserDatabase() userdb.addUser('user', 'password', 1, 2, 'first last', self.mockos.path.path, '/bin/shell') self.patch(pwd, "getpwnam", userdb.getpwnam) self.patch(os, "seteuid", self.mockos.seteuid) self.patch(os, "setegid", self.mockos.setegid)
Example #4
Source File: __main__.py From NordVPN-NetworkManager with GNU General Public License v3.0 | 6 votes |
def main(): if os.getuid() != 0: print("%s must be run as root. Exiting." % __package__) sys.exit(1) # We are running with root priveledges, which is kinda scary, so lets switch to the original user until we actually need root (if there is one) user_uid = os.getenv("SUDO_UID") if user_uid: os.seteuid(int(user_uid)) # Add our custom logging formatter function to handle all logging output formatter = utils.LoggingFormatter() loggingHandler = logging.StreamHandler(sys.stdout) loggingHandler.setFormatter(formatter) logging.root.addHandler(loggingHandler) logging.root.setLevel(logging.INFO) signal.signal(signal.SIGINT, sig_clean_exit) nordnm.NordNM()
Example #5
Source File: bdistutils.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
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: test_openssh_compat.py From python-for-android with Apache License 2.0 | 6 votes |
def setUp(self): self.factory = OpenSSHFactory() self.keysDir = FilePath(self.mktemp()) self.keysDir.makedirs() self.factory.dataRoot = self.keysDir.path self.keysDir.child("ssh_host_foo").setContent("foo") self.keysDir.child("bar_key").setContent("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( "not a key content") self.keysDir.child("ssh_host_one_key.pub").setContent( keydata.publicRSA_openssh) self.mockos = MockOS() self.patch(os, "seteuid", self.mockos.seteuid) self.patch(os, "setegid", self.mockos.setegid)
Example #7
Source File: bdistutils.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
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 #8
Source File: wsdd.py From wsdd with MIT License | 6 votes |
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 #9
Source File: pamauth.py From python-for-android with Apache License 2.0 | 6 votes |
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 #10
Source File: test_openssh_compat.py From python-for-android with Apache License 2.0 | 6 votes |
def test_getPrivateKeysAsRoot(self): """ L{OpenSSHFactory.getPrivateKeys} should switch to root if the keys aren't readable by the current user. """ keyFile = self.keysDir.child("ssh_host_two_key") # Fake permission error by changing the mode keyFile.chmod(0000) self.addCleanup(keyFile.chmod, 0777) # And restore the right mode when seteuid is called savedSeteuid = os.seteuid def seteuid(euid): keyFile.chmod(0777) return savedSeteuid(euid) self.patch(os, "seteuid", seteuid) keys = self.factory.getPrivateKeys() self.assertEquals(len(keys), 2) keyTypes = keys.keys() self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss'])) self.assertEquals(self.mockos.seteuidCalls, [0, os.geteuid()]) self.assertEquals(self.mockos.setegidCalls, [0, os.getegid()])
Example #11
Source File: identity.py From BitTorrent with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: proctools.py From pycopia with Apache License 2.0 | 6 votes |
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: daemon.py From snmpfwd with BSD 2-Clause "Simplified" License | 5 votes |
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 #14
Source File: unix.py From python-for-android with Apache License 2.0 | 5 votes |
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 #15
Source File: checkers.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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 #16
Source File: unix.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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: unix.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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 #18
Source File: test_os.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_seteuid(self): if os.getuid() != 0: self.assertRaises(os.error, os.seteuid, 0) self.assertRaises(OverflowError, os.seteuid, 1<<32)
Example #19
Source File: authorizers.py From pyftpdlib with MIT License | 5 votes |
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 #20
Source File: factory.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
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 #21
Source File: security.py From workload-collocation-agent with Apache License 2.0 | 5 votes |
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 #22
Source File: checkers.py From python-for-android with Apache License 2.0 | 5 votes |
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 #23
Source File: util.py From python-for-android with Apache License 2.0 | 5 votes |
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 #24
Source File: util.py From python-for-android with Apache License 2.0 | 5 votes |
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 #25
Source File: test_os.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_seteuid(self): if os.getuid() != 0: self.assertRaises(os.error, os.seteuid, 0) self.assertRaises(OverflowError, os.seteuid, 1<<32)
Example #26
Source File: Stella-OpenStack.py From Stella-OpenStack with Apache License 2.0 | 5 votes |
def StellaAPI_Set_SLA_VM(): if not request.json or not 'name' in request.json: abort(400) if not request.json or not 'SLA_Option' in request.json: abort(400) if not request.json or not 'SLA_Value' in request.json: abort(400) _name = request.json['name'] _SLA_option = request.json['SLA_Option'] _SLA_value = request.json['SLA_Value'] count = vms.set_SLA(vms, _name, _SLA_option, _SLA_value) instance_name = vms.get_instance_name_by_name(vms, _name) sla_option = vms.get_sla_option_by_name(vms, _name) sla_value = vms.get_sla_value_by_name(vms, _name) # print(instance_name) # get_ROOT privilege olduid = 0 if os.geteuid() != 0: # running as normal user olduid = os.geteuid() print(olduid) os.seteuid(0) # execute SLA setting script cmd_str = './insert_sla.sh' + ' ' + instance_name + ' ' + sla_option + ' ' + sla_value print(cmd_str) os.system(cmd_str) # reset user privilege if olduid != 0: os.seteuid(olduid) if (count < 0): return jsonify({'message': 'error'}) else: return jsonify(vms.print_all(vms))
Example #27
Source File: daemon.py From d4rkc0de with GNU General Public License v2.0 | 5 votes |
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 #28
Source File: start.py From mamonsu with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _try_run_as_postgres(self): if platform.UNIX and os.getegid() == 0: try: import pwd uid = pwd.getpwnam('postgres').pw_uid os.seteuid(uid) return True except Exception as e: sys.stderr.write("Failed run as postgres: {0}\n".format(e)) pass return False
Example #29
Source File: start.py From mamonsu with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #30
Source File: start.py From mamonsu with BSD 3-Clause "New" or "Revised" License | 5 votes |
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