def prepare(self):
        self.preseed("console-setup/ask_detect", "false")

        # We need to get rid of /etc/default/console-setup, or console-setup
        # will think it's already configured and behave differently. Try to
        # save the old file for interest's sake, but it's not a big deal if
        # we can't.
        os.seteuid(0)
        try:
            os.unlink("/etc/default/console-setup.pre-ubiquity")
        except OSError:
            pass
        try:
            os.rename("/etc/default/console-setup", "/etc/default/console-setup.pre-ubiquity")
        except OSError:
            try:
                os.unlink("/etc/default/console-setup")
            except OSError:
                pass
        misc.drop_privileges()
        # Make sure debconf doesn't do anything with crazy "preseeded"
        # answers to these questions. If you want to preseed these, use the
        # *code variants.
        if not "UBIQUITY_AUTOMATIC" in os.environ:
            self.db.fset("console-setup/layout", "seen", "false")
            self.db.fset("console-setup/variant", "seen", "false")

        # Technically we should provide a version as the second argument,
        # but that isn't currently needed and it would require querying
        # apt/dpkg for the current version, which would be slow, so we don't
        # bother for now.
        return (
            ["/usr/lib/ubiquity/console-setup/console-setup.postinst", "configure"],
            ["^console-setup/layout", "^console-setup/variant"],
        )
Beispiel #2
0
    def run(self):
        # If umask = 0077, created files will be rw for effective user only
        # If umask = 0007, they will be rw for effective user and group only
        os.umask(self.config.umask)
        os.setegid(self.config.egid)
        os.seteuid(self.config.euid)

        # Daemonize early
        if self.daemon:
            self.lock.acquire()
            self.daemonize()

        # Do all kind of initialization
        try:
            ret = self.initialize()
        finally:
            # Tell the father how to return, and let him return (release)
            if self.daemon:
                self.state = ret
                self.lock.release()

        if ret:
            return ret

        reactor.run()
Beispiel #3
0
def attempt_effective_uid(username, suppress_errors=False):
    """
    A context manager to temporarily change the effective user id.

    :param bytes username: The username whose uid will take effect.
    :param bool suppress_errors: Set to `True` to suppress `OSError`
        ("Operation not permitted") when running as a non-root user.
    """
    original_euid = os.geteuid()
    new_euid = pwd.getpwnam(username).pw_uid
    restore_euid = False

    if original_euid != new_euid:
        try:
            os.seteuid(new_euid)
        except OSError as e:
            # Only handle "Operation not permitted" errors.
            if not suppress_errors or e.errno != 1:
                raise
        else:
            restore_euid = True
    try:
        yield
    finally:
        if restore_euid:
            os.seteuid(original_euid)
Beispiel #4
0
def drop_priviliges(euid=None):
    """
    Change EUID of the current process to nobody.

    Some functions require root-privilegies and after we done them,
    we don't really need this privilegies. So, we can simple leave them.
    It makes the application more safier.

    For example, to open a socket we need those privilegies.
    
    It works only under UNIX. For other operation systems,
    this function doesn't do anything.

    @type euid: C{int}
    @param euid: UID number candidate (default: nobody)
    """

    # checking if it's UNIX-family OS
    if os.name != 'posix':
        return

    if euid is None:
        import pwd
        euid = pwd.getpwnam('nobody')[2]
    try:
        os.seteuid(euid)
    except OSError:
        print >> sys.stderr, "Run the program with root-priviliges.\n"
        raise
Beispiel #5
0
def change_user(uid, gid, euid=False):
    # TODO: validate uid/gid, do root checks, etc.
    os.setgid(gid)
    if not euid:
        os.setuid(uid)
    else:
        os.seteuid(uid)
Beispiel #6
0
def main(argv):
    global proxy_addr
    if '--help' in argv:
        usage(argv[0], sys.stdout)
        sys.exit(0)

    if sys.version_info < (2,3,5):
        sys.stderr.write("Python 2.3.5 or later is required.\n")
        sys.exit(1)

    if os.geteuid() != 0:
        sys.stderr.write("ERROR: \n")
        sys.stderr.write(
"  This script must be run as root. Preferably setuid (via companion .c\n"
"  program), but it'll work when invoked as root directly, too.\n")
        sys.exit(1)

    # Set effective uid to userid; will become root as necessary
    os.seteuid(os.getuid())
    user = getpass.getuser()

    try:
        opts,args=getopt.getopt(argv[1:], "", ['verbose', 'http-proxy=', 'socks5-proxy=', 'dont-check-certificates'])
    except getopt.GetoptError, e:
        sys.stderr.write("Unknown option: %s\n" % e.opt)
        usage(argv[0], sys.stderr)
        sys.exit(1)
Beispiel #7
0
def _create_new_key(keystone_user_id, keystone_group_id):
    """Securely create a new encryption key.

    Create a new key that is readable by the Keystone group and Keystone user.
    """
    key = fernet.Fernet.generate_key()  # key is bytes

    # This ensures the key created is not world-readable
    old_umask = os.umask(0o177)
    if keystone_user_id and keystone_group_id:
        old_egid = os.getegid()
        old_euid = os.geteuid()
        os.setegid(keystone_group_id)
        os.seteuid(keystone_user_id)
    elif keystone_user_id or keystone_group_id:
        LOG.warning(_LW(
            'Unable to change the ownership of the new key without a keystone '
            'user ID and keystone group ID both being provided: %s') %
            CONF.fernet_tokens.key_repository)
    # Determine the file name of the new key
    key_file = os.path.join(CONF.fernet_tokens.key_repository, '0')
    try:
        with open(key_file, 'w') as f:
            f.write(key.decode('utf-8'))  # convert key to str for the file.
    finally:
        # After writing the key, set the umask back to it's original value. Do
        # the same with group and user identifiers if a Keystone group or user
        # was supplied.
        os.umask(old_umask)
        if keystone_user_id and keystone_group_id:
            os.seteuid(old_euid)
            os.setegid(old_egid)

    LOG.info(_LI('Created a new key: %s'), key_file)
 def __enter__(self):
   if self.uid:
     self.saved_uid = os.geteuid()
     self.saved_groups = os.getgroups()
     if self.uid:
       os.setgroups(self.saved_groups + [AID_INET])
       os.seteuid(self.uid)
Beispiel #9
0
def run_as_root(args, stdin=None):
    if stdin is not None:
        pipe_r, pipe_w = os.pipe()
    else:
        pipe_r, pipe_w = None, None

    pid = os.fork()
    if pid == 0:
        if pipe_r is not None:
            # setup stdin pipe
            os.dup2(pipe_r, 0)
            os.close(pipe_r)
            os.close(pipe_w)

        os.seteuid(0)
        os.setuid(0)
        try:
            os.execv(args[0], args)
        except:
            os._exit(127)
    else:
        if pipe_r is not None:
            os.close(pipe_r)
            os.write(pipe_w, stdin)
            os.close(pipe_w)
        wpid, sts = os.waitpid(pid, 0)
        code = sts_result(sts)
        if code != 0:
            raise MyException("%r: exited with result %d"% (args, code))
 def vfs_op_success(self, filename, dentry, args, filetype="f", create=False, copy_up=False,
                    hardlink_to=None):
     if "as_bin" in args:
         self.verbosef("os.seteuid(0)")
         os.seteuid(0)
         self.verbosef("os.setegid(0)")
         os.setegid(0)
     want_error = args["err"]
     if want_error:
         raise TestError(filename + ": Expected error (" +
                         os.strerror(want_error) + ") was not produced")
     if dentry.is_negative():
         if not create:
             if filetype == "d":
                 raise TestError(filename + ": Directory was created unexpectedly")
             elif filetype == "s":
                 raise TestError(filename + ": Symlink was created unexpectedly")
             else:
                 raise TestError(filename + ": File was created unexpectedly")
         if not hardlink_to:
             dentry.created(inode(filetype))
         else:
             dentry.created(hardlink_to, on_upper = dentry.on_upper())
     else:
         if copy_up:
             dentry.copied_up()
     self.check_layer(filename)
Beispiel #11
0
def drop_privileges(user: pwd.struct_passwd, group: grp.struct_group, permanent: bool = True):
    """
    Drop root privileges and change to something more safe.

    :param user: The tuple with user info
    :param group: The tuple with group info
    :param permanent: Whether we want to drop just the euid (temporary), or all uids (permanent)
    """
    # Restore euid=0 if we have previously changed it
    if os.geteuid() != 0 and os.getuid() == 0:
        restore_privileges()

    if os.geteuid() != 0:
        raise RuntimeError("Not running as root: cannot change uid/gid to {}/{}".format(user.pw_name, group.gr_name))

    # Remove group privileges
    os.setgroups([])

    if permanent:
        os.setgid(group.gr_gid)
        os.setuid(user.pw_uid)
    else:
        os.setegid(group.gr_gid)
        os.seteuid(user.pw_uid)

    # Ensure a very conservative umask
    os.umask(0o077)

    if permanent:
        logger.debug("Permanently dropped privileges to {}/{}".format(user.pw_name, group.gr_name))
    else:
        logger.debug("Dropped privileges to {}/{}".format(user.pw_name, group.gr_name))
Beispiel #12
0
def setup_container_users():
    r"""
    Create container users and setup SSH access.
    """
    log.info("setting up users in the containter")
    check_call("addgroup --gid {GID} {group}")
    check_call("adduser --uid {server_ID} --ingroup {group} --gecos '' "
               "--disabled-password {server}")
    check_call("adduser --uid {worker_ID} --ingroup {group} --gecos '' "
               "--disabled-password {worker}")

    shome = os.path.join("/home", users["server"])
    whome = os.path.join("/home", users["worker"])
    os.chdir(shome)
    os.setegid(users["GID"])
    os.seteuid(users["server_ID"])
    os.mkdir(".ssh", 0o700)
    check_call("ssh-keygen -q -N '' -f .ssh/id_rsa")

    os.chdir(whome)
    os.setuid(0)
    os.seteuid(users["worker_ID"])
    os.mkdir(".ssh", 0o700)
    files_to_lock = ".ssh .bashrc .bash_profile .bash_logout .profile"
    check_call("touch " + files_to_lock)
    os.setuid(0)
    shutil.copy2(os.path.join(shome, ".ssh/id_rsa.pub"),
                 ".ssh/authorized_keys")
    os.chown(".ssh/authorized_keys", users["worker_ID"], users["GID"])
    # Get the localhost in the known_hosts file.
    check_call("su -l {server} -c "
               "'ssh -q -oStrictHostKeyChecking=no {worker}@localhost whoami'")
    for f in files_to_lock.split():
        check_call("chattr -R +i " + f)
Beispiel #13
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 #14
0
def main():
    #change to data directory if needed
    os.chdir(workdir)
    # Redirect outputs to a logfile
    sys.stdout = sys.stderr = Log(open('%s/%s' % (workdir, logfile), 'a+'))
    # ensure the that the daemon runs a normal user
    os.setegid(0)     # set group
    os.seteuid(0)     # set user
    #start the user program here:
    print 'Daemon running at ' + time.strftime("%Y/%m/%d %H.%M.%S")

    s = socket(AF_INET, SOCK_STREAM)    # Create the TCP Socket
    s.bind((statHost, statPort))        # bind it to the server port
    s.listen(child)                     # allow X simultaneous pending connections
    (connection, address) = s.accept()  # connection is a new socket
    try:
        while 1:
            data = connection.recv(buf)  # receive up to 1K bytes
            if data:
                store(address[0])
                r = data.split()
                result = address[0] + ' '
                for item in r:
                    result += item + ' '
                print result
                #smsfile = open(filename, 'w+')
                #smsfile.write(msg)
                #smsfile.	close()
    except KeyboardInterrupt:
        stopd()
        #	print 'Daemon normal exit at '+time.strftime("%Y/%m/%d %H.%M.%S")
    #	os.remove('%s/%s' % (workdir,pidfile))
    connection.close()              # close socket
Beispiel #15
0
def init(*configFiles):
    global _svr
    if _svr:
        raise RuntimeError, "already initialized"

    loadConfig(*configFiles)
    configDefaults()
    updateConfig()
    configLogging()    

    # set effective user/group, if necessary
    isroot=os.getuid()==0
    run_user=Configuration.run_user
    run_group=Configuration.run_group
    if isroot and run_user is None:
        raise RuntimeError, "won't run as root with out run_user being defined"
    if run_group is not None:
        gid=grp.getnrnam(run_group)[2]
        if hasattr(os, 'setegid'):
            os.setegid(gid)
        #else?
    if run_user is not None:
        uid=pwd.getpwnam(run_user)[2]
        if hasattr(os, 'seteuid'):
            os.seteuid(uid)
        #else?

    loadServices()
    
    # revv 'er up
    _svr=Server(configFiles)
    _svr.mainloop()
Beispiel #16
0
def _attack(attacker, params):
    print >> sys.stderr, "perform %s attack..." % attacker.desc

    try:
        attacker.pre_attack(params)
    except OSError:
        print >> sys.stderr, "Unable to pre-attack:", sys.exc_info()[1]
        return

    try:
        non_root_attacker = pwd.getpwnam('racepro').pw_uid
    except KeyError:
        assert False, "Non-root attacker 'racepro' does not exist"

    pid = os.fork()
    if pid == 0:
        try:
            os.seteuid(non_root_attacker)
            attacker.attack(params)
        except OSError:
            print >> sys.stderr, "Unable to attack:", sys.exc_info()[1]
        else:
            print >> sys.stderr, "Attack succeeds"

        os._exit(0)
    else:
        os.waitpid(pid, 0)
Beispiel #17
0
def main():
	running_vms = {}
	parser = setup_options_parser()
	
	# parse given arguments
	args = parser.parse_args()
	
	if os.getuid() != 0:
		parser.error(	"This program requires root privileges. Please run" + 
						" again with necessary permissions.")
	
	uid = os.stat(parser.prog).st_uid
	os.seteuid(uid)
	
	port = args.port
	qemu_path = args.qemu_path
	pipes_directory = os.path.dirname(os.path.abspath(__file__)) + '/pipes'
	
	if not os.path.exists(pipes_directory):
		os.makedirs(pipes_directory)
	
	serversocket = setup_serversocket(uid, port)
	serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

	def signal_handler(signal, frame):
		serversocket.close()
		# terminate all receivers
		for channel in running_vms:
			running_vms[channel][1].running = False
		print "\nServer shutdown"
		sys.exit()
	
	signal.signal(signal.SIGINT, signal_handler)

	start_server(serversocket, running_vms, qemu_path, pipes_directory)
Beispiel #18
0
def tor_new_process():
    """
    Drops privileges to TOR_USER user and start a new Tor process
    """
    debian_tor_uid = getpwnam(TOR_USER).pw_uid
    debian_tor_gid = getpwnam(TOR_USER).pw_gid
    os.setgid(debian_tor_gid)
    os.setuid(debian_tor_uid)
    os.setegid(debian_tor_gid)
    os.seteuid(debian_tor_uid)
    os.environ['HOME'] = "/var/lib/tor"

    tor_process = stem.process.launch_tor_with_config(
      config = {
        'SocksPort': '6666',
        'ControlPort': '6969',
        'DNSPort': '9053',
        'DNSListenAddress': '127.0.0.1',
        'AutomapHostsOnResolve': '1',
        'AutomapHostsSuffixes': '.exit,.onion',
        'VirtualAddrNetwork': '10.192.0.0/10',
        'TransPort': '9040',
        'TransListenAddress': '127.0.0.1',
        'AvoidDiskWrites': '1',
        'WarnUnsafeSocks': '1',
      })
Beispiel #19
0
def drop_privileges():
    if 'SUDO_GID' in os.environ:
        gid = int(os.environ['SUDO_GID'])
        os.setegid(gid)
    if 'SUDO_UID' in os.environ:
        uid = int(os.environ['SUDO_UID'])
        os.seteuid(uid)
Beispiel #20
0
def switch_to_current_user():
    """Switch euid and guid to current user if current user is root"""
    if os.geteuid() != 0:
        return
    # fallback to root user if no SUDO_GID (should be su - root)
    os.setegid(int(os.getenv("SUDO_GID", default=0)))
    os.seteuid(int(os.getenv("SUDO_UID", default=0)))
Beispiel #21
0
    def __call__(self, props, conn_params, queue):
        """Worker process entry point."""

        self.settings.update(props)

        if "user" in props.keys():
            LOG.debug("Try to switch to user '%s'" % props['user'])
            if os.geteuid() == 0:
                try:
                    newuid = getpwnam(props["user"])[2]
                    os.seteuid(newuid)
                    LOG.debug("Swithced to uid %d" % newuid)
                except KeyError:
                    LOG.error("No such user '%s'" % props['user'])
            else:
                LOG.warning("Not enough permissions to switch user")

        self.connection = pika.BlockingConnection(conn_params)
        self.channel = self.connection.channel()
        self.channel.queue_declare(queue=queue, durable=True,
                                   exclusive=False, auto_delete=False)
        self.channel.basic_qos(prefetch_count=1)
        self.channel.basic_consume(self.handle_delivery, queue=queue)
        signal.signal(signal.SIGTERM, self.cleanup)
        LOG.debug("created new process with props %r" % props)
        if OPT_RESULTS_ROUTING_KEY in props.keys():
            self.results_routing_key = props[OPT_RESULTS_ROUTING_KEY]
        self.channel.start_consuming()
Beispiel #22
0
 def _switch_process_owner(self, user, group):
     try:
         seteuid(getpwnam(user).pw_uid)
         setegid(getgrnam(group).gr_gid)
     except OSError, e:
         raise UnixSetupError('Error - Couldn\'t switch process owner \'{:}.{:}\'. Details {:}.'.format(
             user, group, e))
Beispiel #23
0
 def getRsaKeys(self, all = None):
     uidBefore = os.geteuid()
     os.seteuid(0)
     gidBefore = os.getgid()
     os.setegid(0)
     self._prepareSSHEnvironment()
     sshPrivateKey = os.path.join(dissomniag.config.dissomniag.configDir, dissomniag.config.dissomniag.rsaKeyPrivate)
     sshPrivateKey = os.path.abspath(sshPrivateKey)
     sshPublicKey = os.path.join(dissomniag.config.dissomniag.configDir, dissomniag.config.dissomniag.rsaKeyPublic)
     sshPublicKey = os.path.abspath(sshPublicKey)
     if not (os.path.exists(sshPrivateKey) and os.path.exists(sshPublicKey)):
         ret = subprocess.call(shlex.split("ssh-keygen -t rsa -q -f %s -P ''" % sshPrivateKey),
                         stdout = open('/dev/null', 'w'),
                         stderr = subprocess.STDOUT)
         if ret != 0:
             raise SSHKeyGenError()
         else:
             log.debug("New SSH Keys created")
         
             
     
     privateKeyString = file(sshPrivateKey, 'r').read()
     privateKey = keys.Key.fromString(privateKeyString)
     publicKeyString = file(sshPublicKey, 'r').read()
     publicKey = keys.Key.fromString(publicKeyString)
     
     self._checkRsaKeyAdded(sshPrivateKey, publicKeyString)
     os.setegid(gidBefore)
     os.seteuid(uidBefore)
     if all:
         return sshPrivateKey, privateKeyString, sshPublicKey, publicKeyString
     else:
         return publicKey, privateKey
Beispiel #24
0
def stop(command, argv):
    parser = argparse.ArgumentParser(
        description="Critic administration interface: stop",
        prog="criticctl [options] stop")

    parser.parse_args(argv)

    import os
    import subprocess

    system_identity = configuration.base.SYSTEM_IDENTITY

    try:
        os.seteuid(0)
        os.setegid(0)
    except OSError:
        print >>sys.stderr, "ERROR: 'criticctl stop' must be run as root."
        return 1

    if configuration.base.WEB_SERVER_INTEGRATION == "apache":
        web_server_service = "apache2"
    elif configuration.base.WEB_SERVER_INTEGRATION in ("nginx+uwsgi", "uwsgi"):
        web_server_service = "uwsgi"
    else:
        web_server_service = None

    if web_server_service:
        subprocess.check_call(["service", web_server_service, "stop"])
    subprocess.check_call(["service", "critic-" + system_identity, "stop"])

    return 0
Beispiel #25
0
 def _process_securely(self, operation, path, request, *args, **kw):
     user = request.user_object()
     groups = os.getgroups()
     is_root = not os.getuid()
     uid = os.geteuid()
     gid = os.getegid()
     if not is_root:
         msg = (
             "Framework is not running as root so effective uid "
             "and gid are not being changed prior to doing %s: "
             "%s" % (request.get_command(), path)
         )
         msglog.log("FileRequestHandler", msglog.types.WARN, msg)
     else:
         if self.debug:
             msg = "%s command: file %s, user %s" % (request.get_command(), path, user.name())
             msglog.log(self.name, msglog.types.DB, msg)
         os.setgroups(user.group_ids())
         os.setegid(user.gid())
         os.seteuid(user.uid())
     try:
         result = operation(path, request, *args, **kw)
     finally:
         if is_root:
             os.seteuid(uid)
             os.setegid(gid)
             os.setgroups(groups)
     return result
Beispiel #26
0
def ejecutar_comando_fuente(self, entrega, contexto_ejecucion, caso_de_prueba): #{{{
    path = contexto_ejecucion.build_path
    log.debug(_(u'ComandoFuente.ejecutar(path=%s, entrega=%s)'), path,
        entrega)
    if not self.activo:
        log.debug(_(u'Ignorando comando fuente porque esta inactivo'))
        return
    comando_ejecutado = entrega.add_comando_ejecutado(self)
    basetmp = contexto_ejecucion.build_temp_base_path
    unzip(self.archivos_entrada, path, # TODO try/except
        {self.STDIN: '%s.%s.stdin' % (basetmp, comando_ejecutado.id)})
    options = dict(
        close_fds=True,
        shell=True,
        preexec_fn=contexto_ejecucion.crear_preejecutor_fuente(self)
    )
    if os.path.exists('%s.%s.stdin' % (basetmp, comando_ejecutado.id)):
        options['stdin'] = file('%s.%s.stdin' % (basetmp, comando_ejecutado.id),
            'r')
    else:
        options['preexec_fn'].close_stdin = True
    a_guardar = set(self.archivos_a_guardar)
    zip_a_comparar = Multizip(self.archivos_a_comparar)
    a_comparar = set(zip_a_comparar.namelist())
    a_usar = frozenset(a_guardar | a_comparar)
    if self.STDOUTERR in a_usar:
        options['stdout'] = file('%s.%s.stdouterr' % (basetmp,
            comando_ejecutado.id), 'w')
        options['stderr'] = sp.STDOUT
    else:
        if self.STDOUT in a_usar:
            options['stdout'] = file('%s.%s.stdout' % (basetmp,
                comando_ejecutado.id), 'w')
        else:
            options['preexec_fn'].close_stdout = True
        if self.STDERR in a_usar:
            options['stderr'] = file('%s.%s.stderr' % (basetmp,
                comando_ejecutado.id), 'w')
        else:
            options['preexec_fn'].close_stderr = True
    comando = self.comando # FIXME tiene que diferenciarse de ComandoPrueba
    comando_ejecutado.inicio = datetime.now()
    log.debug(_(u'Ejecutando como root: %s'), comando)
    os.seteuid(0) # Dios! (para chroot)
    os.setegid(0)
    try:
        try:
            returncode = contexto_ejecucion.ejecutar(comando, options)
        except ProcessException as e:
            comando_ejecutado.exito = False
            comando_ejecutado.observaciones += str(e)
            if self.rechazar_si_falla:
                entrega.exito = False
            log.exception(_('Ha ocurrido un error inexperado en la ejecucion de la entrega. Comando: %s. Entrega: %s'), comando, entrega)
        finally:
            contexto_ejecucion.user_info.reset_permisos() # Mortal de nuevo
    except Exception, e:
        if hasattr(e, 'child_traceback'):
            log.error(_(u'Error en el hijo: %s'), e.child_traceback)
        raise
Beispiel #27
0
    def _drop_privileges(self, user=None, group=None):
        """
        Set user/group privileges
        """
        # FIXME: Handle permission exceptions

        # Set group privileges
        if group is None:
            group = self._config.get(
                plog.CFG_SECT_GLOBAL, plog.CFG_OPT_GROUP, None)
            group = self._config.get(self._name, plog.CFG_OPT_GROUP, group)
        if group is not None:
            import grp
            group_info = grp.getgrnam(group)
            os.setegid(group_info.gr_gid)

        # Set user privileges
        if user is None:
            user = self._config.get(
                plog.CFG_SECT_GLOBAL, plog.CFG_OPT_USER, None)
            user = self._config.get(self._name, plog.CFG_OPT_USER, user)
        if user is not None:
            import pwd
            user_info = pwd.getpwnam(user)
            os.seteuid(user_info.pw_uid)
 def copyUIDs(self):
     """Copy EUID/EGID to UID/GID"""
     uid, gid = os.geteuid(), os.getegid()
     if uid != 0 and os.getuid() == 0:
         os.seteuid(0)
         os.setgid(gid)
         os.setuid(uid)
Beispiel #29
0
def super_priviliges(fun=None, *fargs, **kwargs):
    """
    Change EUID of the current process to 0 (root).

    Request for root-priviliges.
    Pass function, then after call the function, drop the priviliges again.

    @type fun: C{function}
    @param fun: function which will be called with EUID=0.

    @param fargs: arguments for the function.

    @param kwargs: key-arguments for the function.

    @return: if function is passed, return the result of the function
    """

    if os.name != 'posix':
        return

    old_euid = os.geteuid()
    try:
        os.seteuid(0)
    except OSError:
        print >> sys.stderr, "Run the program with root-priviliges.\n"
        raise
    if fun:
        result = fun(*fargs, **kwargs)
        drop_priviliges(old_euid)
        return result
Beispiel #30
0
    def setuid(self):
        """
        Set user and group ID of the process

        If ``self.group`` is not defined, then this method uses the group ID of
        the ``self.user``.

        Returns a tuple containing the active user and group IDs.
        """
        if not has_user:
            logging.warn('User switching is disabled on this OS')
            return
        logging.debug('Setting process UID and GID')
        pwinfo = pwd.getpwnam(self.user)
        uid = pwinfo.pw_uid
        os.setuid(uid)
        os.seteuid(uid)
        if self.group:
            logging.debug('Using specified group for GID')
            gid = grp.getgrpnam(self.group).grp_gid
        else:
            logging.debug('Using specified user for GID')
            gid = pwinfo.pw_gid
        os.setgid(gid)
        os.setegid(gid)
        logging.debug('Process UID=%s and GID=%s', uid, gid)
        return uid, gid
Beispiel #31
0
def become(user):
    try:
        userinfo = pwd.getpwuid(int(user))
    except:
        try:
            userinfo = pwd.getpwnam(user)
        except:
            raise ValueError('User {} not found'.format(user))

    if os.geteuid() == userinfo.pw_uid:
        return

    sys._SAVED_UID = os.geteuid()
    sys._SAVED_GID = os.getegid()
    sys._SAVED_GROUPS = os.getgroups()
    sys._SAVED_CWD = os.getcwdu()
    sys._SAVED_ENV = os.environ.copy()

    os.initgroups(userinfo.pw_name, userinfo.pw_gid)
    os.setegid(userinfo.pw_gid)
    os.seteuid(userinfo.pw_uid)

    os.environ['HOME'] = userinfo.pw_dir
    os.environ['USER'] = userinfo.pw_name
    os.environ['LOGNAME'] = userinfo.pw_name
    os.environ['SHELL'] = userinfo.pw_shell
    os.environ['XAUTHORITY'] = os.path.join(userinfo.pw_dir, '.Xauthority')

    user_dbus_socket = os.path.join('/', 'var', 'run', 'user',
                                    str(userinfo.pw_uid), 'dbus',
                                    'user_bus_socket')

    if os.path.exists(user_dbus_socket):
        os.environ[
            'DBUS_SESSION_BUS_ADDRESS'] = 'unix:path=' + user_dbus_socket
    elif 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
        del os.environ['DBUS_SESSION_BUS_ADDRESS']

    for var in os.environ.keys():
        if var.startswith(('XDG_', 'GDM', 'DESKTOP_')):
            del os.environ[var]

    if 'PATH' in os.environ:
        os.environ['PATH'] += ':'.join([
            os.path.join(userinfo.pw_dir, '.local', 'bin'),
            os.path.join(userinfo.pw_dir, 'bin')
        ])

    try:
        os.chdir(userinfo.pw_dir)
    except:
        pass

    try:
        for line in subprocess.check_output([
                userinfo.pw_shell, '-c', '; '.join([
                    '[ -f /etc/profile ] && source /etc/profile >/dev/null 2>/dev/null',
                    '[ -f ~/.profile ] && source ~/.profile >/dev/null 2>/dev/null',
                    'printenv'
                ])
        ]).split('\n'):
            if line and '=' in line:
                k, v = line.split('=', 1)
                os.environ[k] = v
    except:
        pass
Beispiel #32
0
    def open_file(self, filename, **args):
        filename = filename.replace("//", "/")
        self.check_layer(filename)

        line = ""
        flags = 0
        rd = False
        wr = False

        if "ro" in args:
            line += " -r"
            rd = True
        elif "rw" in args:
            line += " -r -w"
            rd = True
            wr = True
        elif "wo" in args:
            line += " -w"
            wr = True
        elif "app" in args:
            wr = True
        else:
            raise RuntimeError("One or both of -r and -w must be supplied to open_file")

        if "app" in args:
            flags |= os.O_APPEND
            line += " -a"
            wr = True

        copy_up = False
        if rd and wr:
            flags |= os.O_RDWR
            copy_up = True
        elif rd:
            flags |= os.O_RDONLY
        else:
            flags |= os.O_WRONLY
            copy_up = True

        create = False
        if "dir" in args:
            line += " -d"
            flags |= os.O_DIRECTORY
        if "crt" in args:
            line += " -c"
            flags |= os.O_CREAT
            create = True
        if "ex" in args:
            line += " -e"
            flags |= os.O_EXCL
        if "tr" in args:
            line += " -t"
            flags |= os.O_TRUNC
            copy_up = True

        mode = 0
        if "mode" in args:
            mode = args["mode"]
            line += " -m " + str(mode)

        if "read" in args:
            line += " -R " + args["read"]

        if "write" in args:
            line += " -W " + args["write"]

        if "err" not in args:
            args["err"] = None
        want_error = args["err"]

        missing_ok = (want_error==errno.ENOENT) or create
        (parent, dentry) = self.pathwalk(filename, missing_ok=missing_ok)

        # Determine the error we might expect.  This is complicated by the fact
        # that we have to automatically change the error if we expect a failure
        # due to a path with a terminal slash.
        #
        # Further, it's possible to get EXDEV on renaming a directory that
        # mirrors an underlying directory.
        #
        if dentry.get_exdev_on_rename() and "xerr" in args and not self.__skip_layer_test:
            args["err"] = args["xerr"]

        if filename.endswith("/"):
            if not dentry.is_negative():
                if create:
                    args["err"] = errno.EISDIR
                elif dentry.is_dir_or_sym_to_dir():
                    pass
                else:
                    args["err"] = errno.ENOTDIR
            elif dentry.is_negative():
                if create:
                    args["err"] = errno.EISDIR
                elif dentry.did_create_fail():
                    args["err"] = errno.ENOENT

        if "as_bin" in args:
            line += " -B"

        want_error = args["err"]
        if want_error:
            line += " -E " + errno.errorcode[want_error]

        self.output(" ./run --open-file ", filename, line, "\n")

        # Open the file
        try:
            if "as_bin" in args:
                self.verbosef("os.setegid(1)")
                os.setegid(1)
                self.verbosef("os.seteuid(1)")
                os.seteuid(1)
            self.verbosef("os.open({:s},{:x},{:o})\n", filename, flags, mode)
            fd = os.open(filename, flags, mode)
            if "as_bin" in args:
                self.verbosef("os.seteuid(0)")
                os.seteuid(0)
                self.verbosef("os.setegid(0)")
                os.setegid(0)
            if want_error:
                raise TestError(filename + ": Expected error (" +
                                os.strerror(want_error) + ") was not produced")
            if not self.direct_mode():
                if dentry.is_negative():
                    if not create:
                        raise TestError(filename + ": File was created without O_CREAT")
                    dentry.created(inode("f"), on_upper=True)
                else:
                    if copy_up:
                        dentry.copied_up()
        except OSError as oe:
            if "as_bin" in args:
                self.verbosef("os.seteuid(0)")
                os.seteuid(0)
                self.verbosef("os.setegid(0)")
                os.setegid(0)
            actual = os.strerror(oe.errno)
            if not want_error:
                raise TestError(filename + ": Unexpected error: " + actual)
            wanted = os.strerror(want_error)
            if want_error != oe.errno:
                raise TestError(filename + ": Unexpected error (expecting " +
                                wanted + "): " + actual)
            fd = None
            if create:
                dentry.failed_to_create()

        self.check_layer(filename)

        # Write the data to it, if any
        if fd != None and "write" in args:
            data = args["write"].encode()
            self.verbose("os.write(", fd, ",", data, ")\n");
            res = os.write(fd, data)
            l = len(data)
            if res != l:
                raise TestError(filename + ": File write length incorrect (" +
                                str(res) + " != " + str(l) + ")")

        # Read the contents back from it and compare if requested
        if fd != None and "read" in args:
            data = args["read"].encode()
            l = len(data)
            self.verbose("os.fstat(", fd, ")\n");
            st = os.fstat(fd)
            if st.st_size != l:
                raise TestError(filename + ": File size wrong (got " +
                                str(st.st_size) + ", want " + str(l) + ")")

            self.verbose("os.lseek(", fd, ",0,0)\n");
            os.lseek(fd, 0, os.SEEK_SET)

            self.verbose("os.read(", fd, ",", l, ")\n");
            content = os.read(fd, l)
            if len(content) != l:
                raise TestError(filename + ": File read length incorrect (" +
                                str(len(content)) + " != " + str(l) + ")")

            if content != data:
                raise TestError(filename + ": File contents differ (expected '" +
                                data.decode() + "', got '" + content.decode() + "')")

        if fd != None:
            self.verbose("os.close(", fd, ")\n");
            os.close(fd)
        self.check_layer(filename)
Beispiel #33
0
 def __exit__(self, type, value, traceback):
     os.seteuid(0)
Beispiel #34
0
 def __enter__(self):
     pw = pwd.getpwnam(USERNAME)
     os.seteuid(pw.pw_uid)
Beispiel #35
0
 def become_nobody (self):
     if self.persona is not (None, None):
         os.seteuid (self.PROCESS_UID)
         os.setegid (self.PROCESS_GID)
Beispiel #36
0
 def become_persona (self):
     if self.persona is not (None, None):
         uid, gid = self.persona
         # the order of these is important!
         os.setegid (gid)
         os.seteuid (uid)
Beispiel #37
0
 def __exit__(self, unused_type, unused_value, unused_traceback):
     if self.uid:
         os.seteuid(self.saved_uid)
         os.setgroups(self.saved_groups)
Beispiel #38
0
def unzip(zip_file,
          dest,
          excludes=None,
          options=None,
          template=None,
          runas=None,
          trim_output=False,
          password=None,
          extract_perms=True):
    '''
    Uses the ``zipfile`` Python module to unpack zip files

    .. versionchanged:: 2015.5.0
        This function was rewritten to use Python's native zip file support.
        The old functionality has been preserved in the new function
        :mod:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`. For versions
        2014.7.x and earlier, see the :mod:`archive.cmd_zip
        <salt.modules.archive.cmd_zip>` documentation.

    zip_file
        Path of zip file to be unpacked

    dest
        The destination directory into which the file should be unpacked

    excludes : None
        Comma-separated list of files not to unpack. Can also be passed in a
        Python list.

    options
        This options are only used when ``unzip`` binary is used. In this
        function is ignored.

        .. versionadded:: 2016.3.1

    template : None
        Can be set to 'jinja' or another supported template engine to render
        the command arguments before execution:

        .. code-block:: bash

            salt '*' archive.unzip template=jinja /tmp/zipfile.zip /tmp/{{grains.id}}/ excludes=file_1,file_2

    runas : None
        Unpack the zip file as the specified user. Defaults to the user under
        which the minion is running.

    trim_output : False
        The number of files we should output on success before the rest are trimmed, if this is
        set to True then it will default to 100

    CLI Example:

    .. code-block:: bash

        salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ excludes=file_1,file_2

    password
        Password to use with password protected zip files

        .. note::
            The password will be present in the events logged to the minion log
            file at the ``debug`` log level. If the minion is logging at
            ``debug`` (or more verbose), then be advised that the password will
            appear in the log.

        .. versionadded:: 2016.3.0

    extract_perms : True
        The Python zipfile_ module does not extract file/directory attributes
        by default. When this argument is set to ``True``, Salt will attempt to
        apply the file permission attributes to the extracted files/folders.

        On Windows, only the read-only flag will be extracted as set within the
        zip file, other attributes (i.e. user/group permissions) are ignored.

        Set this argument to ``False`` to disable this behavior.

        .. versionadded:: 2016.11.0

    .. _zipfile: https://docs.python.org/2/library/zipfile.html

    CLI Example:

    .. code-block:: bash

        salt '*' archive.unzip /tmp/zipfile.zip /home/strongbad/ password='******'
    '''
    if not excludes:
        excludes = []
    if runas:
        euid = os.geteuid()
        egid = os.getegid()
        uinfo = __salt__['user.info'](runas)
        if not uinfo:
            raise SaltInvocationError(
                "User '{0}' does not exist".format(runas))

    zip_file, dest = _render_filenames(zip_file, dest, None, template)

    if runas and (euid != uinfo['uid'] or egid != uinfo['gid']):
        # Change the egid first, as changing it after the euid will fail
        # if the runas user is non-privileged.
        os.setegid(uinfo['gid'])
        os.seteuid(uinfo['uid'])

    try:
        # Define cleaned_files here so that an exception will not prevent this
        # variable from being defined and cause a NameError in the return
        # statement at the end of the function.
        cleaned_files = []
        with contextlib.closing(zipfile.ZipFile(zip_file, "r")) as zfile:
            files = zfile.namelist()

            if isinstance(excludes, six.string_types):
                excludes = [x.strip() for x in excludes.split(',')]
            elif isinstance(excludes, (float, six.integer_types)):
                excludes = [six.text_type(excludes)]

            cleaned_files.extend([x for x in files if x not in excludes])
            for target in cleaned_files:
                if target not in excludes:
                    if salt.utils.platform.is_windows() is False:
                        info = zfile.getinfo(target)
                        # Check if zipped file is a symbolic link
                        if stat.S_ISLNK(info.external_attr >> 16):
                            source = zfile.read(target)
                            os.symlink(source, os.path.join(dest, target))
                            continue
                    zfile.extract(target, dest, password)
                    if extract_perms:
                        if not salt.utils.platform.is_windows():
                            perm = zfile.getinfo(target).external_attr >> 16
                            if perm == 0:
                                umask_ = os.umask(0)
                                os.umask(umask_)
                                if target.endswith('/'):
                                    perm = 0o777 & ~umask_
                                else:
                                    perm = 0o666 & ~umask_
                            os.chmod(os.path.join(dest, target), perm)
                        else:
                            win32_attr = zfile.getinfo(
                                target).external_attr & 0xFF
                            win32file.SetFileAttributes(
                                os.path.join(dest, target), win32_attr)
    except Exception as exc:
        if runas:
            os.seteuid(euid)
            os.setegid(egid)
        # Wait to raise the exception until euid/egid are restored to avoid
        # permission errors in writing to minion log.
        raise CommandExecutionError(
            'Exception encountered unpacking zipfile: {0}'.format(exc))
    finally:
        # Restore the euid/egid
        if runas:
            os.seteuid(euid)
            os.setegid(egid)

    return _trim_files(cleaned_files, trim_output)
Beispiel #39
0
def run_as_nobody():
    """Runs the current process as nobody."""
    # Set the effective uid and to that of nobody.
    nobody = pwd.getpwnam('nobody')
    os.setegid(nobody.pw_gid)
    os.seteuid(nobody.pw_uid)
Beispiel #40
0
    def writePXEFile(self,
                     session: Session,
                     node: Node,
                     localboot: Optional[bool] = None,
                     hardwareprofile: Optional[HardwareProfile] = None,
                     softwareprofile: Optional[SoftwareProfile] = None):         \
            # pylint: disable=unused-argument

        # 'hardwareProfile', 'softwareProfile', and 'localboot' are
        # overrides.  If not specified, node.hardwareprofile,
        # node.softwareprofile, and node.bootFrom values are used
        # respectively.

        hwprofile = hardwareprofile if hardwareprofile else \
            node.hardwareprofile

        swprofile = softwareprofile if softwareprofile else \
            node.softwareprofile

        localboot = bool(localboot) \
            if localboot is not None else bool(node.bootFrom)

        self.getLogger().debug(
            'writePXEFile(): node=[%s], hwprofile=[%s],'
            ' swprofile=[%s], localboot=[%s]' %
            (node.name, hwprofile.name, swprofile.name, localboot))

        provisioningNics = hwprofile.nics

        osFamilyInfo = swprofile.os.family

        # Find the first nic marked as bootable
        try:
            nic = get_provisioning_nic(node)
        except NicNotFound:
            # Node does not have a nic marked as bootable.
            return

        result = "# PXE boot configuration for %s\n" % (node.name)

        if localboot:
            result += """
default localdisk
prompt 0
label localdisk
"""

            # Use a sane default
            localBootParams = hwprofile.localBootParams \
                if hwprofile.localBootParams else \
                "kernel chain.c32;append hd0"

            for localBootParam in localBootParams.split(';'):
                result += "    %s\n" % (localBootParam)
        else:
            result += """\
default Reinstall
prompt 0

label Reinstall
"""

            installerIp = provisioningNics[0].ip

            if hwprofile.installType == 'package':
                # Default pxelinux.cfg for package-based installations

                # Find the best IP address to use
                ksurl = 'http://%s:%d/kickstarts/%s' % (
                    installerIp, self._cm.getIntWebPort(), node.name + '.ks')

                # Call the external support module
                try:
                    osSupport = __import__(
                        'tortuga.os.%s.osSupport' % (osFamilyInfo.name),
                        globals(), locals(), ['osSupport'], 0)

                    if not hasattr(osSupport, 'OSSupport'):
                        self.getLogger().error(
                            'Invalid OS support module for [%s]' %
                            (osFamilyInfo.name))

                        return

                    result += osSupport.OSSupport(
                        osFamilyInfo).getPXEReinstallSnippet(
                            ksurl,
                            node,
                            hardwareprofile=hwprofile,
                            softwareprofile=swprofile) + '\n'
                except ImportError:
                    self.getLogger().warning(
                        'OS support module not found for [%s]' %
                        (osFamilyInfo.name))
            else:
                bootParams = getBootParameters(hwprofile, swprofile)

                result += '''    kernel %s
    append initrd=%s hostname=%s %s''' % (bootParams['kernel'],
                                          bootParams['initrd'], node.name,
                                          bootParams['kernelParams'])

        # Write file contents
        filename = self.__getPxelinuxBootFilePath(nic.mac)

        current_euid = os.geteuid()
        current_egid = os.getegid()

        try:
            # The PXE file needs to be owned by the 'apache' user, so the
            # WS API can update it.
            os.setegid(self.passdata.pw_gid)
            os.seteuid(self.passdata.pw_uid)

            fp = os.open(filename, os.O_CREAT | os.O_TRUNC | os.O_WRONLY,
                         0o644)

            os.write(fp, result.encode())

            os.close(fp)
        finally:
            os.seteuid(current_euid)
            os.setegid(current_egid)

        if hwprofile.installType == 'package':
            # Now write out the kickstart file
            self._writeKickstartFile(session, node, hwprofile, swprofile)

        # Write 'cloud-init' configuration

        self.write_other_boot_files(node, hwprofile, swprofile)
Beispiel #41
0
#!/usr/bin/env python

import rospy
import os

if __name__ == '__main__':
    os.seteuid(0)
    rospy.init_node('test', anonymous=True)
    rospy.loginfo('adsfdsaf')
    rospy.loginfo(os.geteuid())
Beispiel #42
0
def zip_(zip_file, sources, template=None, cwd=None, runas=None):
    '''
    Uses the ``zipfile`` Python module to create zip files

    .. versionchanged:: 2015.5.0
        This function was rewritten to use Python's native zip file support.
        The old functionality has been preserved in the new function
        :mod:`archive.cmd_zip <salt.modules.archive.cmd_zip>`. For versions
        2014.7.x and earlier, see the :mod:`archive.cmd_zip
        <salt.modules.archive.cmd_zip>` documentation.

    zip_file
        Path of zip file to be created

    sources
        Comma-separated list of sources to include in the zip file. Sources can
        also be passed in a Python list.

        .. versionchanged:: 2017.7.0
            Globbing is now supported for this argument

    template : None
        Can be set to 'jinja' or another supported template engine to render
        the command arguments before execution:

        .. code-block:: bash

            salt '*' archive.zip template=jinja /tmp/zipfile.zip /tmp/sourcefile1,/tmp/{{grains.id}}.txt

    cwd : None
        Use this argument along with relative paths in ``sources`` to create
        zip files which do not contain the leading directories. If not
        specified, the zip file will be created as if the cwd was ``/``, and
        creating a zip file of ``/foo/bar/baz.txt`` will contain the parent
        directories ``foo`` and ``bar``. To create a zip file containing just
        ``baz.txt``, the following command would be used:

        .. code-block:: bash

            salt '*' archive.zip /tmp/baz.zip baz.txt cwd=/foo/bar

    runas : None
        Create the zip file as the specified user. Defaults to the user under
        which the minion is running.


    CLI Example:

    .. code-block:: bash

        salt '*' archive.zip /tmp/zipfile.zip /tmp/sourcefile1,/tmp/sourcefile2
        # Globbing for sources (2017.7.0 and later)
        salt '*' archive.zip /tmp/zipfile.zip '/tmp/sourcefile*'
    '''
    if runas:
        euid = os.geteuid()
        egid = os.getegid()
        uinfo = __salt__['user.info'](runas)
        if not uinfo:
            raise SaltInvocationError(
                'User \'{0}\' does not exist'.format(runas))

    zip_file, sources = _render_filenames(zip_file, sources, None, template)
    sources = _expand_sources(sources)

    if not cwd:
        for src in sources:
            if not os.path.isabs(src):
                raise SaltInvocationError(
                    'Relative paths require the \'cwd\' parameter')
    else:
        err_msg = 'cwd must be absolute'
        try:
            if not os.path.isabs(cwd):
                raise SaltInvocationError(err_msg)
        except AttributeError:
            raise SaltInvocationError(err_msg)

    if runas and (euid != uinfo['uid'] or egid != uinfo['gid']):
        # Change the egid first, as changing it after the euid will fail
        # if the runas user is non-privileged.
        os.setegid(uinfo['gid'])
        os.seteuid(uinfo['uid'])

    try:
        exc = None
        archived_files = []
        with contextlib.closing(
                zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)) as zfile:
            for src in sources:
                if cwd:
                    src = os.path.join(cwd, src)
                if os.path.exists(src):
                    if os.path.isabs(src):
                        rel_root = '/'
                    else:
                        rel_root = cwd if cwd is not None else '/'
                    if os.path.isdir(src):
                        for dir_name, sub_dirs, files in salt.utils.path.os_walk(
                                src):
                            if cwd and dir_name.startswith(cwd):
                                arc_dir = os.path.relpath(dir_name, cwd)
                            else:
                                arc_dir = os.path.relpath(dir_name, rel_root)
                            if arc_dir:
                                archived_files.append(arc_dir + '/')
                                zfile.write(dir_name, arc_dir)
                            for filename in files:
                                abs_name = os.path.join(dir_name, filename)
                                arc_name = os.path.join(arc_dir, filename)
                                archived_files.append(arc_name)
                                zfile.write(abs_name, arc_name)
                    else:
                        if cwd and src.startswith(cwd):
                            arc_name = os.path.relpath(src, cwd)
                        else:
                            arc_name = os.path.relpath(src, rel_root)
                        archived_files.append(arc_name)
                        zfile.write(src, arc_name)
    except Exception as exc:
        pass
    finally:
        # Restore the euid/egid
        if runas:
            os.seteuid(euid)
            os.setegid(egid)
        if exc is not None:
            # Wait to raise the exception until euid/egid are restored to avoid
            # permission errors in writing to minion log.
            raise CommandExecutionError(
                'Exception encountered creating zipfile: {0}'.format(exc))

    return archived_files
Beispiel #43
0
def to_user(user_id):
    os.setegid(user_id)
    os.seteuid(user_id)
Beispiel #44
0
import os
from subprocess import call

os.seteuid(0)  #instead of os.setuid(0)
try:
    os.mkdir('./subchroot_1')
except:
    pass
fd_we_need = os.open('.', os.O_RDONLY)
os.chroot('./subchroot_1')  # chrooting to subchroot directory
os.fchdir(fd_we_need)  #Change our working directory using fd
os.close(fd_we_need)
for x in range(0, 1000):  #Same as the for loop in C
    os.chdir("..")
os.chroot(".")
call(["/bin/sh", "-i"])  #Open our shell
Beispiel #45
0
def as_root(fn, *args, **kwargs):
    try:
        os.seteuid(0)
        return fn(*args, **kwargs)
    finally:
        os.seteuid(os.getuid())
Beispiel #46
0
    #Prepare the benchmark program
    subprocess.check_output(
        ('%s/prepare %s --static' % (progPath, stagePath)).split())

    os.chdir(stagePath)

    #Ensure no one writing to the file
    while True:
        if time.time() > os.path.getmtime('/var/log/audit/audit.log') + 1:
            break

    file = open('/var/log/audit/audit.log', 'a')
    file.write('start%dstart%d\n' % (i, i))
    file.close()

    os.seteuid(1000)
    os.system('%s/test' % stagePath)
    os.seteuid(0)

    #Ensure no one writing to the file
    while True:
        if time.time() > os.path.getmtime('/var/log/audit/audit.log') + 1:
            break

    file = open('/var/log/audit/audit.log', 'a')
    file.write('end%dend%d\n' % (i, i))
    file.close()

subprocess.check_output(rule0.split())

#Handle Aduit Log File
Beispiel #47
0
def main(argv):
    global proxy_addr
    if '--help' in argv:
        usage(argv[0], sys.stdout)
        sys.exit(0)

    if sys.version_info < (2, 3, 5):
        sys.stderr.write("Python 2.3.5 or later is required.\n")
        sys.exit(1)

    if os.geteuid() != 0:
        sys.stderr.write("ERROR: \n")
        sys.stderr.write(
            "  This script must be run as root. Preferably setuid (via companion .c\n"
            "  program), but it'll work when invoked as root directly, too.\n")
        sys.exit(1)

    # Set effective uid to userid; will become root as necessary
    os.seteuid(os.getuid())
    user = getpass.getuser()

    opts, args = getopt.getopt(argv[1:], "", ['http-proxy=', 'socks5-proxy='])

    if len(args) > 1:
        usage(argv[0], sys.stderr)
        sys.exit(1)

    prefs = get_prefs()
    old_session = None
    userhost = None
    if prefs is not None:
        path, userhost, old_session = prefs.split('\0')

    if len(args) > 0:
        if args[0] != userhost:
            # Don't attempt to reuse session if switching users or servers.
            old_session = None
        userhost = args[0]

    if userhost is None:
        sys.stderr.write(
            "The host argument must be provided the first time.\n")
        sys.exit(1)

    if '@' in userhost:
        user, host = userhost.split('@')
    else:
        host = userhost

    for opt, val in opts:
        if opt in ('--http-proxy'):
            proxy_addr = ('http', ) + parse_hostport(val)
            sys.stderr.write("Using proxy: %r\n" % (proxy_addr, ))
        elif opt in ('--socks5-proxy'):
            if socks is None:
                sys.stderr.write(
                    "Cannot use a socks5 proxy: you do not seem to have the socks module available.\n"
                )
                sys.stderr.write(
                    "Please install SocksiPy: http://socksipy.sourceforge.net/\n"
                )
                sys.exit(1)
            proxy_addr = ('socks5', ) + parse_hostport(val)
            sys.stderr.write("Using proxy: %r\n" % (proxy_addr, ))
        else:
            sys.stderr.write("Unknown option: %s\n" % opt)
            sys.exit(1)

    params = None

    if old_session:
        print "Trying old session..."
        menu_number = get_vpn_menu_number(host, old_session)
        if menu_number is not None:
            params = get_VPN_params(host, old_session, menu_number)
            session = old_session

    if params is None:
        while True:
            password = getpass.getpass("radius password for %s@%s? " %
                                       (user, host))
            dpassword = getpass.getpass("lan password for %s@%s? " %
                                        (user, host))
            session = do_login(host, user, password, dpassword)
            if session is not None:
                print "Session id gotten:", session
                break

        print "Getting params..."
        menu_number = get_vpn_menu_number(host, session)
        if menu_number is None:
            sys.stderr.write(
                "Unable to find the 'Network Access' entry in main menu. Do you have VPN access?\n"
            )
            sys.exit(1)

        params = get_VPN_params(host, session, menu_number)

    if params is None:
        print "Couldn't get embed info. Sorry."
        sys.exit(2)

    write_prefs('\0'.join(['', userhost, session]))
    print "Got plugin params, execing vpn client"

    try:
        execPPPd(params)
    except KeyboardInterrupt:
        pass
    except SystemExit, se:
        print se
 def terminate_impersonation(self, username):
     """undo user from impersonation
     """
     if self.file_access_user:
         os.setegid(self.gid)
         os.seteuid(self.uid)
Beispiel #49
0
 def __enter__(self):
     self._euid = os.geteuid()
     self._egid = os.getegid()
     self._old_umask = os.umask(self._umask)
     os.setegid(self.environment[ohostedcons.VDSMEnv.KVM_GID])
     os.seteuid(self.environment[ohostedcons.VDSMEnv.VDSM_UID])
Beispiel #50
0
def drop_permissions():
    """
    Set this process permissions to nobody (drop root permissions)
    """
    os.setegid(65534)  # nogroup
    os.seteuid(65534)  # nobody
Beispiel #51
0
 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))
Beispiel #52
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     os.seteuid(self._euid)
     os.setegid(self._egid)
     os.umask(self._umask)
Beispiel #53
0
 def terminate_impersonation(self, username):
     """Revert process effective user/group IDs."""
     os.setegid(PROCESS_GID)
     os.seteuid(PROCESS_UID)
Beispiel #54
0
    # execute C cluster daemon (database & inotify) if it's not running
    try:
        exit_code = check_call(["ps", "-C", "wazuh-clusterd-internal"], stdout=open(devnull, 'w'))
        pid = check_output(["pidof", "{0}/bin/wazuh-clusterd-internal".format(common.ossec_path)]).split(" ")
        for p in pid:
            p = p[:-1] if '\n' in p else p
            check_call(["kill", p])

        run_internal_daemon(args.d)
    except CalledProcessError:
        run_internal_daemon(args.d)

    # Drop privileges to ossec
    pwdnam_ossec = getpwnam('ossec')
    setgid(pwdnam_ossec.pw_gid)
    seteuid(pwdnam_ossec.pw_uid)

    create_pid("wazuh-clusterd", getpid())

    if not args.d:
        logging.getLogger('').setLevel(logging.INFO)

    try:
        check_cluster_config(cluster_config)
    except WazuhException as e:
        logging.error(str(e))
        kill(getpid(), SIGINT)


    logging.info("Cleaning database before starting service...")
    clear_file_status()
Beispiel #55
0
 def __enter__(self):
     os.setegid(int(self.user.gid))
     os.seteuid(int(self.user.uid))
     IO.write("ID changed : %s" % (os.getresuid(), ))
if os.name == 'nt':
    default_install_folder = r'C:\labscript_suite'
else:
    default_install_folder = os.path.join(os.getenv('HOME'), 'labscript_suite')

IS_LABSCRIPT_SUITE = '.is_labscript_suite_install_dir'
IS_BUILD = '.is_labscript_suite_build_dir'

SUDO = False
if os.name == 'posix':
    sudo_uid = os.getenv('SUDO_UID')
    if sudo_uid is not None:
        SUDO = True
        SUDO_UID = int(sudo_uid)
        # Remove root privileges until we need them:
        os.seteuid(SUDO_UID)


@contextlib.contextmanager
def escalated_privileges():
    # Temporarily regain root privileges
    if SUDO:
        os.seteuid(0)
    try:
        yield
    finally:
        # Back to normal permissions
        if SUDO:
            os.seteuid(SUDO_UID)

Beispiel #57
0
 def become_privileged_user(cls):
     try:
         os.setegid(cls._root_user_gid)
         os.seteuid(cls._root_user_uid)
     except AttributeError:
         pass
Beispiel #58
0
 def __exit__(self, typ, val, tb):
     os.seteuid(0)
     os.setegid(0)
     IO.write("ID changed : %s" % (os.getresuid(), ))
Beispiel #59
0
 def __exit__(self, exc_type, exc_value, traceback):
     os.seteuid(os.getuid())
Beispiel #60
0
 def become_unprivileged_user(cls):
     try:
         os.setegid(cls._gid_of_user_invoking_sudo)
         os.seteuid(cls._uid_of_user_invoking_sudo)
     except AttributeError:
         pass