Set settings.DROPLET_USER effective UID for the current process

    This adds some security, but nothing magic, an attacker can still
    gain root access, but at least we only elevate privileges when needed

    See root context manager
163544
def set_euid():
    
    current = os.geteuid()
    logger.debug("Current EUID is %s" % current)

    if settings.DROPLET_USER is None:
        logger.info("Not changing EUID, DROPLET_USER is None")
        return

    uid = int(pwd.getpwnam(settings.DROPLET_USER).pw_uid)
    if current != uid:
        try:
            os.seteuid(uid)
            logger.info("Set EUID to %s (%s)" %
                        (settings.DROPLET_USER, os.geteuid()))
        except:
            current_user = pwd.getpwuid(os.getuid()).pw_name
            logger.error("Failed to set '%s' EUID, running as '%s'" %
                         (settings.DROPLET_USER, current_user))
    else:
        logger.debug("Didn't set EUID, it was already correct")
1066309
def setup_sudo_access(plugin):
    

    def run_root(self, command):
        """ Executes a shell command as root.

            `command`
                Shell command string.

            Returns boolean.
            """
        try:
            return not (common.shell_process('sudo ' + command) is None)

        except KeyboardInterrupt:  # user cancelled
            return False

    plugin.run_root = types.MethodType(run_root, plugin)
666441
def get_uid(user=None):
    '''
    
    '''
    if not HAS_PWD:
        return None
    elif user is None:
        try:
            return os.geteuid()
        except AttributeError:
            return None
    else:
        try:
            return pwd.getpwnam(user).pw_uid
        except KeyError:
            return None
1056126
def _filter_by_user(self, user, pids):
        
        filtered_pids = set()
        for pid in pids:
            try:
                proc = psutil.Process(pid)
                if proc.username() == user:
                    self.log.debug("Collecting pid {} belonging to {}".format(pid, user))
                    filtered_pids.add(pid)
                else:
                    self.log.debug("Discarding pid {} not belonging to {}".format(pid, user))
            except psutil.NoSuchProcess:
                pass

        return filtered_pids
1367491
def disable_root():
    
    
    def enter_password():
        password1 = getpass.getpass(prompt='Enter the password for %s:'% sudo_user)
        password2 = getpass.getpass(prompt='Re-enter the password:')
        if password1 <> password2:
            print env.host, 'The password was not the same'
            enter_password()
        return password1

    (olduser,host,port) = normalize(env.host_string)
 
    if env.verbosity and not (env.HOST_USER or env.ROLEDEFS):
    
        print "\nWOVEN will now walk through setting up your node (host).\n"

        if env.INTERACTIVE:
            root_user = prompt("\nWhat is the default administrator account for your node?", default=env.ROOT_USER)
        else: root_user = env.ROOT_USER
        if env.user <> 'root': sudo_user = env.user
        else: sudo_user = ''
        if env.INTERACTIVE:
            sudo_user = prompt("What is the new or existing account you wish to use to setup and deploy to your node?", default=sudo_user)
           
    else:
        root_user = env.ROOT_USER
        sudo_user = env.user
        

    original_password = env.get('HOST_PASSWORD','')
    
    host_string=join_host_strings(root_user,host,str(env.DEFAULT_SSH_PORT))
    with settings(host_string=host_string, key_filename=env.key_filename, password=env.ROOT_PASSWORD):
        if not contains('/etc/group','sudo',use_sudo=True):
            sudo('groupadd sudo')

        home_path = '/home/%s'% sudo_user
        if not exists(home_path):
            if env.verbosity:
                print env.host, 'CREATING A NEW ACCOUNT WITH SUDO PRIVILEGE: %s'% sudo_user
            if not original_password:

                original_password = enter_password()
            
            add_user(username=sudo_user, password=original_password,group='sudo')

        #Add existing user to sudo group
        else:
            sudo('adduser %s sudo'% sudo_user)
        #adm group used by Ubuntu logs
        sudo('usermod -a -G adm %s'% sudo_user)
        #add user to /etc/sudoers
        if not exists('/etc/sudoers.wovenbak',use_sudo=True):
            sudo('cp -f /etc/sudoers /etc/sudoers.wovenbak')
        sudo('cp -f /etc/sudoers /tmp/sudoers.tmp')
        append('/tmp/sudoers.tmp', "# Members of the sudo group may gain root privileges", use_sudo=True)
        append('/tmp/sudoers.tmp', "%sudo ALL=(ALL) NOPASSWD:ALL",  use_sudo=True)
        sudo('visudo -c -f /tmp/sudoers.tmp')
        sudo('cp -f /tmp/sudoers.tmp /etc/sudoers')
        sudo('rm -rf /tmp/sudoers.tmp')
        if env.key_filename:
            sudo('mkdir -p /home/%s/.ssh'% sudo_user)
            sudo('cp -f ~/.ssh/authorized_keys /home/%s/.ssh/authorized_keys'% sudo_user)
            sudo('chown -R %s:sudo /home/%s/.ssh'% (sudo_user,sudo_user))
            
    env.password = original_password

    #finally disable root
    host_string=join_host_strings(sudo_user,host,str(env.DEFAULT_SSH_PORT))
    with settings(host_string=host_string):
        if sudo_user <> root_user and root_user == 'root':
            if env.INTERACTIVE:
                d_root = confirm("Disable the root account", default=True)
            else: d_root = env.DISABLE_ROOT
            if d_root:
                if env.verbosity:
                    print env.host, 'DISABLING ROOT'
                sudo("usermod -L %s"% 'root')

    return True
626751
def grant_sudo_privileges(request, max_age=COOKIE_AGE):
    
    user = getattr(request, 'user', None)

    # If there's not a user on the request, just noop
    if user is None:
        return

    if not user.is_authenticated():
        raise ValueError('User needs to be logged in to be elevated to sudo')

    # Token doesn't need to be unique,
    # just needs to be unpredictable and match the cookie and the session
    token = get_random_string()
    request.session[COOKIE_NAME] = token
    request._sudo = True
    request._sudo_token = token
    request._sudo_max_age = max_age
    return token
266727
def configure_owner(self, owner='www-data'):
        
        if owner is not None:
            self.main_process.set_owner_params(uid=owner, gid=owner)

        return self
257059
def deny_user(user):
    """"""
    def processor(action, argument):
        db.session.add(
            ActionUsers.deny(action, argument=argument, user_id=user.id)
        )
    return processor
289687
def set_pidfile(pidfile, user):
    '''
    
    '''
    pdir = os.path.dirname(pidfile)
    if not os.path.isdir(pdir) and pdir:
        os.makedirs(pdir)
    try:
        with salt.utils.files.fopen(pidfile, 'w+') as ofile:
            ofile.write(str(os.getpid()))  # future lint: disable=blacklisted-function
    except IOError:
        pass

    log.debug('Created pidfile: %s', pidfile)
    if salt.utils.platform.is_windows():
        return True

    import pwd  # after confirming not running Windows
    #import grp
    try:
        pwnam = pwd.getpwnam(user)
        uid = pwnam[2]
        gid = pwnam[3]
        #groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
    except (KeyError, IndexError):
        sys.stderr.write(
            'Failed to set the pid to user: {0}. The user is not '
            'available.\n'.format(
                user
            )
        )
        sys.exit(salt.defaults.exitcodes.EX_NOUSER)

    if os.getuid() == uid:
        # The current user already owns the pidfile. Return!
        return

    try:
        os.chown(pidfile, uid, gid)
    except OSError as err:
        msg = (
            'Failed to set the ownership of PID file {0} to user {1}.'.format(
                pidfile, user
            )
        )
        log.debug('%s Traceback follows:', msg, exc_info=True)
        sys.stderr.write('{0}\n'.format(msg))
        sys.exit(err.errno)
    log.debug('Chowned pidfile: %s to user: %s', pidfile, user)
150466
def containsUid(self, uid):
        '''
            
        '''
        for rootNode in self.getRootNodes():
            if rootNode.containsUid(uid):
                return True

        return False
1198591
def setUser(request):
    """"""

    if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS:
        raise Http404

    request.session['plugit-standalone-usermode'] = request.GET.get('mode')

    return HttpResponse('')
835502
def enable_root(host)
      if host['user'] != 'root'
        copy_ssh_to_root(host, @options)
        enable_root_login(host, @options)
        host['user'] = 'root'
        host.close
      end
    end
540969
def _set(self, value):
        '''
        

        '''
        user = self.USER
        try:
            uid = pwd.getpwnam(user).pw_uid
        except KeyError:
            log.info('User does not exist')
            result = {}
            result['retcode'] = 1
            result['stdout'] = 'User {0} does not exist'.format(user)
            return result

        cmd = self.gsetting_command + ['set', self.SCHEMA, self.KEY, value]
        environ = {}
        environ['XDG_RUNTIME_DIR'] = '/run/user/{0}'.format(uid)
        result = __salt__['cmd.run_all'](cmd, runas=user, env=environ, python_shell=False)
        return result
1142197
def setsudo(self, user=None):
        
        if user is None:
            try:
                self.headers.pop('SUDO')
            except KeyError:
                pass
        else:
            self.headers['SUDO'] = user
961345
def update_user(resource_root, user):
  
  return call(resource_root.put,
      '%s/%s' % (USERS_PATH, user.name), ApiUser, data=user)
598775
def current_user_name_or_id
      require 'etc' if !defined?(Etc)
      begin
        user = Etc.getpwuid(Process.uid)
      rescue ArgumentError
        user = nil
      end
      if user
        return user.name
      else
        return "##{Process.uid}"
      end
    end
257764
def create_stack_user(self):
        
        self.run('adduser -m stack', success_status=(0, 9))
        self.create_file('/etc/sudoers.d/stack', 'stack ALL=(root) NOPASSWD:ALL\n')
        self.run('mkdir -p /home/stack/.ssh')
        self.run('cp /root/.ssh/authorized_keys /home/stack/.ssh/authorized_keys')
        self.run('chown -R stack:stack /home/stack/.ssh')
        self.run('chmod 700 /home/stack/.ssh')
        self.run('chmod 600 /home/stack/.ssh/authorized_keys')
        self.ssh_pool.build_ssh_client(self.hostname, 'stack',
                                       self._key_filename,
                                       self.via_ip)