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()
def test_getresgid(self): def f(): a, b, c = os.getresgid() return a + b * 37 + c * 1291 res = self.interpret(f, []) a, b, c = os.getresgid() assert res == a + b * 37 + c * 1291
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)
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)
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()
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()
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()
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.
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
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
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)
def test_gids() -> None: proc = pypsutil.Process() if hasattr(os, "getresgid"): assert proc.gids() == os.getresgid() # pylint: disable=no-member else: rgid, egid, _ = proc.gids() assert rgid == os.getgid() assert egid == os.getegid()
def getresgid(space): """ getresgid() -> (rgid, egid, sgid) Get tuple of the current process's real, effective, and saved group ids. """ try: (rgid, egid, sgid) = os.getresgid() except OSError, e: raise wrap_oserror(space, e)
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)
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])
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 = {}
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)
def test_gids(self): p = psutil.Process(os.getpid()) real, effective, saved = p.gids # os.getuid() refers to "real" uid self.assertEqual(real, os.getgid()) # os.geteuid() refers to "effective" uid self.assertEqual(effective, os.getegid()) # no such thing as os.getsuid() ("saved" uid), but starting # from python 2.7 we have os.getresgid()[2] if hasattr(os, "getresuid"): self.assertEqual(saved, os.getresgid()[2])
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)
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 checkpath(self): if not os.path.exists(self.path): if os.stat(self.path).st_gid not in os.getresgid(): raise RuntimeError("{0} This user doesn't have access".format( self.compose_name)) else: raise RuntimeError("{0} does not exist".format( self.compose_name)) elif not os.path.isdir(self.path): raise RuntimeError("{0} is not a directory".format( self.compose_name))
def test_setfsgid_failure() -> None: bad_gid = max(os.getresgid()) + 1 orig_state = False if pyprctl.cap_effective.setgid: pyprctl.cap_effective.setgid = False orig_state = True with pytest.raises(PermissionError): pyprctl.setfsgid(bad_gid) pyprctl.cap_effective.setgid = orig_state
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)
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")
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)
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
def _drop_privileges(self, username): if os.geteuid() != 0: return pw = pwd.getpwnam(username) os.setgroups( [g.gr_gid for g in grp.getgrall() if username in g.gr_mem]) # Portability note: this assumes that we have [gs]etres[gu]id, which # is true on Linux but not necessarily elsewhere. If you need to # support something else, there are reasonably standard alternatives # involving other similar calls; see e.g. gnulib/lib/idpriv-drop.c. os.setresgid(pw.pw_gid, pw.pw_gid, pw.pw_gid) os.setresuid(pw.pw_uid, pw.pw_uid, pw.pw_uid) assert os.getresuid() == (pw.pw_uid, pw.pw_uid, pw.pw_uid) assert os.getresgid() == (pw.pw_gid, pw.pw_gid, pw.pw_gid) os.umask(0o022)
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)
def inner(*args, **kwargs): current_proc = multiprocessing.current_process() logger.debug( "Changing permissions for process: {0} with PID: {1!s}".format( current_proc.name, current_proc.pid)) if sys.version > "2.7": ruid, euid, suid = os.getresuid() rgid, egid, sgid = os.getresgid() logger.debug( "UIDs before are: (ruid) {0}, (euid) {1}, (suid) {2}".format( ruid, euid, suid)) logger.debug( "GIDs before are: (rgid) {0}, (egid) {1}, (sgid) {2}".format( rgid, egid, sgid)) logger.debug("Setting all UIDs/GIDs to 0") # Make the actual permissions changes os.setresuid(0, 0, 0) os.setresgid(0, 0, 0) try: retval = func(*args, **kwargs) finally: # Restore original permissions os.setresgid(rgid, egid, sgid) os.setresuid(ruid, euid, suid) else: ruid = os.getuid() euid = os.geteuid() rgid = os.getgid() egid = os.getegid() logger.debug("UIDs before are: (ruid) {0}, (euid) {1}".format( ruid, euid)) logger.debug("GIDs before are: (rgid) {0}, (egid) {1}".format( rgid, egid)) logger.debug("Setting all UIDs/GIDs to 0") # Make the actual permissions changes os.setreuid(0, 0) os.setregid(0, 0) try: logger.debug("Setting all UIDs/GIDs to 0") retval = func(*args, **kwargs) finally: # Restore original permissions os.setregid(rgid, egid) os.setreuid(ruid, euid) return retval
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))
def log_sysinfo(app: Flask, config: Config): app.logger.info("ZMQ:") app.logger.info(" zmq version: %s", zmq.zmq_version()) app.logger.info(" pyzmq version: %s", zmq.pyzmq_version()) app.logger.info(" zmq includes: %s", zmq.get_includes()) app.logger.info(" zmq library dirs: %s", zmq.get_library_dirs()) app.logger.info(" has: %s", [c for c in ZMQ_CAPABILITIES if zmq.has(c)]) app.logger.info("socket:") app.logger.info(" fqdn: %s", socket.getfqdn()) app.logger.info(" has_ipv6: %s", socket.has_ipv6) app.logger.info(" hostname: %s", socket.gethostname()) app.logger.info(" interfaces: %s", [i[1] for i in socket.if_nameindex()]) app.logger.info("os:") app.logger.info(" ctermid: %s", os.ctermid()) app.logger.info(" cwd: %s", os.getcwd()) app.logger.info(" groups: %s", os.getgroups()) app.logger.info(" pgid: %d", os.getpgid(0)) app.logger.info(" pgrp: %d", os.getpgrp()) app.logger.info(" pid: %d", os.getpid()) app.logger.info(" ppid: %d", os.getppid()) app.logger.info(" priority_process: %d", os.getpriority(os.PRIO_PROCESS, 0)) app.logger.info(" priority_pgrp: %d", os.getpriority(os.PRIO_PGRP, 0)) app.logger.info(" priority_user: %d", os.getpriority(os.PRIO_USER, 0)) app.logger.info(" resuid: ruid=%d, euid=%d, suid=%d", *os.getresuid()) app.logger.info(" resgid: rgid=%d, egid=%d, sgid=%d", *os.getresgid()) app.logger.info(" sid: %d", os.getsid(0)) app.logger.info(" supports_bytes_environ: %s", os.supports_bytes_environ) app.logger.info(" uname: %s", os.uname()) app.logger.info(" cpu_count: %d", os.cpu_count()) app.logger.info("platform:") app.logger.info(" %s", platform.platform()) app.logger.info(" python_build: %s", platform.python_build()) app.logger.info(" python_compiler: %s", platform.python_compiler()) app.logger.info(" python_branch: %s", platform.python_branch()) app.logger.info(" python_implementation: %s", platform.python_implementation()) app.logger.info(" python_revision: %s", platform.python_revision()) app.logger.info(" python_version: %s", platform.python_version()) app.logger.info("getpass:"******" user: %s", getpass.getuser())
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)
import os import platform import sys print(sys.gettrace()) print(os.getcwd(), os.get_blocking(1), os.get_exec_path(), os.get_inheritable(1)) print(os.get_terminal_size()) print("The code is running from : " + os.getcwd()) print("The credention " + str(os.geteuid())) print("The os use groups are " + str(os.getgroups())) print("The average system load information " + str(os.getloadavg())) print("Get os login " + os.getlogin() + " \n The p_id: " + str(os.getpgid(1)) + "\n the p_group: " + str(os.getpgrp())) print("\n os p_id :" + str(os.getpid()) + "\n os_pp_id :" + str(os.getppid())) print("\nvgroup id" + str(os.getresgid()) + "\nuser_id " + str(os.getresuid())) print("\n " + str(os.getsid(1)) + "\n" + str(os.getuid())) print("cpu count :" + str(os.cpu_count())) print("\n\n\n \t\t<--- SYSTEM INFORMATION ---> \n\n\n") print("" + str(platform.uname())) print("With processor " + platform.processor() + "The machine " + platform.machine() + " run in " + platform.node() + "node is connected in " + str(platform.mac_ver())) print("" + str(platform.java_ver())) print("python version " + str(platform.python_version_tuple()))
def test_os_setresgid(self): os = self.posix a, b, c = os.getresgid() os.setresgid(a, b, c)
def test_os_getresgid(self): os = self.posix res = os.getresgid() assert len(res) == 3
def dropPriviledge(): assert os.geteuid() == 0 and os.getegid() == 0 os.setegid(os.getresgid()[2]) os.seteuid(os.getresuid()[2])
and so on as you while see when running this that these are some good functions to have for directory manipulations and so on """ import os OS_name = os.name print OS_name print os.environ print os.getcwd() if OS_name == 'posix': print ctermid() print getegid() print geteuid() print getgid() print os.getgroups() print os.getlogin() print os.getpgrp() print os.getppid() print os.getresgid() print os.getresuid() print os.getuid() print os.getpid() print os.sep print os.altsep print os.defpath print os.urandom(10)
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)
def _logOpen(cmd_name): log.log_open("tsadm"+__RUN_MODE+"cli") log.inf("start: ", cmd_name) log.inf("user: ", os.getresuid(), os.getresgid())
def f(): a, b, c = os.getresgid() a = (a + 1) - 1 os.setresgid(a, b, c)
def handle_err(e): print "Error handling directory" print e print '-'* 10 print 'System info' systeminfo= os.uname() print systeminfo print 'Environment' env= os.environ print env print 'UID/GID' euid= os.getresuid() egid= os.getresgid() print euid, egid print 'PID/PPID' print os.getpid() print os.getppid() print 'Files/Directories' print os.getcwd() os.chdir('/') print os.getcwd() print os.listdir('/data') print "Creating a file" f1= open('/tmp/test1', 'w') print "Deleting file now" os.unlink('/tmp/test1')
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
#! /usr/bin/python from __future__ import print_function import os (rgid, egid, sgid) = os.getresgid() print("R-GID=",rgid," E-GID=",egid," S-GID=",sgid)) os.setresgid(-1, egid, rgid) (rgid, egid, sgid) = os.getresgid() print("R-GID=",rgid," E-GID=",egid," S-GID=",sgid)) os.setresgid(-1, sgid, -1) (rgid, egid, sgid) = os.getresgid() print("R-GID=",rgid," E-GID=",egid," S-GID=",sgid))
def f(): a, b, c = os.getresgid() return a + b * 37 + c * 1291
def runProgram(path, lang, timecap, memlimit, uids, block_, rres, eloop): global runPid, timeOut # runs program at path and changes context to /run and supplies input.txt and outputs to output.txt and error.txt # returns status (0=self-ended, 1=terminated), runtime, program output, and error #override uids to 'nobody' uids = 65534 if not os.geteuid() == 0: print("need euid 0") quit() timecap = int(timecap) if timecap < 1: timecap = 1 if timecap > 30: timecap = 30 startms = int(time.time() * 1000.0) pid = -1 timeOut = [False] runPid = -1 #def handleSignal(a, b): #print("IN HANDLE SIGNAL, pid:",str(pid)) #tmppid, tmpstatus, rusage = os.wait4(pid, 0) #data.append(rusage) #print(rusage) #print(timedOut) #if timedOut[0]: # data.append(1) #else: # signal.alarm(0) # data.append(0) #signal.signal(signal.SIGCHLD, handleSignal) pid = os.fork() #print("b",pid) if pid == 0: # WARNING DO NOT RETURN HERE. WILL CAUSE GLITCHES. if not os.geteuid() == 0: print( "No root permissions during pipe setup, quitting to preserve security" ) quit() subprocess.call("touch run/output.txt", shell=True) subprocess.call("touch run/error.txt", shell=True) os.dup2(os.open('run/input.txt', os.O_RDONLY), 0) os.dup2(os.open('run/output.txt', os.O_RDWR | os.O_CREAT | os.O_TRUNC), 1) os.dup2(os.open('run/error.txt', os.O_RDWR | os.O_CREAT | os.O_TRUNC), 2) if not os.geteuid() == 0: print( "No root permissions during security setup, quitting to preserve security" ) quit() os.setresgid(uids, uids, uids) os.setresuid(uids, uids, uids) c = os.getresuid() + os.getresgid() for cur in c: if cur != uids: print( "User id set wrong, quitting to preserve security (dump:", c, ")") quit() if os.geteuid() == 0: print( "Effective user id still root, quitting to preserve security") quit() if lang == "cpp": os.execl(path, path[path.find('/') + 1:]) elif lang == "py": os.execl("/usr/bin/python3", "/usr/bin/python3", path) elif lang == "java": os.execl("/usr/bin/java", "/usr/bin/java", "-cp", "compile/", path) elif lang == "c": os.execl(path, path[path.find('/') + 1:]) else: print("LANG ERROR", lang) quit() else: runPid = pid #signal.sigwait([signal.SIGCHLD]) tmppid, tmpstatus, rusage = os.wait4(pid, 0) #print(rusage) #print(timeOut) #print(os.path.isdir('/proc/{}'.format(pid))) #print("Fetching output") ols = open("run/output.txt").read(1000000) if len(ols) == 1000000: print("Capacity reached.") ols += "\r\nOutput limited to only 1,000,000 bytes." #print("Fetching error") els = open("run/error.txt").read(1000000) if len(els) == 1000000: print("Capacity reached.") els += "\r\nError limited to only 1,000,000 bytes." if timeOut[0] == False: signal.alarm(0) if rusage.ru_maxrss > memlimit * 1000: rres += [2, int(timecap * 1000.0), ols, els] else: rres += [0, int(timecap * 1000.0), ols, els] elif timeOut[0] == True: #print("Returning timeOut") rres += [1, int(timecap * 1000.0), ols, els] #print("Releasing block...") eloop.call_soon_threadsafe(block_.set_result, (None))