Beispiel #1
0
def drop_privileges():
    if 'SUDO_GID' in os.environ:
        gid = int(os.environ['SUDO_GID'])
        os.setregid(gid, gid)
    if 'SUDO_UID' in os.environ:
        uid = int(os.environ['SUDO_UID'])
        os.setreuid(uid, uid)
Beispiel #2
0
def drop_privs():
    try:
        new_uid = int(os.getenv('SUDO_UID'))
        new_gid = int(os.getenv('SUDO_GID'))
    except TypeError:
        # they were running directly from a root user and didn't have
        # sudo env variables
        print """[!] WARNING: Couldn't drop privileges! To avoid this error, run from a non-root user.
    You may also use sudo, from a non-root user. Continue? (y/n)""",
        if raw_input().lower()[0] == 'y':
            return
        die()

    debug.info('Dropping privileges to uid: {}, gid: {}'.format(
        new_uid, new_gid))

    # drop group before user, because otherwise you're not privileged enough
    # to drop group
    os.setgroups([])
    os.setregid(new_gid, new_gid)
    os.setreuid(new_uid, new_uid)

    # check to make sure we can't re-escalate
    try:
        os.seteuid(0)
        print '[!] WARNING: Failed to drop privileges! Continue? (y/n)',
        if raw_input().lower()[0] != 'y':
            die()
    except OSError:
        return
Beispiel #3
0
 def _find_tmpdir(self):
     if not self._user_pw:
         return None
     tmpdir = tempfile.gettempdir()
     flags = os.R_OK | os.W_OK | os.X_OK
     os.setreuid(self._user_pw.pw_uid, 0)
     try:
         # check the default directory from $TMPDIR variable
         if os.access(tmpdir, flags):
             return tmpdir
         checked_tmpdirs = [tmpdir]
         # replace pam_tmpdir's directory /tmp/user/0 into e.g. /tmp/user/1000
         if tmpdir.endswith("/0"):
             tmpdir = tmpdir[0:-1] + str(self._user_pw.pw_uid)
             if os.access(tmpdir, flags):
                 return tmpdir
             checked_tmpdirs.append(tmpdir)
         # finally try hard-coded location
         if tmpdir != "/tmp":
             tmpdir = "/tmp"
             if os.access(tmpdir, flags):
                 return tmpdir
             checked_tmpdirs.append(tmpdir)
         raise RuntimeError(
             _("None of the following directories is accessible"
               " by user %(user)s: %(dirs)s") % {
                   'user': self._user_pw.pw_name,
                   'dirs': str(checked_tmpdirs)
               })
     finally:
         os.setuid(0)
Beispiel #4
0
def _validatePath(path, perms):
  """Validate a disk image or other ifle.

  _validatePath makes sure that the user requesting a privileged
  operation would have permission to interact with the file in
  question.

  Args:
    disk: A path to a disk image
    perms: A bitmask composed of os.R_OK, os.W_OK, and/or os.X_OK

  Raises:
    debmarshal.errors.AccessDenied if the unprivileged user doesn't
      have permission to interact with the path using perms.
  """
  # Start by setting the process uid to getCaller(). This is primarily
  # done to make sure we're respecting the abstraction introduced by
  # getCaller().
  #
  # This won't guarantee that we have the necessary bits for, e.g.,
  # AFS, where you need a separate token to prove your identity, but
  # it would work for most other cases.
  old_uid = os.getuid()
  os.setreuid(utils.getCaller(), 0)

  try:
    if not os.access(path, perms):
      raise errors.AccessDenied('UID %s does not have access to %s.' %
                                (utils.getCaller(), path))
  finally:
    # Reset the process uid that we changed earlier.
    os.setuid(old_uid)
Beispiel #5
0
    def run(self):
        """Run Forest, RUN!"""

        exitcode = 0

        utils.ensure_directory(os.path.dirname(conf.pidfile),
                               conf.process_username, conf.process_groupname)

        try:
            try:
                (ruid, euid, suid) = os.getresuid()
                (rgid, egid, sgid) = os.getresgid()
            except AttributeError, errmsg:
                ruid = os.getuid()
                rgid = os.getgid()

            if ruid == 0:
                # Means we can setreuid() / setregid() / setgroups()
                if rgid == 0:
                    # Get group entry details
                    try:
                        (group_name, group_password, group_gid,
                         group_members) = grp.getgrnam(conf.process_groupname)

                    except KeyError:
                        print >> sys.stderr, _("Group %s does not exist") % (
                            conf.process_groupname)

                        sys.exit(1)

                    # Set real and effective group if not the same as current.
                    if not group_gid == rgid:
                        log.debug(
                            _("Switching real and effective group id to %d") %
                            (group_gid),
                            level=8)

                        os.setregid(group_gid, group_gid)

                if ruid == 0:
                    # Means we haven't switched yet.
                    try:
                        (user_name, user_password, user_uid, user_gid,
                         user_gecos, user_homedir,
                         user_shell) = pwd.getpwnam(conf.process_username)

                    except KeyError:
                        print >> sys.stderr, _("User %s does not exist") % (
                            conf.process_username)

                        sys.exit(1)

                    # Set real and effective user if not the same as current.
                    if not user_uid == ruid:
                        log.debug(
                            _("Switching real and effective user id to %d") %
                            (user_uid),
                            level=8)

                        os.setreuid(user_uid, user_uid)
Beispiel #6
0
def initsecurity(config):
    idsetuid = None
    idsetgid = None

    if config.has_option("pygopherd", "setuid"):
        import pwd

        idsetuid = pwd.getpwnam(config.get("pygopherd", "setuid"))[2]

    if config.has_option("pygopherd", "setgid"):
        import grp

        idsetgid = grp.getgrnam(config.get("pygopherd", "setgid"))[2]

    if config.getboolean("pygopherd", "usechroot"):
        os.chroot(config.get("pygopherd", "root"))
        logger.log("Chrooted to " + config.get("pygopherd", "root"))
        config.set("pygopherd", "root", "/")

    if idsetuid != None or idsetgid != None:
        os.setgroups(())
        logger.log("Supplemental group list cleared.")

    if idsetgid != None:
        os.setregid(idsetgid, idsetgid)
        logger.log("Switched to group %d" % idsetgid)

    if idsetuid != None:
        os.setreuid(idsetuid, idsetuid)
        logger.log("Switched to uid %d" % idsetuid)
def main():
    global existing_dir
    global new_name
    global parent_dir
    global new_dir

    parseCmdLine()

    print
    print "=== Renaming directory under original_images directory ==="
    print

    print "Existing directory: ",existing_dir
    print "New name:           ",new_name
    print

    if os.name != "nt":
        os.setreuid(os.geteuid(), -1)

    parent_dir = os.path.dirname(os.path.realpath(existing_dir))

    new_dir = os.path.join(parent_dir, new_name)

    testDirs()

    os.rename(existing_dir, new_dir)

    print "Rename completed."
    print
Beispiel #8
0
    def testServerDownloadWithPrivDropPrivilegedPortUseridOnly(
            self, output='/tmp/out'):
        """Basic test of privilege dropping- the test must be started as root"""
        log.debug(
            "===> Running testcase testServerDownloadWithPrivDropPrivilegedPortUseridOnly"
        )
        root = os.path.dirname(os.path.abspath(__file__))

        server = tftpy.TftpServer(root,
                                  drop_privileges=(VALID_UID, None),
                                  paranoid=False)
        server_thread = threading.Thread(target=server.listen,
                                         kwargs={
                                             'listenip': 'localhost',
                                             'listenport': 69
                                         })
        server_thread.start()

        try:
            server.is_running.wait()
            client = tftpy.TftpClient('localhost', server.listenport, {})
            time.sleep(1)
            client.download('640KBFILE', output)
        finally:
            server.stop(now=False)
            server_thread.join()
            # Remove the file and re-escalate privileges so that they can be dropped
            # again in other privilege dropping test cases. The file must be unlinked
            # because privileges may be dropped to a user that does not have permission
            # to read or write it
            os.unlink(output)
            os.setreuid(ROOT_UID, ROOT_UID)
            os.setregid(ROOT_GID, ROOT_GID)
Beispiel #9
0
    def change_to_user_group(self, insane=None):
        """ Change user of the running program. Just insult the admin if he wants root run (it can override).
If change failed we sys.exit(2) """
        if insane is None:
            insane = not self.idontcareaboutsecurity

        # TODO: change user on nt
        if os.name == 'nt':
            print("Sorry, you can't change user on this system")
            return

        if (self.user == 'root' or self.group == 'root') and not insane:
            print "What's ??? You want the application run under the root account?"
            print "I am not agree with it. If you really want it, put :"
            print "idontcareaboutsecurity=yes"
            print "in the config file"
            print "Exiting"
            sys.exit(2)

        uid = self.find_uid_from_name()
        gid = self.find_gid_from_name()
        if uid is None or gid is None:
            print "Exiting"
            sys.exit(2)
        try:
            # First group, then user :)
            os.setregid(gid, gid)
            os.setreuid(uid, uid)
        except OSError, e:
            print "Error : cannot change user/group to %s/%s (%s [%d])" % (self.user, self.group, e.strerror, e.errno)
            print "Exiting"
            sys.exit(2)
Beispiel #10
0
def demote(username):
    user = pwd.getpwnam(username)

    os.setgroups([])

    os.setregid(user.pw_gid, user.pw_gid)
    os.setreuid(user.pw_uid, user.pw_uid)
Beispiel #11
0
	def generate_file_name(self,from_user,file_name,path,queue,to_user=None):
		
		done=False
		counter=1
		
		original_path=path
		original_file_name=file_name
		file_name="["+from_user+"]_"+file_name
		
		
		if to_user!=None:
			user_uid=pwd.getpwnam(to_user)[2]
			user_gid=pwd.getpwnam(to_user)[3]
			os.setregid(0, user_gid)
			os.setreuid(0, user_uid)

		while not done:
			
			if os.path.exists(path+file_name) or os.path.exists(path+"."+file_name):
				tmp_list=original_file_name.split(".")
				tmp_list[0]=tmp_list[0]+"_("+str(counter)+")"
				file_name=".".join(tmp_list)
				file_name="["+from_user+"]_"+file_name
				counter+=1
			else:
				done=True
		
		f=open(path+"."+file_name,'w')
		f.close()	
		queue.put(file_name)
Beispiel #12
0
def drop_privileges(user, group):
    if user is None:
        uid = os.getuid()
    elif user.lstrip("-").isdigit():
        uid = int(user)
    else:
        uid = pwd.getpwnam(user).pw_uid

    if group is None:
        gid = os.getgid()
    elif group.lstrip("-").isdigit():
        gid = int(group)
    else:
        gid = grp.getgrnam(group).gr_gid

    username = pwd.getpwuid(uid).pw_name
    # groupname = grp.getgrgid(gid).gr_name
    groups = [g for g in grp.getgrall() if username in g.gr_mem]

    os.setgroups(groups)
    if hasattr(os, 'setresgid'):
        os.setresgid(gid, gid, gid)
    else:
        os.setregid(gid, gid)
    if hasattr(os, 'setresuid'):
        os.setresuid(uid, uid, uid)
    else:
        os.setreuid(uid, uid)
Beispiel #13
0
def switchUserPreVeil():
    if sys.platform in ["darwin", "linux2"]:
        preveil_pwuid = pwd.getpwnam("preveil")
        os.setregid(preveil_pwuid.pw_gid, preveil_pwuid.pw_gid)
        os.setreuid(preveil_pwuid.pw_uid, preveil_pwuid.pw_uid)
    elif "win32" == sys.platform:
        pass
Beispiel #14
0
def drop_privs():
    try:
        new_uid = int(os.getenv('SUDO_UID'))
        new_gid = int(os.getenv('SUDO_GID'))
    except TypeError:
        # they were running directly from a root user and didn't have
        # sudo env variables
        print """[!] WARNING: Couldn't drop privileges! To avoid this error, run from a non-root user.
    You may also use sudo, from a non-root user. Continue? (y/n)""",
        if raw_input().lower()[0] == 'y':
            return
        die()

    debug.info('Dropping privileges to uid: {}, gid: {}'.format(new_uid,
                                                                new_gid))

    # drop group before user, because otherwise you're not privileged enough
    # to drop group
    os.setgroups([])
    os.setregid(new_gid, new_gid)
    os.setreuid(new_uid, new_uid)

    # check to make sure we can't re-escalate
    try:
        os.seteuid(0)
        print '[!] WARNING: Failed to drop privileges! Continue? (y/n)',
        if raw_input().lower()[0] != 'y':
            die()
    except OSError:
        return
Beispiel #15
0
def init_security(config: ConfigParser) -> None:
    uid = None
    gid = None

    if config.has_option("pygopherd", "setuid"):
        import pwd

        uid = pwd.getpwnam(config.get("pygopherd", "setuid"))[2]

    if config.has_option("pygopherd", "setgid"):
        import grp

        gid = grp.getgrnam(config.get("pygopherd", "setgid"))[2]

    if config.getboolean("pygopherd", "usechroot"):
        chroot_user = config.get("pygopherd", "root")
        os.chroot(chroot_user)
        logger.log(f"Chrooted to {chroot_user}")
        config.set("pygopherd", "root", "/")

    if uid is not None or gid is not None:
        os.setgroups(())
        logger.log("Supplemental group list cleared.")

    if gid is not None:
        os.setregid(gid, gid)
        logger.log(f"Switched to group {gid}")

    if uid is not None:
        os.setreuid(uid, uid)
        logger.log(f"Switched to uid {uid}")
Beispiel #16
0
def drop_priv(uid_name='nobody', gid_name='nogroup'):
    import os, pwd, grp

    xuid = os.getuid()
    xgid = os.getgid()

    xname = pwd.getpwuid(xuid).pw_name

    if os.getuid() != 0:
        return

    if xuid == 0:
        run_uid = pwd.getpwnam(uid_name).pw_uid
        run_gid = grp.getgrnam(gid_name).gr_gid

        try:
            os.setgroups([run_gid])
            os.setgid(run_gid)
            os.setregid(run_gid, run_gid)
        except OSError, e:
            print "cannot set gid to %s" % gid_name
        try:
            os.setuid(run_uid)
            os.setreuid(run_uid, run_uid)
        except OSError, e:
            print "cannot set uid to %s" % uid_name
Beispiel #17
0
def initsecurity(config):
    idsetuid = None
    idsetgid = None

    if config.has_option("pygopherd", "setuid"):
        import pwd
        idsetuid = pwd.getpwnam(config.get("pygopherd", "setuid"))[2]

    if config.has_option("pygopherd", "setgid"):
        import grp
        idsetgid = grp.getgrnam(config.get("pygopherd", "setgid"))[2]

    if config.getboolean("pygopherd", "usechroot"):
        os.chroot(config.get("pygopherd", "root"))
        logger.log("Chrooted to " + config.get("pygopherd", "root"))
        config.set("pygopherd", "root", "/")

    if idsetuid != None or idsetgid != None:
        os.setgroups( () )
        logger.log("Supplemental group list cleared.")

    if idsetgid != None:
        os.setregid(idsetgid, idsetgid)
        logger.log("Switched to group %d" % idsetgid)

    if idsetuid != None:
        os.setreuid(idsetuid, idsetuid)
        logger.log("Switched to uid %d" % idsetuid)
Beispiel #18
0
    def change_to_user_group(self, insane=None):
        """ Change user of the running program. Just insult the admin if he wants root run (it can override).
If change failed we sys.exit(2) """
        if insane is None:
            insane = not self.idontcareaboutsecurity

        # TODO: change user on nt
        if os.name == 'nt':
            print("Sorry, you can't change user on this system")
            return

        if (self.user == 'root' or self.group == 'root') and not insane:
            print "What's ??? You want the application run under the root account?"
            print "I am not agree with it. If you really want it, put :"
            print "idontcareaboutsecurity=yes"
            print "in the config file"
            print "Exiting"
            sys.exit(2)

        uid = self.find_uid_from_name()
        gid = self.find_gid_from_name()
        if uid is None or gid is None:
            print "Exiting"
            sys.exit(2)
        try:
            # First group, then user :)
            os.setregid(gid, gid)
            os.setreuid(uid, uid)
        except OSError, e:
            print "Error : cannot change user/group to %s/%s (%s [%d])" % (
                self.user, self.group, e.strerror, e.errno)
            print "Exiting"
            sys.exit(2)
Beispiel #19
0
 def newPreExec():
     preExec and preExec()
     os.setreuid(uid, uid)
     os.setregid(gid, gid)
     os.setsid()
     os.chdir(homeDir)
     os.umask(0)
Beispiel #20
0
def drop_privileges(user, group):
    if user is None:
        uid = os.getuid()
    elif user.lstrip("-").isdigit():
        uid = int(user)
    else:
        uid = pwd.getpwnam(user).pw_uid

    if group is None:
        gid = os.getgid()
    elif group.lstrip("-").isdigit():
        gid = int(group)
    else:
        gid = grp.getgrnam(group).gr_gid

    username = pwd.getpwuid(uid).pw_name
    # groupname = grp.getgrgid(gid).gr_name
    groups = [g for g in grp.getgrall() if username in g.gr_mem]

    os.setgroups(groups)
    if hasattr(os, 'setresgid'):
        os.setresgid(gid, gid, gid)
    else:
        os.setregid(gid, gid)
    if hasattr(os, 'setresuid'):
        os.setresuid(uid, uid, uid)
    else:
        os.setreuid(uid, uid)
Beispiel #21
0
def switchUserPreVeil():
    if sys.platform in ["darwin", "linux2"]:
        preveil_pwuid = pwd.getpwnam("preveil")
        os.setregid(preveil_pwuid.pw_gid, preveil_pwuid.pw_gid)
        os.setreuid(preveil_pwuid.pw_uid, preveil_pwuid.pw_uid)
    elif "win32" == sys.platform:
        pass
Beispiel #22
0
def drop_privileges():
    if 'SUDO_GID' in os.environ:
        gid = int(os.environ['SUDO_GID'])
        os.setregid(gid, gid)
    if 'SUDO_UID' in os.environ:
        uid = int(os.environ['SUDO_UID'])
        os.setreuid(uid, uid)
Beispiel #23
0
def test_user_config_file(user_home, user_entry):
    info("Check user config file contents")
    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.read("/etc/domogik/domogik.cfg")

    #check [domogik] section
    dmg = dict(config.items('domogik'))
    database = dict(config.items('database'))
    admin = dict(config.items('admin'))
    butler = dict(config.items('butler'))
    backup = dict(config.items('backup'))
    ok("Config file correctly loaded")

    info("Parse [domogik] section")
    import domogik

    #Check ix xpl port is not used
    _check_port_availability("0.0.0.0", 3865, udp = True)
    ok("xPL hub IP/port is not bound by anything else")

    parent_conn, child_conn = Pipe()
    p = Process(target=_test_user_can_write, args=(child_conn, dmg['log_dir_path'],user_entry,))
    p.start()
    p.join()
    assert parent_conn.recv(), "The directory %s for log does not exist or does not have right permissions" % dmg['log_dir_path']

    assert dmg['log_level'] in ['debug','info','warning','error','critical'], "The log_level parameter does not have a good value. Must \
            be one of debug,info,warning,error,critical"
    ### obsolete
    #if not os.path.isdir(dmg['src_prefix'] + '/share/domogik'):
    #    try:
    #        f = os.listdir("%s/share/domogik" % dmg['src_prefix'])
    #        f.close()
    #    except OSError:
    #        fail("Can't access %s/share/domogik. Check %s is available for domogik user (if you are in development mode, be sure the directory which contains the sources is available for domogik user)." % (dmg['src_prefix'],dmg['src_prefix']))
    #        exit()
    ok("[domogik] section seems good")

    # check [database] section
    info("Parse [database] section")
    assert database['type'] == 'mysql', "Only mysql database type is supported at the moment"

    uid = user_entry.pw_uid
    os.setreuid(0,uid)
    old_home = os.environ['HOME']
    os.environ['HOME'] = user_home
    from domogik.common.database import DbHelper
    d = DbHelper()
    os.setreuid(0,0)
    os.environ['HOME'] = old_home
    assert d.get_engine() != None, "Engine is not set, it seems something went wrong during connection to the database"

    ok("[database] section seems good")

    # Check [admin] section
    info("Parse [admin] section")
    for ipadd in get_ip_for_interfaces(admin['interfaces'].split(",")):
        _check_port_availability(ipadd, admin['port'])
    ok("Admin server IP/port is not bound by anything else")
Beispiel #24
0
def safe_open_write(the_file, may_overwrite=False):
    real_uid = os.getuid()
    effective_uid = os.geteuid()
    os.setreuid(effective_uid, real_uid)
    if may_overwrite:
        print "Writing %s (possibly overwriting)..." % (the_file)
    else:
        print "Writing %s (if it doesn't exist)..." % (the_file)
    try:
        try:
            if may_overwrite:
                fd = os.open(the_file, os.O_WRONLY | os.O_TRUNC | os.O_CREAT,
                             0600)
            else:
                fd = os.open(the_file,
                             os.O_WRONLY | os.O_TRUNC | os.O_EXCL | os.O_CREAT,
                             0600)
        except OSError, e:
            fd = -1
    finally:
        os.setreuid(real_uid, effective_uid)
    if fd != -1:
        fh = os.fdopen(fd, 'w')
        return fh
    else:
        return None
def change_user(username):
  try:
    user_info = pwd.getpwnam(username)
  except KeyError:
    print("user %s does not exist" % (username,))
    raise
  os.setregid(user_info.pw_gid, user_info.pw_gid)
  os.setreuid(user_info.pw_uid, user_info.pw_uid)
Beispiel #26
0
    def drop_privileges(self):
        if os.geteuid() != 0:
            return

        user_name = os.getenv("SUDO_USER")
        pwnam = pwd.getpwnam(user_name)
        os.initgroups(user_name, pwnam.pw_gid)
        os.setregid(pwnam.pw_gid, pwnam.pw_gid)
        os.setreuid(pwnam.pw_uid, pwnam.pw_uid)
Beispiel #27
0
        def set_ids():
            # Configure UID and GID
            try:

                os.setregid(gid, gid)
                os.setgroups([gid])
                os.setreuid(uid, uid)
            except Exception as e:
                debug(e)
Beispiel #28
0
 def drop_all_privileges(self):
     # gconf needs both the UID and effective UID set.
     if "SUDO_GID" in os.environ:
         # gid = int(os.environ['SUDO_GID'])
         os.setregid(self.gid, self.gid)
     if "SUDO_UID" in os.environ:
         # uid = int(os.environ['SUDO_UID'])
         os.setreuid(self.uid, self.uid)
         os.environ["HOME"] = self.home
Beispiel #29
0
def drop_all_privileges():
    # gconf needs both the UID and effective UID set.
    if 'SUDO_GID' in os.environ:
        gid = int(os.environ['SUDO_GID'])
        os.setregid(gid, gid)
    if 'SUDO_UID' in os.environ:
        uid = int(os.environ['SUDO_UID'])
        os.setreuid(uid, uid)
        os.environ['HOME'] = pwd.getpwuid(uid).pw_dir
Beispiel #30
0
def set_reuid(config):
    '''Change real and effective UID according to config.'''
    if config.daemon_uid is not None:
        try:
            os.setreuid(config.daemon_uid, config.daemon_uid)
        except:
            logging.error('Error switching to user %d: %s', config.daemon_uid,
                          sys.exc_info()[1])
            raise
Beispiel #31
0
def set_reuid(config):
    '''Change real and effective UID according to config.'''
    if config.daemon_uid is not None:
        try:
            os.setreuid(config.daemon_uid, config.daemon_uid)
        except:
            logging.error('Error switching to user %d: %s', config.daemon_uid,
                          sys.exc_info()[1])
            raise
Beispiel #32
0
    def drop_privileges(self):
        if os.geteuid() != 0:
            return

        user_name = os.getenv("SUDO_USER")
        pwnam = pwd.getpwnam(user_name)
        os.initgroups(user_name, pwnam.pw_gid)
        os.setregid(pwnam.pw_gid, pwnam.pw_gid)
        os.setreuid(pwnam.pw_uid, pwnam.pw_uid)
def setreuid(space, ruid, euid):
    """ setreuid(ruid, euid)

    Set the current process's real and effective user ids.
    """
    try:
        os.setreuid(ruid, euid)
    except OSError, e:
        raise wrap_oserror(space, e)
Beispiel #34
0
 def _system(self, command, *args):
     os.setuid(self.euid)
     try:
         try:
             system(command, *args)
         except ExecError, e:
             raise Error(e)
     finally:
         os.setreuid(self.uid, self.euid)
Beispiel #35
0
 def drop_all_privileges(self):
     # gconf needs both the UID and effective UID set.
     if 'SUDO_GID' in os.environ:
         #gid = int(os.environ['SUDO_GID'])
         os.setregid(self.gid, self.gid)
     if 'SUDO_UID' in os.environ:
         #uid = int(os.environ['SUDO_UID'])
         os.setreuid(self.uid, self.uid)
         os.environ['HOME'] = self.home
Beispiel #36
0
def setreuid(space, ruid, euid):
    """ setreuid(ruid, euid)

    Set the current process's real and effective user ids.
    """
    try:
        os.setreuid(ruid, euid)
    except OSError as e:
        raise wrap_oserror(space, e)
Beispiel #37
0
def _safe_child(to_exec, q, uid, gid):
    try:
        os.setgroups([])
        os.setregid(gid, gid)
        os.setreuid(uid, uid)

        res = subprocess.check_output(to_exec, stderr=open(os.devnull, 'w'))
        q.put(res)
    except Exception as e:
        q.put(e)
    def _set_uid(self, user):
        try:
            pw_ent = pwd.getpwnam(user)
        except KeyError as e:
            raise PreExecFailed(e.message)

        try:
            os.setreuid(pw_ent.pw_uid, pw_ent.pw_uid)
        except OSError as e:
            raise PreExecFailed('Failed to setreuid: ' + e.strerror)
Beispiel #39
0
def _safe_child(to_exec, q, uid, gid):
    try:
        os.setgroups([])
        os.setregid(gid, gid)
        os.setreuid(uid, uid)

        res = subprocess.check_output(to_exec, stderr=open(os.devnull, 'w'))
        q.put(res)
    except Exception as e:
        q.put(e)
Beispiel #40
0
def dropPrivileges(uid, gid):
    try:
        os.setregid(gid, gid)
        os.setreuid(uid, uid)
        # niby zbedne ;>
        if os.getuid() != uid or os.getgid() != gid or os.geteuid(
        ) != uid or os.getegid() != gid:
            return False
        return True
    except:
        return False
Beispiel #41
0
    def drop_privs(self):
        """Set real UID and GID the same as effective UID and GID.

        To be used as the `preexec_fn` for `run_cmd` for commands that run durable jobs
        (not required for mkdir(1), but required for e.g. `mount.posixovl(8)`)
        """
        IO.write("Setting real GID to %d" % os.getegid())
        os.setregid(os.getegid(), -1)
        IO.write("Setting real UID to %d" % os.geteuid())
        os.setreuid(os.geteuid(), -1)
        IO.write("All privileges dropped")
Beispiel #42
0
 def drop_all_privileges(self):
     # gconf needs both the UID and effective UID set.
     if 'SUDO_GID' in os.environ:
         # gid = int(os.environ['SUDO_GID'])
         print_debug("drop_all_privileges GID=%s" % self.gid)
         os.setregid(self.gid, self.gid)
     if 'SUDO_UID' in os.environ:
         # uid = int(os.environ['SUDO_UID'])
         print_debug("drop_all_privileges UID=%s HOME=%s" % (self.uid, self.home))
         os.setreuid(self.uid, self.uid)
         os.environ['HOME'] = self.home
Beispiel #43
0
def jail():
    os.nice(20)
    resource.setrlimit(resource.RLIMIT_CPU, (5, 5)) # max 5s cpu time
    resource.setrlimit(resource.RLIMIT_AS, (100*1024*1024, 100*1024*1024)) # max 100MB address space

    user = pwd.getpwnam('retex')
    uid, gid = user[2], user[3]

    os.chroot('/retex-jail')

    os.setregid(gid, gid)
    os.setreuid(uid, uid)
Beispiel #44
0
    def switchUser(self):

        sUserName = self.sExpType + "opr"
        iId = int(os.popen("/usr/bin/id -u " + sUserName).read().strip())

        try:
            os.setreuid(iId, iId)
        except:
            print "Cannot switch to %s.  Try sudo?" % sUserName
            return False

        return True
Beispiel #45
0
	def move_file(self,orig,dest,owner):
		
		user_uid=pwd.getpwnam(owner)[2]
		user_gid=pwd.getpwnam(owner)[3]
		os.chown(orig,user_uid,user_gid)
		os.setregid(0,user_gid)
		os.setreuid(0,user_uid)
		shutil.move(orig,dest)
		tmp=dest.split("/")
		tmp_file="." + tmp[len(tmp)-1]
		tmp_file_path="/".join(tmp[:len(tmp)-1]) + "/" + tmp_file
		os.remove(tmp_file_path)
Beispiel #46
0
 def change_privileges(self):
     try:
         user = pwd.getpwnam(self.__config["user_privilege"])
         os.setreuid(user[2], user[2])
     except KeyError:
         print >> sys.stderr, "User : "******"user_privilege"]\
               + " doesn't exist."
         raise OSError
     except OSError:
         syslog.syslog(syslog.LOG_ERR | syslog.LOG_DAEMON, \
                       "Can't change user privileges.")
         raise
Beispiel #47
0
def root_mode(quiet=True):
    root_uid = 0
    root_gid = 0
    try:
        os.setreuid(0, root_uid)
        os.setregid(0, root_gid)
    except OSError as e:
        msg = "Cannot escalate permissions to (uid=%s, gid=%s): %s" % (root_uid, root_gid, e)
        if quiet:
            LOG.warn(msg)
        else:
            raise excp.PermException(msg)
Beispiel #48
0
def root_mode(quiet=True):
    root_uid = 0
    root_gid = 0
    try:
        os.setreuid(0, root_uid)
        os.setregid(0, root_gid)
    except OSError as e:
        msg = "Cannot escalate permissions to (uid=%s, gid=%s): %s" % (root_uid, root_gid, e)
        if quiet:
            LOG.warn(msg)
        else:
            raise excp.PermException(msg)
Beispiel #49
0
    def drop_privileges(self):
        try:
            try:
                (ruid, euid, suid) = os.getresuid()
                (rgid, egid, sgid) = os.getresgid()
            except AttributeError, errmsg:
                ruid = os.getuid()
                rgid = os.getgid()

            if ruid == 0:
                # Means we can setreuid() / setregid() / setgroups()
                if rgid == 0:
                    # Get group entry details
                    try:
                        (
                            group_name,
                            group_password,
                            group_gid,
                            group_members
                        ) = grp.getgrnam(conf.process_groupname)

                    except KeyError:
                        print >> sys.stderr, "Group %s does not exist" % (conf.process_groupname)
                        sys.exit(1)

                    # Set real and effective group if not the same as current.
                    if not group_gid == rgid:
                        log.debug("Switching real and effective group id to %d" % (group_gid), level=8)
                        os.setregid(group_gid, group_gid)

                if ruid == 0:
                    # Means we haven't switched yet.
                    try:
                        (
                            user_name,
                            user_password,
                            user_uid,
                            user_gid,
                            user_gecos,
                            user_homedir,
                            user_shell
                        ) = pwd.getpwnam(conf.process_username)

                    except KeyError:
                        print >> sys.stderr, "User %s does not exist" % (conf.process_username)
                        sys.exit(1)


                    # Set real and effective user if not the same as current.
                    if not user_uid == ruid:
                        log.debug("Switching real and effective user id to %d" % (user_uid), level=8)
                        os.setreuid(user_uid, user_uid)
Beispiel #50
0
  def setUp(self):
    """Setup the getuid/setuid dance."""
    super(TestValidatePath, self).setUp()

    self.mox.StubOutWithMock(os, 'getuid')
    self.mox.StubOutWithMock(os, 'setreuid')
    self.mox.StubOutWithMock(os, 'setuid')
    self.mox.StubOutWithMock(utils, 'getCaller')

    os.getuid().MultipleTimes().AndReturn(0)
    utils.getCaller().MultipleTimes().AndReturn(500)
    os.setreuid(500, 0)
    os.setuid(0)
Beispiel #51
0
Datei: soma.py Projekt: Qwaz/soma
def open_daemon(prob_user, prob_port, prob_entry, prob_home):
    pid = 0
    try:
        pid = os.fork()
    except OSError as e:
        exit(1)
    if pid == 0:
        os.chdir(prob_home)
        user = pwd.getpwnam(prob_user)
        os.setregid(user.pw_gid, user.pw_gid)
        os.setreuid(user.pw_uid, user.pw_uid)
        os.execv('/usr/bin/socat', ['socat', 'tcp-listen:%d,fork,reuseaddr,bind=127.0.0.1' % prob_port, 'exec:%s,PTY,CTTY,raw,echo=0' % prob_entry])
    return pid
Beispiel #52
0
def safe_make_dir(the_dir):
    print "Creating directory %s (if it doesn't exist)..."  % (the_dir)
    real_uid = os.getuid()
    effective_uid = os.geteuid()
    os.setreuid(effective_uid, real_uid)
    try:
        try:
            os.mkdir(the_dir)
        except OSError, e:
            if e.errno != errno.EISDIR and e.errno != errno.EEXIST:
                raise
    finally:
        os.setreuid(real_uid, effective_uid)
Beispiel #53
0
def main ():
	if len (sys.argv) < 2:
		print ("Need args")
	
	print ("Reid: {0}, Euid: {1}".format (getuid (), geteuid ()))
	try:
		setreuid (1234, 12345)
	except OSError as Exc:
		print (Exc)
	os.system ("cat /etc/shadow")
	print ("Ruid: {0}, Euid: {1}".format (getuid (), geteuid ()))
	
	return
Beispiel #54
0
def become(user):
    """Switch to another user (need to be root first)."""
    u = pwd.getpwnam(user)
    os.environ["LOGNAME"] = os.environ["USER"] = u.pw_name
    os.environ["PWD"] = os.getcwd()
    os.environ["HOME"] = u.pw_dir
    os.environ["SHELL"] = u.pw_shell
    os.setregid(u.pw_gid, u.pw_gid)
    try:
        os.initgroups(user, u.pw_gid)
    except OverflowError:
        pass  # FIXME???
    os.setreuid(u.pw_uid, u.pw_uid)
Beispiel #55
0
def do_as_user(username, func, *args, **kwargs):
    _, _, uid, gid, _, _, _ = getpwnam(username)

    pid = os.fork()
    if pid == 0:
        if os.getgid() != gid:
            os.setregid(gid, gid)
        if os.getuid() != uid:
            os.setreuid(uid, uid)
        func(*args, **kwargs)
        os._exit(0)
    else:
        os.waitpid(pid, 0)