Example #1
0
def osPrintInfo():
    print os.ctermid()
    print os.getegid()
    print os.getgroups()
    print os.getlogin()
    print os.getpid()
    print os.getresuid()
    # os.setegid(1001)
    # os.setgid(1000)
    print os.getpid()
Example #2
0
def su(uid=None,gid=None,sub=False):
    #set effective or subprocess user/group if valid and not root,
    #if gid not provided, will use effective user's group
    #if uid is a string, get the uid
    #if sub=True, return a preexeec function that will set the uid/gid
    if type(uid) is str: uid=pwd.getpwnam(uid).pw_uid
    #if uid valid
    if uid and uid>0: 
        if type(gid) is str: gid=grp.getgrnam(gid).gr_gid
        #if no valid group specified, use user's group
        if gid and gid>0: pass
        else: gid=pwd.getpwuid(uid).pw_gid
        #reset effective uid (likely back to root) so we can change it again
        if sub:
            def preexec_fn():
                os.seteuid(os.getuid())
                os.setgid(gid)
                os.setuid(uid)
                os.setsid() #make session leader so kill works
            return preexec_fn
        else:
            os.seteuid(os.getuid())
            os.setegid(gid)
            os.seteuid(uid)
            return os.getresuid(),os.getresgid()
Example #3
0
def initialize(config, LOG):
    """ Store initial values for UID/GID, and setup the user cache."""
    (_, euid, _) = os.getresuid()
    (_, egid, _) = os.getresgid()
    # store effective uid/gid, we'll switch back to these after every action
    config['tsi.effective_uid'] = euid
    config['tsi.effective_gid'] = egid
    switch_uid = config.get("tsi.switch_uid", True)
    if switch_uid or euid == 0:
        LOG.info(
            "Running privileged, will perform all operations as the requested user."
        )
        config['tsi.switch_uid'] = True
    else:
        LOG.info("Running unprivileged.")
        config['tsi.switch_uid'] = False

    if config['tsi.enforce_os_gids']:
        LOG.info(
            "Groups of the user will be limited to those available in the OS.")
    else:
        LOG.info("UNICORE will be free to assign any groups to the user "
                 "regardless of the OS settings.")

    cache_ttl = config.get('tsi.userCacheTtl', 600)
    use_id = config['tsi.use_id_to_resolve_gids']
    if use_id:
        LOG.info("Groups will be resolved via 'id -G <username>")

    user_cache = UserCache.UserCache(cache_ttl, LOG, use_id)
    config['tsi.user_cache'] = user_cache
Example #4
0
def _make_passphrase(length=None, save=False, file=None):
    """Create a passphrase and write it to a file that only the user can read.

    This is not very secure, and should not be relied upon for actual key
    passphrases.

    :param int length: The length in bytes of the string to generate.

    :param file file: The file to save the generated passphrase in. If not
        given, defaults to 'passphrase-<the real user id>-<seconds since
        epoch>' in the top-level directory.
    """
    if not length:
        length = 40

    passphrase = _make_random_string(length)

    if save:
        ruid, euid, suid = os.getresuid()
        gid = os.getgid()
        now = mktime(localtime())

        if not file:
            filename = str('passphrase-%s-%s' % uid, now)
            file = os.path.join(_repo, filename)

        with open(file, 'a') as fh:
            fh.write(passphrase)
            fh.flush()
            fh.close()
            os.chmod(file, stat.S_IRUSR | stat.S_IWUSR)
            os.chown(file, ruid, gid)

        log.warn("Generated passphrase saved to %s" % file)
    return passphrase
Example #5
0
def SwitchRoot():
    (ruid, euid, suid) = os.getresuid()
    if suid == 0:
        os.setuid(0)
        os.setgid(0)
    else:
        raise Exception("Cannot switch on root user")
Example #6
0
def get_cachedir(dir_name='fpn_cache', user_dirs=False):
    """
    Get temp cachedir according to OS (create it if needed)
    * override the dir_name arg for non-cache data
    """
    import os
    import pwd
    import tempfile

    from appdirs import AppDirs

    temp_dir = tempfile.gettempdir()
    dirs = AppDirs('fpnd', 'FreePN')
    if user_dirs or NODE_SETTINGS['runas_user']:
        cache_dir = dirs.user_cache_dir
    else:
        cache_dir = '/var/lib/fpnd'
        sys_usr = pwd.getpwuid(os.geteuid()).pw_name
        sys_uids = os.getresuid()
        if not sys_usr == 'fpnd' and 0 not in sys_uids:
            cache_dir = temp_dir
        # logger.debug('UIDs for cachedir: {}'.format(sys_uids))
        # logger.debug('effective user for cachedir: {}'.format(sys_usr))
    if cache_dir == temp_dir:
        logger.debug('Falling back to temp dir: {}'.format(temp_dir))
    return os.path.join(cache_dir, dir_name)
Example #7
0
def about_user():
    """Show information about the user"""
    if parameters["User"]:
        print("[User]")
        user = getpass.getuser()
        print("getpass.getuser()={}".format(user))
        print("os.getlogin()={}".format(os.getlogin()))
        if sys_type() == "Unix":
            print('pwd.getpwnam("{}")={}'.format(user, pwd.getpwnam(user)))
            print("os.getgroups()={}".format(os.getgroups()))
            for group_id in os.getgroups():
                print("grp.getgrgid({})={}".format(group_id,
                                                   grp.getgrgid(group_id)))
        elif sys_type() == "Windows":
            if os.environ["USERNAME"]:
                print('os.environ["USERNAME"]={}'.format(
                    os.environ["USERNAME"]))
            if os.environ["USERPROFILE"]:
                print('os.environ["USERPROFILE"]={}'.format(
                    os.environ["USERPROFILE"]))
            if os.environ["USERDOMAIN"]:
                print('os.environ["USERDOMAIN"]={}'.format(
                    os.environ["USERDOMAIN"]))
            if os.environ["USERDOMAIN_ROAMINGPROFILE"]:
                print('os.environ["USERDOMAIN_ROAMINGPROFILE"]={}'.format(
                    os.environ["USERDOMAIN_ROAMINGPROFILE"]))
            if os.environ["HOME"]:
                print('os.environ["HOME"]={}'.format(os.environ["HOME"]))
            if os.environ["HOMEDRIVE"]:
                print('os.environ["HOMEDRIVE"]={}'.format(
                    os.environ["HOMEDRIVE"]))
            if os.environ["HOMEPATH"]:
                print('os.environ["HOMEPATH"]={}'.format(
                    os.environ["HOMEPATH"]))
        print()

        print("[User/Process]")
        if sys_type() == "Unix":
            print("os.getuid()={}".format(os.getuid()))
            print("os.getgid()={}".format(os.getgid()))
            print("os.geteuid()={}".format(os.geteuid()))
            print("os.getegid()={}".format(os.getegid()))
            print("os.getresuid()={}".format(os.getresuid()))
            print("os.getresgid()={}".format(os.getresgid()))
        print()

        print("[Process]")
        pid = os.getpid()
        print("os.getpid()={}".format(pid))
        print("os.getppid()={}".format(os.getppid()))
        if sys_type() == "Unix":
            print("os.getpgid({})={}".format(pid, os.getpgid(pid)))
            print("os.getpgrp()={}".format(os.getpgrp()))
            print("os.getpriority(os.PRIO_PROCESS, 0)={}".format(
                os.getpriority(os.PRIO_PROCESS, 0)))
            print("os.getpriority(os.PRIO_PGRP, 0)={}".format(
                os.getpriority(os.PRIO_PGRP, 0)))
            print("os.getpriority(os.PRIO_USER, 0)={}".format(
                os.getpriority(os.PRIO_USER, 0)))
        print()
Example #8
0
def ottieniValori():
    #  https://docs.python.org/3.3/library/os.html
    userLogin           = os.getlogin()
    userLogin           = pwd.getpwuid(os.getuid())[0]
    uid                 = os.getuid()   # current process’s user id
    ruid, euid, suid    = os.getresuid()   # real, effective, and saved user ids
    rgid, egid, sgid    = os.getresgid()   # real, effective, and saved group ids.
Example #9
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)
Example #10
0
def SwitchRoot():
    (ruid, euid, suid) = os.getresuid()
    if suid == 0:
        os.setuid(0)
        os.setgid(0)
    else:
        raise Exception("Cannot switch on root user")
Example #11
0
    def __init__(self, *args, **kw):
        if kw.has_key("name"):
            name = kw["name"]
        elif len(args) == 1:
            name = args[0]
        else:
            name = "bonnie"

        logging.Logger.__init__(self, name)

        plaintextformatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")

        if not self.fork:
            self.console_stdout = logging.StreamHandler(sys.stdout)
            self.console_stdout.setFormatter(plaintextformatter)

            self.addHandler(self.console_stdout)

        if kw.has_key("logfile"):
            self.logfile = kw["logfile"]
        elif self.logfile is None:
            self.logfile = "/var/log/bonnie/bonnie.log"

        self.setLevel(self.loglevel)

        # Make sure (read: attempt to change) the permissions
        try:
            (ruid, euid, suid) = os.getresuid()
            (rgid, egid, sgid) = os.getresgid()
        except AttributeError, errmsg:
            ruid = os.getuid()
            rgid = os.getgid()
Example #12
0
def initialize(config, LOG: Log):
    """ Setup the user cache."""
    (_x, euid, _y) = os.getresuid()
    config['uftpd.effective_uid'] = euid
    if euid == 0:
        LOG.info(
            "Running privileged, will launch sessions as the current user.")
        config['uftpd.switch_uid'] = True
    else:
        LOG.info("Running unprivileged")
        config['uftpd.switch_uid'] = False

    if config.get('uftpd.enforce_os_gids', True):
        LOG.info(
            "Groups of the user will be limited to those available for the "
            "Xlogin in the operating system.")
    else:
        LOG.info("UFTPD will be free to assign any groups for the Xlogin "
                 "regardless of the operating system settings.")

    cache_ttl = config.get('uftpd.userCacheTtl', 600)
    use_id = config.get('uftpd.use_id_to_resolve_gids', False)
    if use_id:
        LOG.info("Groups will be resolved via 'id -G <username>'")

    user_cache = UserCache.UserCache(cache_ttl, LOG, use_id)
    config['uftpd.user_cache'] = user_cache
Example #13
0
    def __init__(self, *args, **kw):
        if kw.has_key('name'):
            name = kw['name']
        elif len(args) == 1:
            name = args[0]
        else:
            name = 'pykolab'

        logging.Logger.__init__(self, name)

        plaintextformatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")

        if not self.fork:
            self.console_stdout = logging.StreamHandler(sys.stdout)
            self.console_stdout.setFormatter(plaintextformatter)

            self.addHandler(self.console_stdout)

        if kw.has_key('logfile'):
            self.logfile = kw['logfile']
        else:
            self.logfile = '/var/log/kolab/pykolab.log'

        # Make sure (read: attempt to change) the permissions
        try:
            (ruid, euid, suid) = os.getresuid()
            (rgid, egid, sgid) = os.getresgid()
        except AttributeError, errmsg:
            ruid = os.getuid()
            rgid = os.getgid()
Example #14
0
def _make_passphrase(length=None, save=False, file=None):
    """Create a passphrase and write it to a file that only the user can read.

    This is not very secure, and should not be relied upon for actual key
    passphrases.

    :param int length: The length in bytes of the string to generate.

    :param file file: The file to save the generated passphrase in. If not
        given, defaults to 'passphrase-<the real user id>-<seconds since
        epoch>' in the top-level directory.
    """
    if not length:
        length = 40

    passphrase = _make_random_string(length)

    if save:
        ruid, euid, suid = os.getresuid()
        gid = os.getgid()
        now = mktime(gmtime())

        if not file:
            filename = str('passphrase-%s-%s' % uid, now)
            file = os.path.join(_repo, filename)

        with open(file, 'a') as fh:
            fh.write(passphrase)
            fh.flush()
            fh.close()
            os.chmod(file, 0600)
            os.chown(file, ruid, gid)

        log.warn("Generated passphrase saved to %s" % file)
    return passphrase
Example #15
0
 def test_getresuid(self):
     def f():
         a, b, c = os.getresuid()
         return a + b * 37 + c * 1291
     res = self.interpret(f, [])
     a, b, c = os.getresuid()
     assert res == a + b * 37 + c * 1291
Example #16
0
 def test_getresuid(self):
     def f():
         a, b, c = os.getresuid()
         return a + b * 37 + c * 1291
     res = self.interpret(f, [])
     a, b, c = os.getresuid()
     assert res == a + b * 37 + c * 1291
Example #17
0
def printUser(USER):
    realUID, eUID, savedUID = os.getresuid()         # get current user
    if isinstance(USER, int):
        user = pwd.getpwuid(USER)
    else:
        user = pwd.getpwnam(USER)       # get RunAS user data
    data = """
                current realUID   : {}
                current eUID      : {}
                current savedUID  : {}

                        pw_name   : {}
                        pw_passwd : {}
                        pw_gecos  : {}
                        pw_uid    : {}
                        pw_gid    : {}
                        pw_dir    : {}
                        pw_shell  : {}
    """.format(
                realUID,
                eUID,
                savedUID,
                user.pw_name,
                user.pw_passwd,
                user.pw_gecos,
                user.pw_uid,
                user.pw_gid,
                user.pw_dir,
                user.pw_shell,
            )

    return data
Example #18
0
 def possible() -> bool:
     """Evaluates if the privileges elevation is possible by doing a
     RES{U,G}ID flip over."""
     resuid = os.getresuid()
     resgid = os.getresgid()
     return ((resuid[2], resgid[2]) == (0, 0) and resuid[0] != 0
             and resuid[1] != 0 and resgid[0] != 0 and resgid[0] != 0)
Example #19
0
def initialize(config, LOG):
    """ Store initial values for UID/GID, and setup the user cache."""
    (_, euid, _) = os.getresuid()
    (_, egid, _) = os.getresgid()
    # store effective uid/gid, we'll switch back to these after every action
    config['tsi.effective_uid'] = euid
    config['tsi.effective_gid'] = egid

    if euid == 0:
        LOG.info("Running privileged [%s : %s], will execute "
                 "commands as the Xlogin" % (euid, egid))
        config['tsi.switch_uid'] = True
    else:
        LOG.info("Running unprivileged")
        config['tsi.switch_uid'] = False

    if config['tsi.enforce_os_gids']:
        LOG.info(
            "Groups of the user will be limited to those available for the "
            "Xlogin in the operating system.")
    else:
        LOG.info("XNJS will be free to assign any groups for the Xlogin "
                 "regardless of the operating system settings.")

    cache_ttl = config.get('tsi.userCacheTtl', 600)
    use_id = config['tsi.use_id_to_resolve_gids']
    if use_id:
        LOG.info("Groups will be resolved via 'id -G <username>")

    user_cache = UserCache.UserCache(cache_ttl, LOG, use_id)
    config['tsi.user_cache'] = user_cache
Example #20
0
 def __exit__(self, exc_type: Optional[Type[BaseException]],
              exc_value: Optional[BaseException],
              traceback: Optional[TracebackType]) -> None:
     os.umask(self.current_mask)
     unprivileged_uid = os.getresuid()[2]  # retrieve saved-set-UID
     unprivileged_gid = os.getresgid()[2]  # retrieve saved-set-GID
     os.setresuid(unprivileged_uid, unprivileged_uid, 0)
     os.setresgid(unprivileged_gid, unprivileged_gid, 0)
Example #21
0
 def get_bitcoind(self):
     for pid in psutil.get_pid_list():
         # match process name
         if (psutil.Process(pid).name == self.bitcoind_command[0]):
             # match process real uid against this scripts ruid
             if (os.getresuid()[0] == psutil.Process(pid).uids[0]):
                 return psutil.Process(pid)
     return False
Example #22
0
def user(user_name):
    db.engine.dispose()
    uid = pwd.getpwnam(user_name).pw_uid
    os.seteuid(uid)
    yield user_name
    db.engine.dispose()
    ruid, euid, suid = os.getresuid()
    os.seteuid(suid)
Example #23
0
 def get_bitcoind(self):
     for pid in psutil.get_pid_list():
         # match process name
         if (psutil.Process(pid).name == self.bitcoind_command[0]):
             # match process real uid against this scripts ruid
             if (os.getresuid()[0] == psutil.Process(pid).uids[0]):
                 return psutil.Process(pid)
     return False
Example #24
0
def getresuid(space):
    """ getresuid() -> (ruid, euid, suid)

    Get tuple of the current process's real, effective, and saved user ids.
    """
    try:
        (ruid, euid, suid) = os.getresuid()
    except OSError, e:
        raise wrap_oserror(space, e)
Example #25
0
def test_uids() -> None:
    proc = pypsutil.Process()

    if hasattr(os, "getresuid"):
        assert proc.uids() == os.getresuid()  # pylint: disable=no-member
    else:
        ruid, euid, _ = proc.uids()
        assert ruid == os.getuid()
        assert euid == os.geteuid()
Example #26
0
def ensure_directory(_dir, _user='******', _group='root'):
    if not os.path.isdir(_dir):
        os.makedirs(_dir)

    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(_group)

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

                    sys.exit(1)

                # Set real and effective group if not the same as current.
                if not group_gid == rgid:
                    os.chown(_dir, -1, 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(_user)

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

                    sys.exit(1)


                # Set real and effective user if not the same as current.
                if not user_uid == ruid:
                    os.chown(_dir, user_uid, -1)
Example #27
0
def getresuid(space):
    """ getresuid() -> (ruid, euid, suid)

    Get tuple of the current process's real, effective, and saved user ids.
    """
    try:
        (ruid, euid, suid) = os.getresuid()
    except OSError, e:
        raise wrap_oserror(space, e)
Example #28
0
def as_effective_user_from_path(path):
    stat = os.stat(path)
    os.setegid(stat.st_gid)
    os.seteuid(stat.st_uid)
    try:
        yield
    finally:
        os.seteuid(os.getresuid()[0])
        os.setegid(os.getresgid()[0])
Example #29
0
 def restore_user_group(self):
     try:
         (ruid, euid, suid) = os.getresuid()
         (rgid, egid, sgid) = os.getresgid()
         os.setresuid(suid, suid, suid)
         os.setresgid(sgid, sgid, sgid)
     except Exception, e:
         log.error("Error: %s" % e)
         exit(1)
Example #30
0
 def __init__(self, restore_to_root, saveenv):
     self.u = os.getresuid()
     self.g = os.getresgid()
     self.groups = os.getgroups()
     self.to_root = restore_to_root
     if saveenv:
         self.env = {k: os.getenv(k, None) for k in ("LOGNAME", "USER", "USERNAME", "HOME")}
     else:
         self.env = {}
Example #31
0
def is_superuser():
    """ Tests if a user has superuser privileges"""
    if sys.version > "2.7":
        for uid in os.getresuid():
            if uid == 0:
                return True
    else:
        if os.getuid() == 0 or os.getegid() == 0:
            return True
    return False
Example #32
0
 def _checked_setresuid(self, ruid, euid, suid):
     os.setresuid(ruid, euid, suid)
     if os.getresuid() != (ruid, euid, suid):
         try:
             raise SystemExit('PANIC: setresuid failed')
         except SystemExit as e:
             # Print stack trace
             logger.exception(e)
             # Force exit
             exit(1)
Example #33
0
def dump_process_info():
    ruid, euid, suid = os.getresuid()
    logging.info('User IDs:')
    logging.info('\tReal: %d', ruid)
    logging.info('\tEffective: %d', euid)
    logging.info('\tSaved: %d', suid)
    rgid, egid, sgid = os.getresgid()
    logging.info('Group IDs:')
    logging.info('\tReal: %d', rgid)
    logging.info('\tEffective: %d', egid)
    logging.info('\tSaved: %d', sgid)
 def test_uids(self):
     p = psutil.Process(os.getpid())
     real, effective, saved = p.uids
     # os.getuid() refers to "real" uid
     self.assertEqual(real, os.getuid())
     # os.geteuid() refers to "effective" uid
     self.assertEqual(effective, os.geteuid())
     # no such thing as os.getsuid() ("saved" uid), but starting
     # from python 2.7 we have os.getresuid()[2]
     if hasattr(os, "getresuid"):
         self.assertEqual(saved, os.getresuid()[2])
Example #35
0
 def test_uids(self):
     p = psutil.Process(os.getpid())
     real, effective, saved = p.uids
     # os.getuid() refers to "real" uid
     self.assertEqual(real, os.getuid())
     # os.geteuid() refers to "effective" uid
     self.assertEqual(effective, os.geteuid())
     # no such thing as os.getsuid() ("saved" uid), but starting
     # from python 2.7 we have os.getresuid()[2]
     if hasattr(os, "getresuid"):
         self.assertEqual(saved, os.getresuid()[2])
Example #36
0
def as_critic_system_user():
    saved_cwd = os.getcwd()
    os.chdir(tempfile.gettempdir())
    os.setegid(installation.system.gid)
    os.seteuid(installation.system.uid)
    try:
        yield
    finally:
        os.seteuid(os.getresuid()[0])
        os.setegid(os.getresgid()[0])
        os.chdir(saved_cwd)
Example #37
0
def regain_privileges_save():
    """Recover our real UID/GID after calling drop_privileges_save."""
    assert _dropped_privileges is not None and _dropped_privileges > 0
    # We need to call os.setresuid and os.setresgid twice to avoid
    # permission issues when calling os.setgroups (see LP: #646827).
    _, euid, _ = os.getresuid()
    _, egid, _ = os.getresgid()
    os.setresuid(0, 0, 0)
    os.setresgid(0, 0, 0)
    os.setgroups([])
    os.setresgid(-1, egid, -1)
    os.setresuid(-1, euid, -1)
Example #38
0
def test_setfsuid_failure() -> None:
    bad_uid = max(os.getresuid()) + 1

    orig_state = False
    if pyprctl.cap_effective.setuid:
        pyprctl.cap_effective.setuid = False
        orig_state = True

    with pytest.raises(PermissionError):
        pyprctl.setfsuid(bad_uid)

    pyprctl.cap_effective.setuid = orig_state
def get_token(username):
    #print("[get_token] UID: ", os.getresuid(), "GID: ", os.getresgid())
    if os.getresuid()[0] != 0:  # If not root
        return None
    db = zoodb.cred_setup()
    if not db:
        return None
    cred = db.query(zoodb.Cred).get(username)
    if cred:
        return cred.token
    else:
        return None
Example #40
0
def check_res_ids():
    ruid, euid, suid = os.getresuid()
    if not ruid == euid == suid:
        raise QuickenError(
            f"real uid ({ruid}), effective uid ({euid}), and saved uid ({suid})"
            " must be the same")

    rgid, egid, sgid = os.getresgid()
    if not rgid == egid == sgid:
        raise QuickenError(
            f"real gid ({rgid}), effective gid ({egid}), and saved gid ({sgid})"
            " must be the same")
Example #41
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)
Example #42
0
    def __init__(self, is_suid, via_sudo, signal_mode=None, uids=None, gids=None, groups=None, user_pwent=None):
        self.is_suid = is_suid
        self.suid_via_sudo = via_sudo
        self.signal_mode = signal_mode
        self.uid, self.euid, self.suid = uids  if uids       is not None else os.getresuid()
        self.gid, self.egid, self.sgid = gids  if gids       is not None else os.getresgid()
        self.groups = groups                   if groups     is not None else os.getgroups()
        self.user_pwent = user_pwent           if user_pwent is not None else pwd.getpwuid(self.uid)
        self.root_pwent = pwd.getpwuid(self.euid)

        assert (self.user_pwent.pw_uid == self.uid)
        assert (self.root_pwent.pw_uid == self.euid)
        return
Example #43
0
def as_critic_system_user():
    if installation.is_quick_start:
        yield
        return

    saved_cwd = os.getcwd()
    os.chdir(tempfile.gettempdir())
    os.setegid(installation.system.gid)
    os.seteuid(installation.system.uid)
    try:
        yield
    finally:
        os.seteuid(os.getresuid()[0])
        os.setegid(os.getresgid()[0])
        os.chdir(saved_cwd)
Example #44
0
def soft_info(req):
    if not wapp.start(req, '__soft-info', '__soft-info', acclvl='ADMIN'):
        return wapp.error_page()
    tmpl_data = wapp.tmpl_data()

    tmpl_data['version'] = wapp.version
    tmpl_data['settings'] = wapp.conf.export()
    tmpl_data['django_version'] = django.get_version()
    tmpl_data['python_version'] = '{}.{}.{}'.format(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
    tmpl_data['mysql_server_version'] = wapp.db.server_version()
    tmpl_data['mysql_server_charset'] = wapp.db.server_charset()
    tmpl_data['mysql_conn_version'] = wapp.db.conn_version()
    tmpl_data['os_user_uid'] = os.getresuid()
    tmpl_data['os_user_gid'] = os.getresgid()
    tmpl_data['uwsgi_version'] = req.META.get('uwsgi.version', None)

    return render(req, 'soft-info.html', wapp.end(tmpl_data))
Example #45
0
def setUID_OK(gv, userName=None, uid=None, exitOnError=False):
    global TAByel, TABerr, TAB

    logger = gv.LN.logger.setLogger(gv, package=__name__)
    calledBy = gv.LN.sys.calledBy
    logger.info('entered - [called by:%s]' % (calledBy(1)))

    TAByel      = gv.LN.cYELLOW + ' '*8
    TABerr      = gv.LN.cERROR + ' '*8
    TAB         = gv.LN.cGREEN + ' '*8


    ruid, euid, suid  = os.getresuid()   # real, effective, and saved user ids

        # ------------------------------
        # - catturiamo lo UID
        # ------------------------------
    if userName != None:
        reqUID = pwd.getpwnam(userName).pw_uid
    elif uid != None:
        reqUID = uid
    else:
        reqUID = ruid                           # preleva il REAL-UID
        # reqUID = suid                           # preleva il SAVED-UID


    logger.info('')
    msg = 'Requested setUID for username:[{}:{}]'.format(pwd.getpwuid(reqUID).pw_name, reqUID)
    logger.info(TAB + msg)
    msg = 'currUser:[{}:{}] ruid:{} euid:{} suid:{} '.format(pwd.getpwuid(os.getuid()).pw_name, os.geteuid(), ruid, euid, suid)
    logger.info(TAB + msg)

        # --------------------------------------------
        # - Se il current euid!=0  non possiamo
        # - fare il setUID per un altro user
        # - Switch temporaneo su root per permetterlo
        # ---------------------------------------------
    rCode = 0

    if euid != 0 and euid != reqUID:
        rCode = processSetUid(gv, 0, exitOnError)

    if rCode == 0:
        rCode = processSetUid(gv, reqUID, exitOnError)

    return rCode
Example #46
0
def chOwn(gv, fileName, user_group=None, UID=-1, GID=-1):
    logger = gv.LN.logger.setLogger(gv, package=__name__)

    TAByel      = gv.LN.cYELLOW + ' '*8
    TABerr      = gv.LN.cERROR + ' '*8

    if user_group:
        if user_group == '-:-': return 0
        userName, groupName = user_group.split(':')
        stat = os.stat(fileName)
        UID  = pwd.getpwnam(userName).pw_uid
        GID  = grp.getgrnam(groupName).gr_gid

    msg = "Before1 {} - chown {} {} {}".format(os.geteuid(), fileName, UID, GID)
    # print (msg)
    realUID, eUID, savedUID = os.getresuid()         # SAVE dello user corrente
    # msg = "Before2 {} - chown {} {} {}".format(os.geteuid(), fileName, UID, GID)
    # print (msg)
    rCode = 1
    errMsg = ''
    try:
        '''
        savedUID = os.geteuid()         # SAVE dello user corrente
        os.seteuid(os.getuid())         # impostiamo il REAL_USER
        os.chown(fileName, UID, GID)    # mantenere l'ordine GID-UID
        os.seteuid(savedUID)            # ripristiniamo lo user
        '''

        os.seteuid(realUID)         # impostiamo il REAL_USER
        os.chown(fileName, UID, GID)    # mantenere l'ordine GID-UID
        print('OK')
        rCode = 0

    except PermissionError as why:
        errMsg = "chown: - Permission Error {}".format(str(why))
        print(TABerr + errMsg)

    except:
        errMsg = "Unexpected ERROR: {}".format(msg, str(sys.exc_info()[0]))
        print(TABerr + errMsg)

    # finally:
    #     print('ERR3', rCode)

    os.seteuid(savedUID)            # ripristiniamo lo user
    return rCode
Example #47
0
def get_current_os_user():
    """
    Find the real user who runs the current process. Return a tuple of uid, username, homedir.
    :rtype: (int, str, str, int)
    """
    user_name = os.getenv('SUDO_USER')
    if not user_name:
        user_name = os.getenv('USER')
    if user_name:
        pw = getpwnam(user_name)
        user_uid = pw.pw_uid
    else:
        # If cannot find the user, use ruid instead.
        user_uid = os.getresuid()[0]
        pw = getpwuid(user_uid)
        user_name = pw.pw_name
    user_gid = pw.pw_gid
    user_home = pw.pw_dir
    return user_uid, user_name, user_home, user_gid
Example #48
0
    def _find_agent(cls):
        """Discover if a gpg-agent process for the current euid is running.

        If there is a matching gpg-agent process, set a :class:`psutil.Process`
        instance containing the gpg-agent process' information to
        :attr:`GPG._agent_proc`.

        :returns: True if there exists a gpg-agent process running under the
                  same effective user ID as that of this program. Otherwise,
                  returns None.
        """
        identity = os.getresuid()
        for proc in psutil.process_iter():
            if (proc.name == "gpg-agent") and proc.is_running:
                log.debug("Found gpg-agent process with pid %d" % proc.pid)
                if proc.uids == identity:
                    log.debug("Effective UIDs of this process and gpg-agent match")
                    setattr(cls, "_agent_proc", proc)
                    return True
Example #49
0
def demote(user_uid, user_gid):
    realUID, eUID, savedUID = os.getresuid()         # SAVE dello user corrente
    report_ids("Before run [{}]".format(pwd.getpwuid(eUID)))
    report_ids("executing setUID with user [{}]".format(pwd.getpwuid(realUID)))


        # -------------------------------------------------------------
        # Set user to realUID (qello del login) per fare il setUID
        # Il tutto dovrebbe rimanere nello scope del processo perch*
        # sotto la funzione che segue.
        # -------------------------------------------------------------
    def result():
        report_ids("STARTING demotion[{}]".format(pwd.getpwuid(eUID)))
        os.seteuid(realUID)  # Per abilitare a dare il comando
        os.setgid(user_gid)
        os.setuid(user_uid)
        report_ids("FINISHED demotion[{}]".format(pwd.getpwuid(eUID)))

    report_ids("After  run [{}]".format(pwd.getpwuid(eUID)))
    return result
Example #50
0
    def set_user_group(self, user, group, real=False):
        try:
            (ruid, euid, suid) = os.getresuid()
            (rgid, egid, sgid) = os.getresgid()

            if group:
                gid = grp.getgrnam(group)
                egid = gid.gr_gid
                if real:
                    os.setresgid(egid, egid,rgid)
                else:
                    os.setresgid(rgid, egid, rgid)
                
            if user:
                uid = pwd.getpwnam(user)
                euid = uid.pw_uid
                if real:
                    os.setresuid(euid, euid, ruid)
                else:
                    os.setresuid(ruid, euid, ruid)
        except Exception, e:
            log.error("Error: %s" % e)
            exit(1)
Example #51
0
def SwitchRoot():
    if os.getresuid().suid == 0:
        os.setuid(0)
        os.setgid(0)
Example #52
0
 def test_os_setresuid(self):
     os = self.posix
     a, b, c = os.getresuid()
     os.setresuid(a, b, c)
Example #53
0
 def test_os_getresuid(self):
     os = self.posix
     res = os.getresuid()
     assert len(res) == 3
Example #54
0
    def __init__(self, *args, **kw):
        if kw.has_key('name'):
            name = kw['name']
        elif len(args) == 1:
            name = args[0]
        else:
            name = 'pykolab'

        logging.Logger.__init__(self, name)

        plaintextformatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")

        if not self.fork:
            self.console_stdout = logging.StreamHandler(sys.stdout)
            self.console_stdout.setFormatter(plaintextformatter)

            self.addHandler(self.console_stdout)

        if kw.has_key('logfile'):
            self.logfile = kw['logfile']
        else:
            self.logfile = '/var/log/kolab/pykolab.log'

        group_gid = 0
        user_uid = 0

        # Make sure (read: attempt to change) the permissions
        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(self.process_groupname)

                    except KeyError, errmsg:
                        group_name = False

                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(self.process_username)

                    except KeyError, errmsg:
                        user_name = False
Example #55
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)
Example #56
0
 def is_root(self):
     # surprisingly, even when running under sudo we have all 3 set to 0
     r, e, s = os.getresuid()
     is_root = r==0 and e==0 and s==0
     return is_root
import os, pwd, grp

#Throws OSError exception (it will be thrown when the process is not allowed
#to switch its effective UID or GID):
def drop_privileges():
    if os.getuid() != 0:
        # We're not root so, like, whatever dude
        return

    # Get the uid/gid from the name
    user_name = os.getenv("SUDO_USER")
    pwnam = pwd.getpwnam(user_name)

    # Remove group privileges
    os.setgroups([])

    # Try setting the new uid/gid
    os.setgid(pwnam.pw_gid)
    os.setuid(pwnam.pw_uid)

    # Ensure a very conservative umask
    old_umask = os.umask(0o22)


#Test by running...
#./drop_privileges
#sudo ./drop_privileges
if __name__ == '__main__':
    print(os.getresuid())
    drop_privileges()
    print(os.getresuid())
Example #58
0
def _logOpen(cmd_name):
    log.log_open("tsadm"+__RUN_MODE+"cli")
    log.inf("start: ", cmd_name)
    log.inf("user: ", os.getresuid(), os.getresgid())