Python os.setuid() Examples

The following are 30 code examples of os.setuid(). 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: acehttp.py    From HTTPAceProxy with GNU General Public License v3.0 6 votes vote down vote up
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    try: import pwd, grp
    except ImportError: return False # Windows

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

    # Remove group privileges
    os.setgroups([])

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

    # Ensure a very conservative umask
    old_umask = os.umask(int('077', 8))
    value = (os.getuid() == running_uid and os.getgid() == running_gid)
    if value:  # could be useful
       os.environ['HOME'] = running_uid_home
       logger.info('Changed permissions to: %s: %i, %s, %i' % (uid_name, running_uid, gid_name, running_gid))
    return value 
Example #2
Source File: ext_daemon.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def switch(self):
        """
        Switch the current process's user/group to ``self.user``, and
        ``self.group``.  Change directory to ``self.dir``, and write the
        current pid out to ``self.pid_file``.
        """
        # set the running uid/gid
        LOG.debug('setting process uid(%s) and gid(%s)' %
                  (self.user.pw_uid, self.group.gr_gid))
        os.setgid(self.group.gr_gid)
        os.setuid(self.user.pw_uid)
        os.environ['HOME'] = self.user.pw_dir
        os.chdir(self.dir)
        if self.pid_file and os.path.exists(self.pid_file):
            raise exc.FrameworkError("Process already running (%s)" %
                                     self.pid_file)
        else:
            self._write_pid_file() 
Example #3
Source File: process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #4
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_mockPTYSetUid(self):
        """
        Try creating a PTY process with setting its uid: it's almost the same
        path as the standard path, but with a C{switchUID} call before the
        exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=True, uid=8081)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), 'setsid', ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8081, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #5
Source File: SetEnvironment.py    From Resetter with GNU General Public License v3.0 6 votes vote down vote up
def createDirs(self):
        uid_change = pwd.getpwnam(self.user).pw_uid
        gid_change = pwd.getpwnam(self.user).pw_gid
        pidx = os.fork()
        if pidx == 0:
            try:
                os.setgid(gid_change)
                os.setuid(uid_change)
                if not os.path.exists(self.directory):
                    os.makedirs(self.directory)
                os.chdir(self.directory)
                man_dir = os.path.abspath("manifests")
                userlists_dir = os.path.abspath("userlists")
                self.copy(self.manifests, man_dir)
                self.copy(self.userlists, userlists_dir)
            finally:
                os._exit(0)
        os.waitpid(pidx, 0) 
Example #6
Source File: _privdrop_unix.py    From py_daemoniker with The Unlicense 6 votes vote down vote up
def _setuser(user):
    ''' Normalizes user to a uid and sets the current uid, or does 
    nothing if user is None.
    '''
    if user is None:
        return
        
    # Normalize group to gid
    elif isinstance(user, str):
        uid = pwd.getpwnam(user).pw_uid
    # The group is already a gid.
    else:
        uid = user
        
    try:
        os.setuid(uid)
    except OSError:
        self.logger.error('Unable to change user.')
        sys.exit(1) 
Example #7
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_mockSetUid(self):
        """
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=False, uid=8080)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8080, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #8
Source File: daemon.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def change_process_owner(uid, gid):
    """ Change the owning UID and GID of this process.

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

        """
    try:
        os.setgid(gid)
        os.setuid(uid)
    except Exception, exc:
        error = DaemonOSEnvironmentError(
            "Unable to change file creation mask (%(exc)s)"
            % vars())
        raise error 
Example #9
Source File: systemctl3.py    From vanilla-docker with MIT License 6 votes vote down vote up
def shutil_setuid(user = None, group = None):
    """ set fork-child uid/gid (returns pw-info env-settings)"""
    if group:
        import grp
        gid = grp.getgrnam(group).gr_gid
        os.setgid(gid)
        logg.debug("setgid %s '%s'", gid, group)
    if user:
        import pwd
        pw = pwd.getpwnam(user)
        if not group:
            gid = pw.pw_gid
            os.setgid(gid)
            logg.debug("setgid %s", gid)
        uid = pw.pw_uid
        os.setuid(uid)
        logg.debug("setuid %s '%s'", uid, user)
        home = pw.pw_dir
        shell = pw.pw_shell
        logname = pw.pw_name
        return { "USER": user, "LOGNAME": logname, "HOME": home, "SHELL": shell }
    return {} 
Example #10
Source File: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_mockSetUid(self):
        """
        Try creating a process with setting its uid: it's almost the same path
        as the standard path, but with a C{switchUID} call before the exec.
        """
        cmd = b'/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        try:
            reactor.spawnProcess(p, cmd, [b'ouch'], env=None,
                                 usePTY=False, uid=8080)
        except SystemError:
            self.assertTrue(self.mockos.exited)
            self.assertEqual(
                self.mockos.actions,
                [('fork', False), ('setuid', 0), ('setgid', 0),
                 ('switchuid', 8080, 1234), 'exec', ('exit', 1)])
        else:
            self.fail("Should not be here") 
Example #11
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 #12
Source File: process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #13
Source File: utils.py    From barman with GNU General Public License v3.0 6 votes vote down vote up
def drop_privileges(user):
    """
    Change the system user of the current python process.

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

    :param string user: target user
    :raise KeyError: if the target user doesn't exists
    :raise OSError: when the user change fails
    """
    pw = pwd.getpwnam(user)
    if pw.pw_uid == os.getuid():
        return
    groups = [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem]
    groups.append(pw.pw_gid)
    os.setgroups(groups)
    os.setgid(pw.pw_gid)
    os.setuid(pw.pw_uid)
    os.environ['HOME'] = pw.pw_dir 
Example #14
Source File: subprocess.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def demote(self, uid, gid):
        def fn_uid_gid():
            os.setgid(gid)
            os.setuid(uid)

        def fn_uid():
            os.setuid(uid)

        def fn_gid():
            os.setgid(gid)

        def fn_nop():
            pass

        if uid and gid:
            return fn_uid_gid
        elif uid:
            return fn_uid
        elif gid:
            return fn_gid
        return fn_nop 
Example #15
Source File: ext_daemon.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def switch(self):
        """
        Switch the current process's user/group to ``self.user``, and
        ``self.group``.  Change directory to ``self.dir``, and write the
        current pid out to ``self.pid_file``.
        """
        # set the running uid/gid
        LOG.debug('setting process uid(%s) and gid(%s)' %
                  (self.user.pw_uid, self.group.gr_gid))
        os.setgid(self.group.gr_gid)
        os.setuid(self.user.pw_uid)
        os.environ['HOME'] = self.user.pw_dir
        os.chdir(self.dir)
        if self.pid_file and os.path.exists(self.pid_file):
            raise exc.FrameworkError("Process already running (%s)" %
                                     self.pid_file)
        else:
            self._write_pid_file() 
Example #16
Source File: endpoints.py    From qpid-python with Apache License 2.0 5 votes vote down vote up
def testEINTR(self):
    m1 = self.content("testEINTR", 0)
    m2 = self.content("testEINTR", 1)

    self.snd.send(m1, timeout=self.timeout())
    try:
      os.setuid(500)
      assert False, "setuid should fail"
    except:
      pass
    self.snd.send(m2, timeout=self.timeout()) 
Example #17
Source File: oschameleonRun.py    From oschameleon with MIT License 5 votes vote down vote up
def drop_privileges(self, uid_name='nobody', gid_name='nogroup'):
        if self.args.debug:
            print("Init: Running as {0}/{1}.".format(pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0]))
        wanted_uid = pwd.getpwnam(uid_name)[2]
        wanted_gid = grp.getgrnam(gid_name)[2]

        pid = gevent.fork()
        # print "root_fork : drop_privil  :  pid   ",pid
        if pid == 0:
            # child
            # print  ('starting child process')
            child_process = gevent.spawn(self.root_process)
            child_process.join()
            # print  ('Child done:', child_process.successful())
            flush_tables()
            # print  ('Child exit')
        else:
            # parent
            os.setgid(wanted_gid)
            os.setuid(wanted_uid)
            new_uid_name = pwd.getpwuid(os.getuid())[0]
            new_gid_name = grp.getgrgid(os.getgid())[0]
            if self.args.debug:
                print("Parent: Privileges dropped, running as {0}/{1}.".format(new_uid_name, new_gid_name))
            while True:
                try:
                    gevent.sleep(1)
                    # print ('Parent: ping')
                except KeyboardInterrupt:
                    break 
Example #18
Source File: root_fork.py    From oschameleon with MIT License 5 votes vote down vote up
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
    print("Init: Running as {0}/{1}.".format(pwd.getpwuid(os.getuid())[0], grp.getgrgid(os.getgid())[0]))
    wanted_uid = pwd.getpwnam(uid_name)[2]
    wanted_gid = grp.getgrnam(gid_name)[2]

    pid = gevent.fork()
    # print "root_fork : drop_privil  :  pid   ",pid
    if pid == 0:
        # child
        print ('starting child process')
        child_process = gevent.spawn(root_process)
        child_process.join()
        print ('Child done:', child_process.successful())
        flush_tables()
        print ('Child exit')
    else:
        # parent
        os.setgid(wanted_gid)
        os.setuid(wanted_uid)
        new_uid_name = pwd.getpwuid(os.getuid())[0]
        new_gid_name = grp.getgrgid(os.getgid())[0]
        print("Parent: Privileges dropped, running as {0}/{1}.".format(new_uid_name, new_gid_name))
        while True:
            try:
                gevent.sleep(1)
                print ('Parent: ping')
            except KeyboardInterrupt:
                break 
Example #19
Source File: daemon.py    From ssrr with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

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

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example #20
Source File: subprocess.py    From service-manager with Apache License 2.0 5 votes vote down vote up
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno 
Example #21
Source File: daemon.py    From SSRSpeed with GNU General Public License v3.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

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

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example #22
Source File: daemon.py    From Dockerfiles with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

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

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example #23
Source File: _cpcompat_subprocess.py    From opsbro with MIT License 5 votes vote down vote up
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno 
Example #24
Source File: netstat.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def drop_privileges():
    """Drops privileges if running as root."""
    try:
        ent = pwd.getpwnam(USER)
    except KeyError:
        return

    if os.getuid() != 0:
        return

    os.setgid(ent.pw_gid)
    os.setuid(ent.pw_uid) 
Example #25
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_setuid(self):
        if os.getuid() != 0:
            self.assertRaises(OSError, os.setuid, 0)
        self.assertRaises(OverflowError, os.setuid, 1<<32) 
Example #26
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_setuid(self):
        if os.getuid() != 0:
            self.assertRaises(OSError, os.setuid, 0)
        self.assertRaises(OverflowError, os.setuid, 1<<32) 
Example #27
Source File: subprocess_hack.py    From advanced-launcher with GNU General Public License v2.0 5 votes vote down vote up
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno 
Example #28
Source File: spark_gce.py    From spark_gce with Apache License 2.0 5 votes vote down vote up
def enable_sudo(master,command):
	'''
	ssh_command(master,"echo \"import os\" > setuid.py ")
	ssh_command(master,"echo \"import sys\" >> setuid.py")
	ssh_command(master,"echo \"import commands\" >> setuid.py")
	ssh_command(master,"echo \"command=sys.argv[1]\" >> setuid.py")
	ssh_command(master,"echo \"os.setuid(os.geteuid())\" >> setuid.py")
	ssh_command(master,"echo \"print commands.getstatusoutput(\"command\")\" >> setuid.py")
	'''
	os.system("ssh -i " + identity_file + " -t -o 'UserKnownHostsFile=/dev/null' -o 'CheckHostIP=no' -o 'StrictHostKeyChecking no' "+ username + "@" + master + " '" + command + "'") 
Example #29
Source File: daemon.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

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

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example #30
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def setuid(self, val):
        """
        Override C{os.setuid}. Do nothing.
        """
        self.actions.append(('setuid', val))