def testGetGroupMap(self): """Verify we build a correct group map from nss calls.""" foo = ("foo", "*", 10, []) bar = ("bar", "*", 20, ["foo", "bar"]) self.mox.StubOutWithMock(grp, "getgrall") grp.getgrall().AndReturn([foo, bar]) entry1 = group.GroupMapEntry() entry1.name = "foo" entry1.passwd = "*" entry1.gid = 10 entry1.members = [""] entry2 = group.GroupMapEntry() entry2.name = "bar" entry2.passwd = "*" entry2.gid = 20 entry2.members = ["foo", "bar"] self.mox.ReplayAll() group_map = nss.GetGroupMap() self.assertTrue(isinstance(group_map, group.GroupMap)) self.assertEquals(len(group_map), 2) self.assertTrue(group_map.Exists(entry1)) self.assertTrue(group_map.Exists(entry2))
def listgroup(fullinfo=True): if fullinfo: groups = grp.getgrall() for i, group in enumerate(groups): groups[i] = dict((name, getattr(group, name)) for name in dir(group) if not name.startswith("__")) else: groups = [gr.gr_name for gr in grp.getgrall()] return groups
def getGroups(user=False): grouplist = [] if not user: for group in grp.getgrall(): grouplist.append(group[0]) else: for group in grp.getgrall(): if user in group[3]: grouplist.append(group[0]) return grouplist
def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' ugrp = set() # Add the primary user's group try: ugrp.add(grp.getgrgid(pwd.getpwnam(name).pw_gid).gr_name) except KeyError: # The user's applied default group is undefined on the system, so # it does not exist pass # If we already grabbed the group list, it's overkill to grab it again if 'user.getgrall' in __context__: groups = __context__['user.getgrall'] else: groups = grp.getgrall() __context__['user.getgrall'] = groups # Now, all other groups the user belongs to for group in groups: if name in group.gr_mem: ugrp.add(group.gr_name) return sorted(list(ugrp))
def auth_user(pam_config, username, password): """ Authenticate user with PAM. """ LOG.debug('Authenticating user with PAM.') auth = pam.pam() if auth.authenticate(username, password): allowed_users = pam_config.get("users") \ or [] allowed_group = pam_config.get("groups")\ or [] if len(allowed_users) == 0 and len(allowed_group) == 0: # If no filters are set, only authentication is needed. return True else: if username in allowed_users: # The user is allowed by username. return True # Otherwise, check group memeberships. If any of the user's # groups are an allowed groupl, the user is allowed. groups = [g.gr_name for g in grp.getgrall() if username in g.gr_mem] gid = pwd.getpwnam(username).pw_gid groups.append(grp.getgrgid(gid).gr_name) return not set(groups).isdisjoint( set(pam_config.get("groups"))) return False
def verify_files(files, user): ''' Verify that the named files exist and are owned by the named user ''' if 'os' in os.environ: if os.environ['os'].startswith('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: err = ('Failed to prepare the Salt environment for user ' '{0}. The user is not available.\n').format(user) sys.stderr.write(err) sys.exit(2) for fn_ in files: dirname = os.path.dirname(fn_) if not os.path.isdir(dirname): os.makedirs(dirname) if not os.path.isfile(fn_): with salt.utils.fopen(fn_, 'w+') as fp_: fp_.write('') stats = os.stat(fn_) if not uid == stats.st_uid: try: os.chown(fn_, uid, -1) except OSError: pass return True
def demote(self, uid): try: username = pwd.getpwuid(uid).pw_name gid = pwd.getpwuid(uid).pw_gid except KeyError: username = None gid = uid if os.getuid() == uid: return else: if os.getuid() != 0: logging.warn('Running as a limited user, setuid() unavailable!') return logging.info( 'Worker %s is demoting to UID %s / GID %s...', os.getpid(), uid, gid ) groups = [ g.gr_gid for g in grp.getgrall() if username in g.gr_mem or g.gr_gid == gid ] os.setgroups(groups) os.setgid(gid) os.setuid(uid) logging.info( '...done, new EUID %s EGID %s', os.geteuid(), os.getegid() )
def set_user_setuid(username): """Return a preexec_fn for spawning a single-user server as a particular user. Returned preexec_fn will set uid/gid, and attempt to chdir to the target user's home directory. """ user = pwd.getpwnam(username) uid = user.pw_uid gid = user.pw_gid home = user.pw_dir gids = [ g.gr_gid for g in grp.getgrall() if username in g.gr_mem ] def preexec(): """Set uid/gid of current process Executed after fork but before exec by python. Also try to chdir to the user's home directory. """ os.setgid(gid) try: os.setgroups(gids) except Exception as e: print('Failed to set groups %s' % e, file=sys.stderr) os.setuid(uid) # start in the user's home dir _try_setcwd(home) return preexec
def __init__(self, category): if os.geteuid() != 0: self._current_user = os.getenv("USER") self._current_user = pwd.getpwuid(int(os.getenv("SUDO_UID", default=0))).pw_name for group_name in [g.gr_name for g in grp.getgrall() if self._current_user in g.gr_mem]: if group_name == self.ARDUINO_GROUP: self.was_in_arduino_group = True break else: self.was_in_arduino_group = False super().__init__(name="Arduino", description=_("The Arduino Software Distribution"), category=category, only_on_archs=['i386', 'amd64'], download_page='http://www.arduino.cc/en/Main/Software', dir_to_decompress_in_tarball='arduino-*', desktop_filename='arduino.desktop', packages_requirements=['openjdk-7-jdk', 'jayatana', 'gcc-avr', 'avr-libc'], need_root_access=not self.was_in_arduino_group) self.scraped_checksum_url = None self.scraped_download_url = None # This is needed later in several places. # The framework covers other cases, in combination with self.only_on_archs self.bits = '32' if platform.machine() == 'i686' else '64'
def change_uid(self): c_user = self.config.uid c_group = self.config.gid if os.getuid() == 0: cpw = pwd.getpwnam(c_user) c_uid = cpw.pw_uid if c_group: cgr = grp.getgrnam(c_group) c_gid = cgr.gr_gid else: c_gid = cpw.pw_gid c_groups = [] for item in grp.getgrall(): if c_user in item.gr_mem: c_groups.append(item.gr_gid) if c_gid not in c_groups: c_groups.append(c_gid) os.chown(self.config.datadir, c_uid, c_gid) os.chown(self.config.rundir, c_uid, c_gid) os.chown(self.config.pidfile, c_uid, c_gid) for root, _, filenames in os.walk(self.config.datadir): for filename in filenames: os.chown(os.path.join(root, filename), c_uid, c_gid) for root, _, filenames in os.walk(self.config.rundir): for filename in filenames: os.chown(os.path.join(root, filename), c_uid, c_gid) os.setgid(c_gid) os.setgroups(c_groups) os.setuid(c_uid)
def _get_non_member_group(self): """Get a group tuple that this user is not a member of.""" user_groups = set(os.getgroups()) for group in grp.getgrall(): if group.gr_gid not in user_groups: return group self.skipTest('no usable groups found')
def __init__ (self, username): super(GroupsDialog, self).__init__() try: self.set_modal(True) self.set_skip_taskbar_hint(True) self.set_skip_pager_hint(True) self.set_title("") self.set_default_size(200, 480) scrolled = Gtk.ScrolledWindow() viewport = Gtk.Viewport() vbox = Gtk.VBox() self.checkboxes = [] groups = sorted(grp.getgrall(), key=lambda x: x[0], reverse=False) for group in groups: checkbox = Gtk.CheckButton(group[0]) self.checkboxes.append(checkbox) vbox.add(checkbox) if username in group[3]: checkbox.set_active(True) viewport.add(vbox) scrolled.add(viewport) self.set_border_width(6) box = self.get_content_area() box.pack_start(scrolled, True, True, 0) self.show_all() self.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK, ) except Exception, detail: print detail
def load_groups(self): self.groups.clear() groups = sorted(grp.getgrall(), key=lambda x: x[0], reverse=False) for group in groups: (gr_name, gr_passwd, gr_gid, gr_mem) = group piter = self.groups.append(None, [gr_gid, gr_name]) self.groups_treeview.set_model(self.groups)
def is_in_group(group): """return if current user is in a group""" for group_name in [g.gr_name for g in grp.getgrall() if os.environ["USER"] in g.gr_mem]: print(group_name) if group_name == group: return True return False
def _ownership_update(self): """Update owner and group""" stat = self._provider.get_stat(self._path) self._combobox_owner.handler_block_by_func(self._ownership_changed) self._combobox_group.handler_block_by_func(self._ownership_changed) # remove old entries self._list_owner.clear() self._list_group.clear() # for local file system fill comboboxes with available user and group names if self._provider.is_local: for i, user in enumerate(pwd.getpwall()): self._list_owner.append((user.pw_name, user.pw_uid)) if user.pw_uid == stat.user_id: self._combobox_owner.set_active(i) for i, group in enumerate(grp.getgrall()): self._list_group.append((group.gr_name, group.gr_gid)) if group.gr_gid == stat.group_id: self._combobox_group.set_active(i) # for remote file systems simply set owner and group else: self._list_owner.append((stat.user_id, stat.user_id)) self._list_group.append((stat.group_id, stat.group_id)) self._combobox_owner.set_active(0) self._combobox_group.set_active(0) self._combobox_owner.handler_unblock_by_func(self._ownership_changed) self._combobox_group.handler_unblock_by_func(self._ownership_changed)
def user_login_auth(user): manifest = get_manifest() user_section = 'user_{}'.format(user) my_hostname = socket.gethostname() linux_groups_str = "" auth = False groups = manifest.get(user_section, 'groups').split(",") for group in groups: #loop over all cluster_groups user is part of group_name = group.strip() # remove white space hostnames = manifest.get('group_{}'.format(group_name), "hostnames").split(",") #get a list of servers they can access for pattern in hostnames: # loop over all the patterns of hostnames they can access if fnmatch.fnmatch(my_hostname, pattern) is True: # if the current host name matches a pattern linux_groups_str = "{} {}".format(linux_groups, manifest.get('group_{}').format(group_name), "linux_groups") # add it to the list of linux groups auth = True break if auth == False: return False # clean up the list of linux groups linux_groups = list() for grp in grp.split(" "): if grp == "" or grp == " ": continue linux_groups.append(grp) linux_groups = list(set(linux_groups)) #remove duplicates # remove linux groups that dont exist on the servers system_groups = grp.getgrall() linux_groups = list(set(linux_groups).intersection(system_groups)) linux_groups.append(user) #append my self in the list just incase return linux_groups
def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' ugrp = set() # Add the primary user's group ugrp.add(grp.getgrgid(pwd.getpwnam(name).pw_gid).gr_name) # If we already grabbed the group list, it's overkill to grab it again if 'user.getgrall' in __context__: groups = __context__['user.getgrall'] else: groups = grp.getgrall() __context__['user.getgrall'] = groups # Now, all other groups the user belongs to for group in groups: if name in group.gr_mem: ugrp.add(group.gr_name) return sorted(list(ugrp))
def dashboard(self): from procfs_reader import entries, proc_uptime, disk_free, git_hash from grp import getgrall, getgrgid from pwd import getpwnam from stock_profiles import STOCK_PROFILES kb_free = dict(entries('', 'meminfo'))['MemFree'] mb_free = str(round(float(kb_free.split()[0])/1000, 2)) try: pc_path = os.path.join(self.base_directory, mc.DEFAULT_PATHS['profiles'], 'profile.config') mc.has_ownership(self.login, pc_path) except (OSError, KeyError): profile_editable = False else: profile_editable = True finally: st = os.stat(pc_path) pc_group = getgrgid(st.st_gid).gr_name primary_group = getgrgid(getpwnam(self.login).pw_gid).gr_name return { 'uptime': int(proc_uptime()[0]), 'memfree': mb_free, 'whoami': self.login, 'group': primary_group, 'df': dict(disk_free('/')._asdict()), 'groups': [i.gr_name for i in getgrall() if self.login in i.gr_mem or self.login == 'root'] + [primary_group], 'pc_permissions': profile_editable, 'pc_group': pc_group, 'git_hash': git_hash(os.path.dirname(os.path.abspath(__file__))), 'stock_profiles': [i['name'] for i in STOCK_PROFILES], 'base_directory': self.base_directory, }
def UserAdd_Group(User, GroupFile='/etc/group'): # 1. temporary file fd, TempGroupFile = mkstemp(prefix='group', dir='/tmp') # 2. add new group entry pw = pwd.getpwnam(User) gr = grp.struct_group( sequence = ( User, 'x', pw.pw_gid, ['www-data'])) grall = grp.getgrall() grall.append(gr) grall.sort(lambda a, b: cmp(a.gr_gid, b.gr_gid)) # 3. write groups to temporary file with fdopen(fd, 'w+') as fh: for gr in grall: if gr.gr_name in ['www-data', 'jail'] and User not in gr.gr_mem: gr.gr_mem.append(User) fh.write(':'.join(map(GroupItem, gr))+'\n') # 4. activate new group file rename(TempGroupFile, GroupFile) chown(GroupFile, 0, 0) chmod(GroupFile, 0644)
def getNewGroupID(self): newID = 0 grps = grp.getgrall() for g in grps: if (g.gr_gid >= 1000 and g.gr_gid <= 1500) and g.gr_gid > newID: newID = g.gr_gid return newID + 1
def GetGroupIDs(): GroupIDs = map( lambda x: x.gr_gid, grp.getgrall()) return set(filter( lambda x: x >= MinID and x <= MaxID, GroupIDs))
def Group(): groups = grp.getgrall() return ("group", select_by_weight( [ (4, groups[randint(0, len(groups) - 1)].gr_name ), (1, str(randint(0, 65536)) ) ] ) )
def setuser(username): if not username: return import pwd import grp try: pwrec = pwd.getpwnam(username) except KeyError: sys.stderr.write('user not found: %s\n' % username) raise user = pwrec[0] uid = pwrec[2] gid = pwrec[3] cur_uid = os.getuid() if uid == cur_uid: return if cur_uid != 0: sys.stderr.write('can not set user as nonroot user\n') # will raise later # inspired by supervisor if hasattr(os, 'setgroups'): groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]] groups.insert(0, gid) os.setgroups(groups) os.setgid(gid) os.setuid(uid)
def gid_list(self): """Lists all GIDs on the target system(s).""" gids = [] for group in grp.getgrall(): if group[2] < 4294967294: gids.append(group[2]) return gids
def getGroup(self,mess,a): # %nss getGroup gr_gid=1000 gr_name=stud s='' p=None print a try: if (a.has_key('gr_gid')): p=grp.getgruid(a['gr_uid']) elif (a.has_key('gr_name')): p=grp.getgrnam(a['gr_name']) else: groups=grp.getgrall() i=0 while (i<len(groups)): groups[i]=self.grpStructToDict(groups[i]) i+=1 s='@'+mess.getID()+'\n'+self.d.packData(groups,'json') except: p=None if (s==''): if (p!=None): s='@'+mess.getID()+'\n'+self.d.packData(self.grpStructToDict(p),'json') else: s='@'+mess.getID()+'\n'+'success=false' out=xmpp.Message(mess.getFrom(),s) mid=self.d.genId() out.setID(mid) return out
def check_writable( node, uid=None ): if uid == None: user = pwd.getpwuid( get_uid() ) else: user = pwd.getpwuid( uid ) s = os.stat( node ) groups = [g for g in grp.getgrall() if user.pw_name in g.gr_mem] groups.append( user.pw_gid ) cmd = '' if s.st_uid == user.pw_uid: # user owns the file if s.st_mode & stat.S_IWUSR == 0: cmd = 'chmod u+w %s' %(node) if os.path.isdir( node ) and s.st_mode & stat.S_IXUSR == 0: cmd = 'chmod u+wx %s' %(node) elif s.st_gid in groups: if s.st_mode & stat.S_IWGRP == 0: cmd = 'chmod g+w %s' %(node) if os.path.isdir( node ) and s.st_mode & stat.S_IXGRP == 0: cmd = 'chmod g+wx %s' %(node) else: if s.st_mode & stat.S_IWOTH == 0: cmd = 'chmod o+w %s' %(node) if os.path.isdir( node ) and s.st_mode & stat.S_IXOTH == 0: cmd = 'chmod o+wx %s' %(node) if cmd != '': raise RuntimeError( node, 'Not writable (fix with %s)' %(cmd) )
def drop_privileges(user, group): if user is None: uid = os.getuid() elif user.lstrip("-").isdigit(): uid = int(user) else: uid = pwd.getpwnam(user).pw_uid if group is None: gid = os.getgid() elif group.lstrip("-").isdigit(): gid = int(group) else: gid = grp.getgrnam(group).gr_gid username = pwd.getpwuid(uid).pw_name # groupname = grp.getgrgid(gid).gr_name groups = [g for g in grp.getgrall() if username in g.gr_mem] os.setgroups(groups) if hasattr(os, 'setresgid'): os.setresgid(gid, gid, gid) else: os.setregid(gid, gid) if hasattr(os, 'setresuid'): os.setresuid(uid, uid, uid) else: os.setreuid(uid, uid)
def getGroups(self): groups = [] groupsDict = grp.getgrall() for group in groupsDict: groups.append(group.gr_name) groups.sort() return groups
def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' ugrp = set() # Add the primary user's group try: ugrp.add(grp.getgrgid(pwd.getpwnam(name).pw_gid).gr_name) except KeyError: # The user's applied default group is undefined on the system, so # it does not exist pass groups = grp.getgrall() # Now, all other groups the user belongs to for group in groups: if name in group.gr_mem: ugrp.add(group.gr_name) return sorted(list(ugrp))
def check_qemu_grp_user(user): """ Check the given user exist and in 'qemu' group :param user: given user name or id :return: True or False """ try: # check the user exist or not user_id = None user_name = None try: user_id = int(user) except ValueError: user_name = user if user_id: pw_user = pwd.getpwuid(user_id) else: pw_user = pwd.getpwnam(user_name) user_name = pw_user.pw_name # check the user is in 'qemu' group grp_names = [] for g in grp.getgrall(): if user_name in g.gr_mem: grp_names.append(g.gr_name) grp_names.append(str(g.gr_gid)) if "qemu" in grp_names: return True else: err_msg = "The given user: %s exist " % user err_msg += "but not in 'qemu' group." raise error.TestFail(err_msg) except KeyError: return False
def setup_uid_manager(mockgid): unprivUid = os.getuid() unprivGid = os.getgid() # sudo if os.environ.get("SUDO_UID") is not None: unprivUid = int(os.environ['SUDO_UID']) os.setgroups((mockgid,)) unprivGid = int(os.environ['SUDO_GID']) # consolehelper if os.environ.get("USERHELPER_UID") is not None: unprivUid = int(os.environ['USERHELPER_UID']) unprivName = pwd.getpwuid(unprivUid).pw_name secondary_groups = [g.gr_gid for g in grp.getgrall() if unprivName in g.gr_mem] os.setgroups([mockgid] + secondary_groups) unprivGid = pwd.getpwuid(unprivUid)[3] uidManager = mockbuild.uid.UidManager(unprivUid, unprivGid) return uidManager
def test_simple_process_other_user(*args): with temporary_dir() as td: some_user = get_other_nonroot_user() taskpath = make_taskpath(td) sandbox = setup_sandbox(td, taskpath) p = TestProcess('process', 'echo hello world', 0, taskpath, sandbox, user=some_user.pw_name) p.start() wait_for_rc(taskpath.getpath('process_checkpoint')) # since we're not actually root, the best we can do is check the right things were attempted assert os.setgroups.calledwith( [g.gr_gid for g in grp.getgrall() if some_user.pw_name in g]) assert os.setgid.calledwith(some_user.pw_uid) assert os.setuid.calledwith(some_user.pw_gid)
def authenticate(): """Authenticate a user using Synology's authenticate.cgi If the user is authenticated, returns a nametuple with the username and its groups, if not returns None. For example:: >>> authenticate() User(name='admin', groups=['administrators']) :rtype: namedtuple or None """ User = namedtuple('User', ['name', 'groups']) with open(os.devnull, 'w') as devnull: user = check_output(['/usr/syno/synoman/webman/modules/authenticate.cgi'], stderr=devnull).strip() if not user: return None groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] groups.append(grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name) return User(user, set(groups))
def update(self): del self.user_table[:] # cleaning previous record .. for user in pwd.getpwall(): san_user = {} san_user['username'] = user.pw_name san_user['password'] = user.pw_passwd san_user["home"] = user.pw_dir san_user["shell"] = user.pw_shell san_user["uid"] = user.pw_uid san_user["gid"] = user.pw_gid self.user_table.append(san_user) del self.group_table[:] # Delete Previous Record for group in grp.getgrall(): san_grp = {} san_grp["grpname"] = group.gr_name san_grp["password"] = group.gr_passwd san_grp["gid"] = group.gr_gid san_grp["mem"] = group.gr_mem self.group_table.append(san_grp)
def make_preexec_fn(self, cluster): # pragma: nocover # Borrowed and modified from jupyterhub/spawner.py pwnam = getpwnam(cluster.username) uid = pwnam.pw_uid gid = pwnam.pw_gid groups = [ g.gr_gid for g in grp.getgrall() if cluster.username in g.gr_mem ] workdir = cluster.state["workdir"] def preexec(): os.setgid(gid) try: os.setgroups(groups) except Exception as e: print("Failed to set groups %s" % e, file=sys.stderr) os.setuid(uid) os.chdir(workdir) return preexec
def test_local_set_group(self): """fileops.set_group: set group ownership on a local directory """ # Get a list of groups current_user = pwd.getpwuid(os.getuid()).pw_name groups = [g.gr_gid for g in grp.getgrall() if current_user in g.gr_mem] print "Available groups: %s" % groups if len(groups) < 2: raise unittest.SkipTest("user '%s' must be in at least " "two groups" % current_user) # Make test directory and files test_dir = os.path.join(self.test_dir,'test.dir') os.mkdir(test_dir) test_file1 = os.path.join(test_dir,'test1.txt') test_file2 = os.path.join(test_dir,'test2.txt') test_file3 = os.path.join(test_dir,'test3.txt') for f in (test_file1,test_file2,test_file3): with open(f,'w') as fp: fp.write("This is a test file") self.assertTrue(os.path.isfile(f)) # Get initial group from a test file gid = os.stat(test_file1).st_gid print "File: %s GID: %s" % (test_file1,gid) # Get a second group new_gid = None for group in groups: if group != gid: new_gid = group break print "Selected new GID: %s" % new_gid for f in (test_file1,test_file2,test_file3): self.assertNotEqual(os.stat(f).st_gid,new_gid) # Change group by name new_group = grp.getgrgid(new_gid).gr_name print "New group name: %s" % new_group status = set_group(new_group,test_dir) self.assertEqual(status,0) for f in (test_file1,test_file2,test_file3): print "File: %s GID: %s" % (f,os.stat(f).st_gid) self.assertEqual(os.stat(f).st_gid,new_gid)
def get_group_list(user=None, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' group_names = None ugroups = set() if not isinstance(user, string_type): raise Exception if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 logger.debug('Trying os.getgrouplist for {0!r}'.format(user)) try: group_names = list(os.getgrouplist(user, pwd.getpwnam(user).pw_gid)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to behave like # os.getgrouplist() and pysss.getgrouplist() do logger.debug('Trying generic group list for {0!r}'.format(user)) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass ugroups.update(group_names) if include_default is False: try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass logger.debug('Group list for user {0!r}: {1!r}'.format( user, sorted(ugroups))) return sorted(ugroups)
def change_user_group(self, user, group): if not user and not group: return import pwd, grp uid = gid = None if group: try: gid = int(group) group = grp.getgrgid(gid).gr_name except ValueError: import grp try: entry = grp.getgrnam(group) except KeyError: raise BadCommand("Bad group: %r; no such group exists" % group) gid = entry.gr_gid try: uid = int(user) user = pwd.getpwuid(uid).pw_name except ValueError: try: entry = pwd.getpwnam(user) except KeyError: raise BadCommand("Bad username: %r; no such user exists" % user) if not gid: gid = entry.pw_gid uid = entry.pw_uid if self.verbose > 0: print 'Changing user to %s:%s (%s:%s)' % (user, group or '(unknown)', uid, gid) if hasattr(os, 'initgroups'): os.initgroups(user, gid) else: os.setgroups( [e.gr_gid for e in grp.getgrall() if user in e.gr_mem] + [gid]) if gid: os.setgid(gid) if uid: os.setuid(uid)
def set_user_setuid(username): """return a preexec_fn for setting the user (via setuid) of a spawned process""" user = pwd.getpwnam(username) uid = user.pw_uid gid = user.pw_gid home = user.pw_dir gids = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem] def preexec(): # set the user and group os.setgid(gid) try: os.setgroups(gids) except Exception as e: print('Failed to set groups %s' % e, file=sys.stderr) os.setuid(uid) # start in the user's home dir _try_setcwd(home) return preexec
def find_gids_for_uid(uid): '''Find all GIDs of groups the user with given name belongs to @param uid: User UID @type uid: number @returns: GIDs of all groups the user belongs to @rtype: list<number> ''' import grp import pwd # Primary group user = pwd.getpwuid(uid) yield user.pw_gid username = user.pw_name for group in grp.getgrall(): if username in group.gr_mem: yield group.gr_gid
def list_groups(name): ''' Return a list of groups the named user belongs to CLI Example:: salt '*' user.list_groups foo ''' ugrp = set() # Add the primary user's group try: ugrp.add(grp.getgrgid(pwd.getpwnam(name).pw_gid).gr_name) except KeyError: # The user's applied default group is undefined on the system, so # it does not exist pass # Now, all other groups the user belongs to for group in grp.getgrall(): if name in group.gr_mem: ugrp.add(group.gr_name) return sorted(list(ugrp))
def __init__(self, username): ConchUser.__init__(self) self.username = username #self.pwdData = pwd.getpwnam(self.username) self.pwdData = [0, 0, 0, 0, 0, 0, 0] self.pwdData[3] = 20 self.pwdData[5] = '/tmp' self.pwdData[6] = '/bin/bash' l = [self.pwdData[3]] for groupname, password, gid, userlist in grp.getgrall(): if username in userlist: l.append(gid) self.otherGroups = l self.listeners = {} # dict mapping (interface, port) -> listener self.channelLookup.update( {"session": session.SSHSession, "direct-tcpip": forwarding.openConnectForwardingClient}) self.subsystemLookup.update( {"sftp": filetransfer.FileTransferServer})
def set_user(uid, assign_all_groups): try: # Get user's default group and set it to current process to make sure file permissions are inherited correctly # Solves issue with permission denied for JSON files gid = pwd.getpwuid(uid).pw_gid import grp os.setgid(gid) if assign_all_groups: # Added lines to assure read/write permission for groups user = pwd.getpwuid(uid).pw_name groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem] os.setgroups(groups) os.setuid(uid) except OSError, e: if e.errno == errno.EPERM: sys.stderr.write( "error: setuid(%d) failed: permission denied. Did you setup 'sudo' correctly for this script?\n" % uid ) exit(1) else: pass
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Find a group that isn't the user's default group (or sudo), and # use that as our default group. login = utils.get_login() def_gid = os.getgid() candidates = [ group for group in grp.getgrall() if (login in group.gr_mem and def_gid != group.gr_gid) ] if not candidates: self.fail("Your user must be in at least two groups (other than " "the user's group) to run this test.") self.orig_group = grp.getgrgid(def_gid).gr_name self.alt_group = candidates[0] # type: grp.struct_group self.alt_group2 = candidates[1] # type: grp.struct_group self.umask = 0o007
def process_pam(self, settings_dict): if not settings_dict["USE_PAM_AUTHENTICATION"]: return [] try: get_distribution("django_pam") except DistributionNotFound: settings_check_results.append( missing_package("django-pam", " to use PAM authentication")) return [] # check if the current user is in the shadow group username = pwd.getpwuid(os.getuid()).pw_name if not any(x.gr_name == "shadow" and username in x.gr_mem for x in grp.getgrall()): settings_check_results.append( Error( 'The user "%s" must belong to the "shadow" group to use PAM ' "authentication." % username, obj="configuration", )) return [] return ["django_pam.auth.backends.PAMBackend"]
def switch_user(name="softwarecollections"): """Change the current user to the specified one. Keyword arguments: name: The name (login) of the user to switch to. Must exists on the system. """ user = pwd.getpwnam(name) groups = [g.gr_gid for g in grp.getgrall() if user.pw_name in g.gr_mem] # Execution context os.setgid(user.pw_gid) os.setgroups(groups) os.setuid(user.pw_uid) # Environment os.environ.update(USER=user.pw_name, LOGNAME=user.pw_name, HOME=user.pw_dir, SHELL=user.pw_shell)
def _enforce_user(self): '''Set the correct user''' try: pw = pwd.getpwnam(self.user) except: msg = "ERROR: the configured user %r does not exists" % self.user raise SystemExit(msg) if pw.pw_uid == os.getuid(): return try: os.setgroups( [e.gr_gid for e in grp.getgrall() if pw.pw_name in e.gr_mem] + [pw.pw_gid]) os.setgid(pw.pw_gid) os.setuid(pw.pw_uid) os.setegid(pw.pw_gid) os.seteuid(pw.pw_uid) except: msg = "ERROR: please run barman as %r user" % self.user raise SystemExit(msg) os.environ['HOME'] = pw.pw_dir
def print_user_details(username): """ Print information about the user. args: username: user to print information about returns nothing """ usr_pwd = pwd.getpwnam(username) print("user: %s uid: %d" % (usr_pwd.pw_name, usr_pwd.pw_uid)) print("home: %s shell: %s" % (usr_pwd.pw_dir, usr_pwd.pw_shell)) primary_group = grp.getgrgid(usr_pwd.pw_gid) print("primary group: %s(%d)" % ( primary_group.gr_name, primary_group.gr_gid )) print("other groups: %s" % ', '.join([ "%s(%d)" % (g.gr_name, g.gr_gid) for g in grp.getgrall() if username \ in g.gr_mem ]))
def valid(self): valid_dirs = ["chdir", "pythonpath"] valid_files = [ "pidfile", "daemonize", "wsgi-file", ] def get_rights(path): try: f = os.stat(path) except OSError: return (None, None) uid = f.st_uid gid = f.st_gid return (uid, gid) for app in self.config: user = self.config[app]["uid"] uid = getpwnam(user).pw_uid gid = getpwnam(user).pw_gid guid = [ g for g in grp.getgrall() if g.gr_name == self.config[app]["gid"] ] if guid and guid[0].gr_gid != gid: self.log.error("%s:%s %s" % (uid, gid, guid[0].gr_gid)) for key in self.config[app].keys(): if key in valid_dirs: filepath = self.config[app][key] elif key in valid_files: filepath = self.config[app][key] else: continue u, g = get_rights(filepath) if u != uid or g != gid: self.log.error("%s: file %s %s:%s %s:%s" % (key, filepath, u, g, uid, gid))
def drop_priviledges(self, user): if user is None: return "No user specified to setuid to!" try: uid = int(user) except ValueError: try: pwrec = pwd.getpwnam(user) except KeyError: return "Can't find username %r" % user uid = pwrec[2] else: try: pwrec = pwd.getpwuid(uid) except KeyError: return "Can't find uid %r" % uid current_uid = os.getuid() if current_uid == uid: return "" if current_uid != 0: return "Can't drop privilege as nonroot user" gid = pwrec[3] if hasattr(os, 'setgroups'): user = pwrec[0] groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]] groups.insert(0, gid) try: os.setgroups(groups) except OSError: return 'Could not set groups of effective user' try: os.setgid(gid) except OSError: return 'Could not set group id of effective user' os.setuid(uid) return "User set for the process"
def load(self): pwds = pwd.getpwall() spwds = spwd.getspall() sn = {} for s in spwds: sn[s.sp_nam] = s for p in pwds: if p.pw_name in sn: s = sn[p.pw_name] else: s = spwd.struct_spwd([None] * 9) gecos = p.pw_gecos.split(',', 4) gecos += [''] * ( 5 - len(gecos) ) # Pad with empty strings so we have exactly 5 items rname, office, wphone, hphone, other = gecos u = User(p.pw_name, p.pw_uid, p.pw_gid, rname, office, wphone, hphone, other, p.pw_dir, p.pw_shell, [grp.getgrgid(p.pw_gid).gr_name], s.sp_lstchg, s.sp_min, s.sp_max, s.sp_warn, s.sp_inact, s.sp_expire, s.sp_pwd) self.users[u.name] = u groups = grp.getgrall() for group in groups: g = Group(group.gr_name, group.gr_gid) for member in group.gr_mem: if member in self.users: ugroups = self.users[member].groups if group.gr_name not in ugroups: self.users[member].groups.append(group.gr_name) g.members[member] = self.users[member] self.groups[group.gr_name] = g for user in self.users.values(): primary_group = grp.getgrgid(user.gid).gr_name if primary_group in self.groups: self.groups[primary_group].members[user.name] = user
def l_groups_groupoptions(): global l_groups_group global l_groups_again global l_groups_input system("clear") options = "1) Show users in the group \n2) Show group id \n3) Add user to this group \n4) Back \n5) Main menu" print options if l_groups_again == 0: l_groups_input = raw_input("Action: ") if l_groups_input == "1": print "{}'s group members:".format(l_groups_group) for g in grp.getgrall(): if g[0] == l_groups_group: print g[3] l_groups_input=raw_input("What would you like to do next? ") l_groups_again = 1 l_groups_groupoptions() elif l_groups_input == "2": l_groups_id=grp.getgrnam(l_groups_group) print "{} ID is {}".format(l_groups_group,l_groups_id[2]) l_groups_input = raw_input("What would you like to do next? ") l_groups_again = 1 l_groups_groupoptions() elif l_groups_input == "3": system("clear") while True: l_groups_input=raw_input(("Which user would you like to add to the group {}? Type \'Back\' to return\nUser: "******"" if l_groups_input.lower() == "back": l_groups_groupoptions() break l_groups_adduser="******".format(l_groups_input,l_groups_group) system(l_groups_adduser) print "" elif l_groups_input == "4": l_groups() elif l_groups_input == "5": m_menu() else: l_groups_groupoptions()
def setuidgid(uid, gid): if not POSIX: return log = get_util_logger() if os.getuid()!=uid or os.getgid()!=gid: #find the username for the given uid: from pwd import getpwuid try: username = getpwuid(uid).pw_name except KeyError: raise Exception("uid %i not found" % uid) #set the groups: if hasattr(os, "initgroups"): # python >= 2.7 os.initgroups(username, gid) else: import grp #@UnresolvedImport groups = [gr.gr_gid for gr in grp.getgrall() if (username in gr.gr_mem)] os.setgroups(groups) #change uid and gid: try: if os.getgid()!=gid: os.setgid(gid) except OSError as e: log.error("Error: cannot change gid to %i:", gid) if os.getgid()==0: #don't run as root! raise log.error(" %s", e) log.error(" continuing with gid=%i", os.getgid()) try: if os.getuid()!=uid: os.setuid(uid) except OSError as e: log.error("Error: cannot change uid to %i:", uid) if os.getuid()==0: #don't run as root! raise log.error(" %s", e) log.error(" continuing with uid=%i", os.getuid()) log("new uid=%s, gid=%s", os.getuid(), os.getgid())
def _get_posix_groups(self, user, group): groups = set() getgrouplist = getattr(os, 'getgrouplist', None) if getgrouplist: ids = getgrouplist(user, group) for i in ids: try: g = grp.getgrgid(i) groups.add(g.gr_name) except KeyError: pass else: g = grp.getgrgid(group) groups.add(g.gr_name) allg = grp.getgrall() for g in allg: if user in g.gr_mem: groups.add(g.gr_name) return list(groups)
def parseAclInfo(queue, qinfo, vo_mapper): """ Take a queue information dictionary and determine which VOs are in the ACL list. The used keys are: - users: A set of all user names allowed to access this queue. - groups: A set of all group names allowed to access this queue. @param queue: Queue name (for logging purposes). @param qinfo: Queue info dictionary @param vo_mapper: VO mapper object @returns: A set of allowed VOs """ users = qinfo.get('users', sets.Set()) if 'groups' in qinfo: all_groups = grp.getgrall() all_users = pwd.getpwall() group_dict = {} for group in all_groups: if group[0] in qinfo['groups'] or group[2] in qinfo['groups']: users.add(group[0]) group_dict[group[2]] = group[0] for user in all_users: try: group = group_dict[user[3]] except: continue if group[0] in qinfo['groups'] or user[3] in qinfo['groups']: users.add(group[0]) vos = sets.Set() for user in users: try: vos.add(vo_mapper[user]) except: pass log.info("The acl info for queue %s (users %s, groups %s) mapped to %s." % \ (queue, ', '.join(qinfo.get('users', [])), ', '.join(qinfo.get('groups', [])), ', '.join(vos))) return vos
def __init__(self, **kwargs): if os.geteuid() != 0: self._current_user = os.getenv("USER") self._current_user = pwd.getpwuid(int(os.getenv("SUDO_UID", default=0))).pw_name for group_name in [g.gr_name for g in grp.getgrall() if self._current_user in g.gr_mem]: if group_name == self.ARDUINO_GROUP: self.was_in_arduino_group = True break else: self.was_in_arduino_group = False super().__init__(name="Arduino", description=_("The Arduino Software Distribution"), only_on_archs=['i386', 'amd64', 'armhf'], download_page='https://www.arduino.cc/en/Main/Software', dir_to_decompress_in_tarball='arduino-*', desktop_filename='arduino.desktop', checksum_type=ChecksumType.sha512, packages_requirements=['gcc-avr', 'avr-libc'], need_root_access=not self.was_in_arduino_group, required_files_path=["arduino"], **kwargs)
def dir_chown(self, directories, user, group, recursive=False): """ Chown a or multiple directories :param directories: Directories to chown :param user: User to assign to directories :param group: Group to assign to directories :param recursive: Chown the directories recursively or not :return: None """ if self._unittest_mode is True: return all_users = [user_info[0] for user_info in pwd.getpwall()] all_groups = [group_info[0] for group_info in grp.getgrall()] if user not in all_users: raise ValueError( 'User "{0}" is unknown on the system'.format(user)) if group not in all_groups: raise ValueError( 'Group "{0}" is unknown on the system'.format(group)) uid = pwd.getpwnam(user)[2] gid = grp.getgrnam(group)[2] if isinstance(directories, basestring): directories = [directories] for directory in directories: if self.is_local is True: os.chown(directory, uid, gid) if recursive is True: for root, dirs, _ in os.walk(directory): for sub_dir in dirs: os.chown('/'.join([root, sub_dir]), uid, gid) else: recursive_str = '-R' if recursive is True else '' self.run([ 'chown', recursive_str, '{0}:{1}'.format(user, group), directory ])
def change_uid(self): c_user = self.options.uid c_group = self.options.gid if os.getuid() == 0: cpw = pwd.getpwnam(c_user) c_uid = cpw.pw_uid if c_group: cgr = grp.getgrnam(c_group) c_gid = cgr.gr_gid else: c_gid = cpw.pw_gid c_group = grp.getgrgid(cpw.pw_gid).gr_name c_groups = [] for item in grp.getgrall(): if c_user in item.gr_mem: c_groups.append(item.gr_gid) if c_gid not in c_groups: c_groups.append(c_gid) os.setgid(c_gid) os.setgroups(c_groups) os.setuid(c_uid)
def __init__(self, username): super(GroupsDialog, self).__init__() try: self.set_modal(True) self.set_skip_taskbar_hint(True) self.set_skip_pager_hint(True) self.set_title("") self.set_default_size(200, 480) scrolled = Gtk.ScrolledWindow() viewport = Gtk.Viewport() vbox = Gtk.VBox() self.checkboxes = [] groups = sorted(grp.getgrall(), key=lambda x: x[0], reverse=False) for group in groups: checkbox = Gtk.CheckButton(group[0]) self.checkboxes.append(checkbox) vbox.add(checkbox) if username in group[3]: checkbox.set_active(True) viewport.add(vbox) scrolled.add(viewport) self.set_border_width(6) box = self.get_content_area() box.pack_start(scrolled, True, True, 0) self.show_all() self.add_buttons( Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK, ) except Exception, detail: print detail
def permissionsUser(uid, gid): """Sets the effective gid/uid to supplied values""" if platform.system() == 'Windows': return if os.getuid() != 0: return PERMISSIONS.acquire() __becomeRoot() try: username = pwd.getpwuid(uid).pw_name usergroups = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem] if rqconstants.LAUNCH_FRAME_USER_GID: groups = [rqconstants.LAUNCH_FRAME_USER_GID] + usergroups else: groups = usergroups os.setgroups(groups) except Exception: pass os.setegid(gid) os.seteuid(uid)