def getpwuid(uidobj): if uidobj == 501: return pwd.struct_passwd(('fots', '********', 501, 20, 'Fotis Gimian', '/Users/fots', '/bin/bash')) elif uidobj == 502: return pwd.struct_passwd(('happy', '********', 502, 20, 'Happy Man', '/Users/happy', '/bin/bash')) else: raise KeyError(f'getpwuid(): uid not found: {uidobj}')
def getpwnam(arg): if arg == 'fots': return pwd.struct_passwd(('fots', '********', 501, 20, 'Fotis Gimian', '/Users/fots', '/bin/bash')) elif arg == 'happy': return pwd.struct_passwd(('happy', '********', 502, 20, 'Happy Man', '/Users/happy', '/bin/bash')) else: raise KeyError(f'getpwnam(): name not found: {arg}')
def stdlib(): if acos(1) == "0": pass # Noncompliant if math.ceil(7.9) == "8": pass # FN: ceil defined twice in math for python 2 & python 3 if math.pow(2, 3) == "8": pass # FN pow defined in builtin as well as math if iskeyword("something") == "1": pass # Noncompliant tuple = "name", "passwd", 123, 456, "gecos", "dir", "shell" passwd = pwd.struct_passwd(tuple) if passwd == "something": pass passwd_2 = pwd.struct_passwd(tuple) if passwd == passwd_2: pass # OK if passwd == pwd.getpwuid(1): pass # OK if 42 == pwd.getpwuid(1): pass # FN, unresolved type hierarchy if pwd.getpwall() == 42: pass # Noncompliant if zip(l1, l2) == 42: pass # Noncompliant
def test_process(): prior = [ struct_passwd(('A', 'x', 10000, 10000, '', '/home/A', '/bin/bash')), struct_passwd(('B', 'x', 10001, 10001, '', '/home/B', '/bin/bash')), struct_passwd(('C', 'x', 10099, 10099, '', '/home/C', '/bin/bash')), ] sprior = [ struct_spwd(('A', '*', 16593, 0, 99999, 7, -1, -1, -1)), struct_spwd(('B', '*', 16503, 0, 99999, 7, -1, -1, -1)), struct_spwd(('C', '*', 16513, 0, 99999, 7, -1, -1, -1)), ] user_pks = { 'john': [ 'ssh-rsa AAAAC...aliuh7', 'ssh-rsa AAAAC...qo874y', ], 'C': [ 'ssh-rsa AAAAC...7a6cs1', ] } passwd, shadow, sudo = iam_acctmgr.process(user_pks, prior, sprior) days_since_epoch = str( (datetime.utcnow() - iam_acctmgr.EPOCH).days ).encode('utf-8') assert passwd == [ b'A:x:10000:10000::/home/A:/bin/bash', b'B:x:10001:10001::/home/B:/bin/bash', b'C:x:10099:10099::/home/C:/bin/bash', b'john:x:10002:10002:IAM-USER:/home/john:/bin/bash', ] assert shadow == [ b'A:*:16593:0:99999:7:::', b'B:*:16503:0:99999:7:::', b'C:*:16513:0:99999:7:::', b'john:*:' + days_since_epoch + b':0:99999:7:::' ] assert sudo[0].decode('utf-8').startswith('# ') assert sudo[1:] == [ b'C ALL=(ALL) NOPASSWD:ALL', b'john ALL=(ALL) NOPASSWD:ALL', ]
def get_users(self): """Returns a list of all local users on the computer. Each user is represented as a dict with the keys: C{username}, C{name}, C{uid}, C{enabled}, C{location}, C{work-phone} and C{home-phone}. """ users = [] found_usernames = set() for user in self.get_user_data(): if not isinstance(user, struct_passwd): user = struct_passwd(user) if user.pw_name in found_usernames: continue gecos_data = [x or None for x in user.pw_gecos.split(",")[:4]] while len(gecos_data) < 4: gecos_data.append(None) name, location, work_phone, home_phone = tuple(gecos_data) enabled = user.pw_name not in self.locked_users users.append({ "username": user.pw_name, "name": name, "uid": user.pw_uid, "enabled": enabled, "location": location, "work-phone": work_phone, "home-phone": home_phone, "primary-gid": user.pw_gid }) found_usernames.add(user.pw_name) return users
def test_format_info(self): """ Tests the formatting of returned user information """ data = pwd.struct_passwd(( "_TEST_GROUP", "*", 83, 83, "AMaViS Daemon", "/var/virusmails", "/usr/bin/false", )) ret = { "shell": "/usr/bin/false", "name": "_TEST_GROUP", "gid": 83, "groups": ["_TEST_GROUP"], "home": "/var/virusmails", "fullname": "AMaViS Daemon", "uid": 83, } with patch("salt.modules.mac_user.list_groups", MagicMock(return_value=["_TEST_GROUP"])): self.assertEqual(mac_user._format_info(data), ret)
def load_passwd(dirpath): # check if we need to reload cache passwd_file = os.path.join(dirpath, "etc/passwd") passwd_stamp = os.stat(passwd_file).st_mtime if passwd_stamp <= users_lastupdate.get(dirpath, -1): return users[dirpath] = user = {} uids[dirpath] = uid = {} f = open(passwd_file) for line in f: arr = line.rstrip().split(":") if len(arr) != 7: # Skip any line we can't make sense of. continue try: arr[2] = int(arr[2]) arr[3] = int(arr[3]) except ValueError: # Skip any line we can't make sense of. continue pw_entry = pwd.struct_passwd(arr) user[pw_entry.pw_name] = pw_entry # Traditional systems allow multiple users to have the same # user id, so only the first one should be mapped to the # current pw_entry. uid.setdefault(pw_entry.pw_uid, pw_entry) users_lastupdate[dirpath] = passwd_stamp f.close()
def load_passwd(dirpath): # check if we need to reload cache passwd_file = os.path.join(dirpath, "etc/passwd") passwd_stamp = os.stat(passwd_file).st_mtime if passwd_stamp <= users_lastupdate.get(dirpath, -1): return users[dirpath] = user = {} uids[dirpath] = uid = {} f = file(passwd_file) for line in f: arr = line.rstrip().split(":") if len(arr) != 7: # Skip any line we can't make sense of. continue try: arr[2] = int(arr[2]) arr[3] = int(arr[3]) except ValueError: # Skip any line we can't make sense of. continue pw_entry = pwd.struct_passwd(arr) user[pw_entry.pw_name] = pw_entry # Traditional systems allow multiple users to have the same # user id, so only the first one should be mapped to the # current pw_entry. uid.setdefault(pw_entry.pw_uid, pw_entry) users_lastupdate[dirpath] = passwd_stamp f.close()
def test_expand_user(value, expect): struct = pwd.struct_passwd( ['tester', 'x', 1234, 1000, 'Test User', '/home/tester', '/bin/sh']) flexmock(os) \ .should_receive('geteuid') \ .and_return(1234) flexmock(pwd) \ .should_receive('getpwuid') \ .and_return(struct) flexmock(pwd) \ .should_receive('getpwnam') \ .and_return(struct) flexmock(grp) \ .should_receive('getgrnam') \ .and_return(grp.struct_group(['gx', 'x', 100, []])) flexmock(grp) \ .should_receive('getgrall') \ .and_return([ grp.struct_group(['g1', 'x', 101, []]), grp.struct_group(['g2', 'x', 102, ['tester']]), grp.struct_group(['.g-$ +3', 'x', 103, ['net+tester']]), grp.struct_group(['veryveryveryveryveryverylongname_thisnot', 'x', 104, ['tester']]), ]) result = expand_user({'global': {'user': value}}) assert result == expect
def assert_create_user_and_group(mock_check_call, gid_exists, uid_exists): mock_pwent = pwd.struct_passwd(( 'someuser', # login name 'hunter2', # password 834, # uid 835, # gid 'Some User', # user name '/home/someuser', # home directory '/bin/sh')) # login shell mock_grent = grp.struct_group(( 'users', # group name '*', # password 835, # gid ['someuser'])) # members exception = subprocess.CalledProcessError( returncode=FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS, cmd='some command', output=None) mock_check_call.side_effect = [ None if gid_exists else exception, None if uid_exists else exception ] with temporary_dir() as d: with mock.patch.object(FileSystemImageSandbox, 'get_user_and_group', return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox(os.path.join(d, 'sandbox'), user='******') sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2
class ConfigPermissions(unittest.TestCase): conf = {'dir': '', 'user': '', 'group': ''} pwd_root = pwd.struct_passwd( ('root', 'x', 0, 0, 'root', '/root', '/bin/bash')) grp_root = grp.struct_group(('root', 'x', 0, [])) def test_no_user(self): with patch.object(pwd, 'getpwnam', side_effect=KeyError()): with patch.object(grp, 'getgrnam', return_value=self.grp_root): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.SKIP) def test_no_group(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', side_effect=KeyError()): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.SKIP) def test_good_perm(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', return_value=self.grp_root): with patch.object(utils, 'validate_permissions', return_value=TestResult(Result.PASS)): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.PASS) def test_bad_perm(self): with patch.object(pwd, 'getpwnam', return_value=self.pwd_root): with patch.object(grp, 'getgrnam', return_value=self.grp_root): with patch.object(utils, 'validate_permissions', return_value=TestResult(Result.FAIL)): res = test_manila.config_permission(self.conf) self.assertEqual(res.result, Result.FAIL)
def test_expand_user_non_posix(): longname = '[email protected]' shortname = longname[:32] posixname = 'This_is-not_a-posix-username.It-' struct = pwd.struct_passwd( [longname, 'x', 1234, 1000, 'Test User', '/home/tester', '/bin/sh']) flexmock(pwd) \ .should_receive('getpwnam') \ .and_return(struct) flexmock(grp) \ .should_receive('getgrnam') \ .and_return(grp.struct_group(['gx', 'x', 100, []])) flexmock(grp) \ .should_receive('getgrall') \ .and_return([ grp.struct_group(['g1', 'x', 101, [longname]]), grp.struct_group(['g2', 'x', 102, [shortname]]), grp.struct_group(['g3', 'x', 103, [posixname]]), ]) result = expand_user({'global': {'user': '******' + longname}}) expect = dict( name=posixname, uid=1234, system=False, sudo=False, comment=longname, groups=[{'name': 'gx', 'gid': 100}, {'name': 'g1', 'gid': 101}]) assert result == expect
def testFindCredentialsFile_PortageUsername(self): """Checks that we can locate the JSON files under $PORTAGE_USERNAME.""" copy_environ = os.environ.copy() copy_environ['HOME'] = '/nonexistent' copy_environ['PORTAGE_USERNAME'] = '******' fakeuser_homedir = os.path.join(TESTDATA_PATH, 'androidbuild') fakeuser_pwent = pwd.struct_passwd( ('fakeuser', 'x', 1234, 1234, 'Fake User', fakeuser_homedir, '/bin/sh')) service_account_name = 'test_creds_authorized_user.json' with mock.patch.dict(os.environ, copy_environ), \ mock.patch.object(pwd, 'getpwnam') as mock_getpwnam: mock_getpwnam.return_value = fakeuser_pwent json_path = androidbuild.FindCredentialsFile( homedir_json_credentials_path=service_account_name) mock_getpwnam.assert_called_once_with('fakeuser') self.assertEqual( json_path, os.path.join(fakeuser_homedir, service_account_name))
def os_user(monkeypatch): # pylint: disable=import-outside-toplevel if os.name == "nt": import getpass # pylint: disable=unused-import # noqa monkeypatch.setattr("getpass.getuser", lambda: "Lektor Test") return "lektortest" # we disable pylint, because there is no such # modules on windows & it's false positive import pwd # pylint: disable=import-error struct = pwd.struct_passwd( ( "lektortest", # pw_name "lektorpass", # pw_passwd 9999, # pw_uid 9999, # pw_gid "Lektor Test", # pw_gecos "/tmp/lektortest", # pw_dir "/bin/lektortest", # pw_shell ) ) monkeypatch.setattr("pwd.getpwuid", lambda id: struct) monkeypatch.setenv("USER", "lektortest") return "lektortest"
def _test_restore_vtpm( self, exists, mock_isdir, mock_exists, mock_chown, mock_move, mock_makedirs, mock_chmod, mock_getpwnam, mock_getgrnam, ): mock_exists.return_value = exists mock_isdir.return_value = True mock_getpwnam.return_value = pwd.struct_passwd( ('swtpm', '*', 1234, 1234, None, '/home/test', '/bin/bash')) mock_getgrnam.return_value = grp.struct_group(('swtpm', '*', 4321, [])) libvirt_utils.restore_vtpm_dir('dummy') if not exists: mock_makedirs.assert_called_once_with(libvirt_utils.VTPM_DIR) mock_chmod.assert_called_once_with(libvirt_utils.VTPM_DIR, 0o711) mock_getpwnam.assert_called_once_with(CONF.libvirt.swtpm_user) mock_getgrnam.assert_called_once_with(CONF.libvirt.swtpm_group) mock_chown.assert_called_with('dummy', 1234, 4321, recursive=True) mock_move.assert_called_with('dummy', libvirt_utils.VTPM_DIR)
def test_process(): prior = [ struct_passwd(('A', 'x', 10000, 10000, '', '/home/A', '/bin/bash')), struct_passwd(('B', 'x', 10001, 10001, '', '/home/B', '/bin/bash')), struct_passwd(('C', 'x', 10099, 10099, '', '/home/C', '/bin/bash')), ] sprior = [ struct_spwd(('A', '*', 16593, 0, 99999, 7, -1, -1, -1)), struct_spwd(('B', '*', 16503, 0, 99999, 7, -1, -1, -1)), struct_spwd(('C', '*', 16513, 0, 99999, 7, -1, -1, -1)), ] user_pks = { 'john': [ 'ssh-rsa AAAAC...aliuh7', 'ssh-rsa AAAAC...qo874y', ], 'C': [ 'ssh-rsa AAAAC...7a6cs1', ] } passwd, shadow, sudo = iam_acctmgr.process(user_pks, prior, sprior) days_since_epoch = str( (datetime.utcnow() - iam_acctmgr.EPOCH).days).encode('utf-8') assert passwd == [ b'A:x:10000:10000::/home/A:/bin/bash', b'B:x:10001:10001::/home/B:/bin/bash', b'C:x:10099:10099::/home/C:/bin/bash', b'john:x:10002:10002:IAM-USER:/home/john:/bin/bash', ] assert shadow == [ b'A:*:16593:0:99999:7:::', b'B:*:16503:0:99999:7:::', b'C:*:16513:0:99999:7:::', b'john:*:' + days_since_epoch + b':0:99999:7:::' ] assert sudo[0].decode('utf-8').startswith('# ') assert sudo[1:] == [ b'C ALL=(ALL) NOPASSWD:ALL', b'john ALL=(ALL) NOPASSWD:ALL', ]
def __init__(self): passwd = [ i.strip().split(":") for i in open(os.path.join(location,"passwd"))] self.passwd = [] for s in passwd: s[2] = int(s[2]) s[3] = int(s[3]) self.passwd.append(struct_passwd(s)) self.byname = dict([ ( i.pw_name, i,) for i in self.passwd]) self.byuid = dict([ ( str(i.pw_uid), i,) for i in self.passwd])
def test_01_username(self, mock_getpwuid, mock_uid, mock_gid): """Test01 HostInfo().username.""" usr = pwd.struct_passwd( ["root", "*", "0", "0", "root usr", "/root", "/bin/bash"]) mock_uid.return_value = 0 mock_gid.return_value = 0 mock_getpwuid.return_value = usr name = HostInfo().username() self.assertEqual(name, usr.pw_name)
def test_format_info(self): ''' Tests the formatting of returned user information ''' data = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) ret = {'shell': '/usr/bin/false', 'name': '_TEST_GROUP', 'gid': 83, 'groups': ['_TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83} self.assertEqual(mac_user._format_info(data), ret)
def test_chugid_and_umask(self): running_user = this_user() running_group = grp.getgrgid(os.getgid()).gr_name gids = {30: "expectedgroup", 20: running_group} getgrnams = { "expectedgroup": grp.struct_group(("expectedgroup", "*", 30, ["expecteduser"])), running_group: grp.struct_group((running_group, "*", 20, [running_user])), } getpwnams = { "expecteduser": pwd.struct_passwd(("expecteduser", "x", 30, 30, "-", "-", "-")), running_user: pwd.struct_passwd((running_user, "x", 20, 20, "-", "-", "-")), } def getgrnam(group): return getgrnams[group] def getpwnam(user): return getpwnams[user] def getgrgid(gid): return getgrnams[gids[gid]] with patch("grp.getgrgid", getgrgid): with patch("grp.getgrnam", getgrnam): with patch("pwd.getpwnam", getpwnam): with patch("salt.utils.user.chugid") as chugid_mock: salt.utils.user.chugid_and_umask("expecteduser", umask=None, group=running_group) chugid_mock.assert_called_with("expecteduser", running_group) salt.utils.user.chugid_and_umask("expecteduser", umask=None, group=None) chugid_mock.assert_called_with("expecteduser", "expectedgroup")
def test_info(self): ''' Tests the return of user information ''' mock_pwnam = pwd.struct_passwd(('test', '*', 0, 0, 'TEST USER', '/var/test', '/bin/bash')) ret = {'shell': '/bin/bash', 'name': 'test', 'gid': 0, 'groups': ['_TEST_GROUP'], 'home': '/var/test', 'fullname': 'TEST USER', 'uid': 0} with patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam)): self.assertEqual(mac_user.info('root'), ret)
def get_nobody() -> pwd.struct_passwd: try: return pwd.getpwnam('nobody') except KeyError: return pwd.struct_passwd(pw_name='nobody', pw_passwd='*', pw_uid=-1, pw_gid=-1, pw_gecos='Unprivileged User', pw_dir='/tmp', pw_shell='/usr/bin/false')
def init_session(self, user_pwd: Tuple, user_env: Tuple[str, ...]): """Perform session setup Beware that user_pwd can be None if user is not present in the password database. Otherwise it is a tuple convertible to pwd.struct_passwd. """ # conversion example: user_pwd = pwd.struct_passwd(user_pwd) if user_pwd else None # This is how you change the user_env: return (sudo.RC_OK, user_env)
def test_gecos_missing_in_getpwuid_response(config): """No GECOS field in getpwuid response.""" import pwd cmd = InitCommand(config) with patch("pwd.getpwuid") as mock_pwd: # return a fack passwd struct with an empty gecos (5th parameter) mock_pwd.return_value = pwd.struct_passwd(("user", "pass", 1, 1, "", "dir", "shell")) msg = "Unable to automatically determine author's name, specify it with --author" with pytest.raises(CraftError, match=msg): cmd.run(Namespace(name="my-charm", author=None, force=False))
def setUp(self): import pwd import struct pwd.getpwuid = minimock.Mock('pwd.getpwuid', tracker=None) pwd.getpwuid.mock_returns = pwd.struct_passwd(('fakeuser', 'x', 123, 123, 'gecos', 'homedir', 'shell')) struct.unpack = minimock.Mock('struct.unpack', tracker=None) struct.unpack.mock_returns = 0, 123, 123 # pid, uid, gid config.configuration.remove_section('ACL') config.configuration.add_section('ACL') # force ACLs to be reloaded config.configuration._acl = () sp = self.sp = ServerProtocol() sp.factory = ServerFactory() self.testUser = testUser = User() testUser.name = 'Test User' testUser.time = 0 testUser.username = '******' testUser.groups = ['testgroup'] testUser.client = 'ltsp200' testUser.server = 'ltspserver00' testUser.display = ':1234' testUser.location = 'room0' testServer = Server() self.testServer = s = Server() s.hostname = 'ltspserver00' s.uptime = 0 s.load = 0.0 s.os = 'linux2' s.users = {(testUser.username, testUser.server, testUser.client, testUser.display): testUser} s.connected = True s.location = u'room0' s.agentProtocol = minimock.Mock('agentProtocol', tracker=None) for f in 'getProcesses killProcesses getThumbnails Vnc sendMessage' \ ' Logout lock openURL'.split(): m = s.agentProtocol.__dict__[f] = minimock.Mock(f, tracker=None) m.mock_returns = defer.succeed( [{'username': '******', 'client': 'ltsp200', 'display': ':1234', 'mock': 1}] ) s.agentProtocol.Login = minimock.Mock('Login', tracker=None) s.agentProtocol.Login.mock_returns = defer.succeed({'port': 123}) s.agentProtocol.shutdown = minimock.Mock('shutdown', tracker=None) s.agentProtocol.shutdown.mock_returns = defer.succeed({}) sp.factory.servers = {'ltspserver00': s} sp.transport = Transport()
def _getpwall(root=None): """ Alternative implemetantion for getpwall, that use only /etc/passwd """ root = "/" if not root else root passwd = os.path.join(root, "etc/passwd") with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(":") # Generate a getpwall compatible output comps[2], comps[3] = int(comps[2]), int(comps[3]) yield pwd.struct_passwd(comps)
def os_user(monkeypatch): struct = pwd.struct_passwd(( 'lektortest', # pw_name 'lektorpass', # pw_passwd 9999, # pw_uid 9999, # pw_gid 'Lektor Test', # pw_gecos '/tmp/lektortest', # pw_dir '/bin/lektortest', # pw_shell )) monkeypatch.setattr("pwd.getpwuid", lambda id: struct) monkeypatch.setenv("USER", "lektortest") return "lektortest"
def assert_create_user_and_group(mock_check_call, mock_verify, gid_exists, uid_exists, group_name_exists, user_name_exists): mock_pwent = pwd.struct_passwd(( 'someuser', # login name 'hunter2', # password 834, # uid 835, # gid 'Some User', # user name '/home/someuser', # home directory '/bin/sh')) # login shell mock_grent = grp.struct_group(( 'users', # group name '*', # password 835, # gid ['someuser'])) # members returncode = 0 if gid_exists or uid_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS elif group_name_exists or user_name_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_NAME_EXISTS exception = subprocess.CalledProcessError( returncode=returncode, cmd='some command', output=None) mock_check_call.side_effect = [ exception if gid_exists or group_name_exists else None, exception if uid_exists or user_name_exists else None] with temporary_dir() as d: with mock.patch.object( FileSystemImageSandbox, 'get_user_and_group', return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox( os.path.join(d, 'sandbox'), user='******', sandbox_mount_point='/some/path') sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2 assert len(mock_verify.mock_calls) == 1
def test_info(self): ''' Test the user information ''' self.assertEqual(useradd.info('username-that-doesnt-exist'), {}) mock = MagicMock(return_value=pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false'))) with patch.object(pwd, 'getpwnam', mock): self.assertEqual(useradd.info('username-that-doesnt-exist')['name'], '_TEST_GROUP')
def test_gecos_missing_in_getpwuid_response(config): """No GECOS field in getpwuid response.""" cmd = InitCommand("group", config) with patch("pwd.getpwuid") as mock_pwd: # return a fack passwd struct with an empty gecos (5th parameter) mock_pwd.return_value = pwd.struct_passwd( ("user", "pass", 1, 1, "", "dir", "shell")) msg = "Author not given, and nothing in GECOS field" with pytest.raises(CommandError, match=msg): cmd.run( Namespace(name="my-charm", author=None, series="k8s", force=False))
def test_info(self): ''' Test the user information ''' self.assertEqual(useradd.info('username-that-doesnt-exist'), {}) mock = MagicMock(return_value=pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false'))) with patch.object(pwd, 'getpwnam', mock): self.assertEqual( useradd.info('username-that-doesnt-exist')['name'], '_TEST_GROUP')
def test_info(self): ''' Return user information ''' self.assertEqual(pw_user.info('name'), {}) mock = MagicMock(return_value=pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false'))) with patch.object(pwd, 'getpwnam', mock): mock = MagicMock(return_value='Group Name') with patch.object(pw_user, 'list_groups', mock): self.assertEqual(pw_user.info('name')['name'], '_TEST_GROUP')
def _getpwnam(name, root=None): """ Alternative implementation for getpwnam, that use only /etc/passwd """ root = "/" if not root else root passwd = os.path.join(root, "etc/passwd") with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(":") if comps[0] == name: # Generate a getpwnam compatible output comps[2], comps[3] = int(comps[2]), int(comps[3]) return pwd.struct_passwd(comps) raise KeyError
def test_format_info(self): ''' Tests the formatting of returned user information ''' data = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon', '/var/virusmails', '/usr/bin/false')) ret = { 'shell': '/usr/bin/false', 'name': '_TEST_GROUP', 'gid': 83, 'groups': ['_TEST_GROUP'], 'home': '/var/virusmails', 'fullname': 'AMaViS Daemon', 'uid': 83 } with patch('salt.modules.mac_user.list_groups', MagicMock(return_value=['_TEST_GROUP'])): self.assertEqual(mac_user._format_info(data), ret)
def _mocks_for_parse_cli_args(): with mock.patch('fs_image.nspawn_in_subvol.args.pwd.getpwnam' ) as getpwnam_mock, mock.patch( 'fs_image.nspawn_in_subvol.args.find_built_subvol' ) as find_built_subvol_mock: getpwnam_mock.side_effect = [ struct_passwd([ 'pw_name', 'pw_passwd', 123, 123, 'pw_gecos', '/test/home', '/test/sh', ]) ] find_built_subvol_mock.side_effect = [None] yield
def testFindCredentialsFile_PortageUsername(self): """Checks that we can locate the JSON files under $PORTAGE_USERNAME.""" copy_environ = os.environ.copy() copy_environ["HOME"] = "/nonexistent" copy_environ["PORTAGE_USERNAME"] = "******" fakeuser_homedir = os.path.join(TESTDATA_PATH, "androidbuild") fakeuser_pwent = pwd.struct_passwd(("fakeuser", "x", 1234, 1234, "Fake User", fakeuser_homedir, "/bin/sh")) service_account_name = "test_creds_authorized_user.json" with mock.patch.dict(os.environ, copy_environ), mock.patch.object(pwd, "getpwnam") as mock_getpwnam: mock_getpwnam.return_value = fakeuser_pwent json_path = androidbuild.FindCredentialsFile(homedir_json_credentials_path=service_account_name) mock_getpwnam.assert_called_once_with("fakeuser") self.assertEqual(json_path, os.path.join(fakeuser_homedir, service_account_name))
def test_info(self): """ Return user information """ self.assertEqual(pw_user.info("name"), {}) mock = MagicMock(return_value=pwd.struct_passwd(( "_TEST_GROUP", "*", 83, 83, "AMaViS Daemon", "/var/virusmails", "/usr/bin/false", ))) with patch.object(pwd, "getpwnam", mock): mock = MagicMock(return_value="Group Name") with patch.object(pw_user, "list_groups", mock): self.assertEqual(pw_user.info("name")["name"], "_TEST_GROUP")
def test_info(self): """ Tests the return of user information """ mock_pwnam = pwd.struct_passwd( ("test", "*", 0, 0, "TEST USER", "/var/test", "/bin/bash")) ret = { "shell": "/bin/bash", "name": "test", "gid": 0, "groups": ["_TEST_GROUP"], "home": "/var/test", "fullname": "TEST USER", "uid": 0, } with patch("pwd.getpwnam", MagicMock(return_value=mock_pwnam)), patch( "salt.modules.mac_user.list_groups", MagicMock(return_value=["_TEST_GROUP"])): self.assertEqual(mac_user.info("root"), ret)
def test_info(self): """ Test the user information """ self.assertEqual(useradd.info("username-that-does-not-exist"), {}) mock = MagicMock(return_value=pwd.struct_passwd(( "_TEST_GROUP", "*", 83, 83, "AMaViS Daemon", "/var/virusmails", "/usr/bin/false", ))) with patch.object(pwd, "getpwnam", mock): self.assertEqual( useradd.info("username-that-does-not-exist")["name"], "_TEST_GROUP")
def test_check_environ_getpwuid(self): util._environ_checked = 0 os.environ.pop('HOME', None) import pwd # only set pw_dir field, other fields are not used result = pwd.struct_passwd((None, None, None, None, None, '/home/distutils', None)) with mock.patch.object(pwd, 'getpwuid', return_value=result): check_environ() self.assertEqual(os.environ['HOME'], '/home/distutils') util._environ_checked = 0 os.environ.pop('HOME', None) # bpo-10496: Catch pwd.getpwuid() error with mock.patch.object(pwd, 'getpwuid', side_effect=KeyError): check_environ() self.assertNotIn('HOME', os.environ)
def os_user(monkeypatch): if os.name == 'nt': import getpass monkeypatch.setattr('getpass.getuser', lambda: 'Lektor Test') return "lektortest" # we disable pylint, because there is no such # modules on windows & it's false positive import pwd # pylint: disable=import-error struct = pwd.struct_passwd(( 'lektortest', # pw_name 'lektorpass', # pw_passwd 9999, # pw_uid 9999, # pw_gid 'Lektor Test', # pw_gecos '/tmp/lektortest', # pw_dir '/bin/lektortest', # pw_shell )) monkeypatch.setattr("pwd.getpwuid", lambda id: struct) monkeypatch.setenv("USER", "lektortest") return "lektortest"
def assert_create_user_and_group( mock_check_call, mock_verify, gid_exists, uid_exists, group_name_exists, user_name_exists ): mock_pwent = pwd.struct_passwd( ( "someuser", # login name "hunter2", # password 834, # uid 835, # gid "Some User", # user name "/home/someuser", # home directory "/bin/sh", ) ) # login shell mock_grent = grp.struct_group(("users", "*", 835, ["someuser"])) # group name # password # gid # members returncode = 0 if gid_exists or uid_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_ID_EXISTS elif group_name_exists or user_name_exists: returncode = FileSystemImageSandbox._USER_OR_GROUP_NAME_EXISTS exception = subprocess.CalledProcessError(returncode=returncode, cmd="some command", output=None) mock_check_call.side_effect = [ exception if gid_exists or group_name_exists else None, exception if uid_exists or user_name_exists else None, ] with temporary_dir() as d: with mock.patch.object(FileSystemImageSandbox, "get_user_and_group", return_value=(mock_pwent, mock_grent)): sandbox = FileSystemImageSandbox( os.path.join(d, "sandbox"), user="******", sandbox_mount_point="/some/path" ) sandbox._create_user_and_group_in_taskfs() assert len(mock_check_call.mock_calls) == 2 assert len(mock_verify.mock_calls) == 1
def get_user_map(self, key_by_uid=False): """ Returns dictionary where keys are remote usernames and values are pwd.struct_passwd objects from the standard pwd module key_by_uid=True will use the integer uid as the returned dictionary's keys instead of the user's login name """ etc_passwd = self.ssh.remote_file('/etc/passwd', 'r') users = [l.strip().split(':') for l in etc_passwd.readlines()] etc_passwd.close() user_map = {} for user in users: name, passwd, uid, gid, gecos, home, shell = user uid = int(uid) gid = int(gid) key = name if key_by_uid: key = uid user_map[key] = pwd.struct_passwd([name, passwd, uid, gid, gecos, home, shell]) return user_map
def UserAdd_Passwd(User, PasswdFile='/etc/passwd'): # 1. temporary file fd, TempPasswdFile = mkstemp(prefix='passwd', dir='/tmp') # 2. get minimum available user and group IDs UserID = min( AllowedUserIDs.difference(GetUserIDs())) GroupIDs = AllowedGroupIDs.difference(GetGroupIDs()) GroupID = min(GroupIDs) if GroupID != UserID and UserID in GroupIDs: GroupID = UserID # 3. prepare passwd pw_user = pwd.struct_passwd( sequence = ( User, 'x', UserID, GroupID, '', join('/home', User), '/bin/bash')) # 4. generate temporary passwd file pwall = pwd.getpwall() pwall.append(pw_user) pwall.sort(lambda a, b: cmp(a.pw_uid, b.pw_uid)) with fdopen(fd, 'w+') as fh: for pw in pwall: fh.write(':'.join(map(lambda x: str(x), pw))+'\n') # 5. activate new passwd file rename(TempPasswdFile, PasswdFile) chown(PasswdFile, 0, 0) chmod(PasswdFile, 0644)
def mgetpwnam(name): s = pwmaps.get(name) if s is not None: return pwd.struct_passwd(s) raise KeyError(name)
def process(user_pks, pwall, spwall): '''Generate the passwd, shadow, and sudo fragments for IAM users. :param user_pks: Mapping of username (``str``) to public keys (``list`` of ``str``) retrieved from IAM. :type user_pks: dict :param pwall: A list of ``pwd.struct_passwd`` including all password entries found by NSS. Should include those users identified by libnss-extrausers. :type pwall: list ''' username_index = dict( (user.pw_name, user) for user in pwall if is_iam_user(user)) susername_index = dict( (user[0], user) for user in spwall if user[0] in username_index) uid_index = dict((int(user.pw_uid), user) for user in pwall) next_uid = MIN_USER_UID passwd, shadow, sudo = [], [], [] # Users that have been removed from IAM will keep their UIDs around in the # event that user IDs have. In practice, I don't anticipate this behavior # to be problematic since there is an abundance of UIDs available in the # default configuration UID range for all but the largest admin user pools. for old_username in set(username_index.keys()) - set(user_pks.keys()): passwd.append(username_index[old_username]) shadow.append(susername_index[old_username]) for username in user_pks.keys(): # Find the next gap in user IDs while next_uid in uid_index: next_uid += 1 if next_uid > MAX_USER_UID: LOG.error("User limit reached! Skipping user %s", username) break sudo.append('{} ALL=(ALL) NOPASSWD:ALL'.format(username)) if username in username_index: passwd.append(username_index[username]) shadow.append(susername_index[username]) else: passwd.append(pwd.struct_passwd(( username, 'x', next_uid, next_uid, 'IAM-USER', '/home/{}'.format(username), '/bin/bash', ))) shadow.append(spwd.struct_spwd(( username, '*', (datetime.datetime.utcnow() - EPOCH).days, 0, 99999, 7, -1, -1, -1, ))) next_uid += 1 sudo.sort() sudo.insert(0, '# Created by {} on {}'.format( __file__, datetime.datetime.utcnow().ctime())) return ( sorted(passwd_to_line(x) for x in passwd), sorted(shadow_to_line(x) for x in shadow), [x.encode('utf-8') for x in sudo] )
def parseRecords(self): passwd_info = self.results[0].split(':') passwd_info[2] = int(passwd_info[2]) passwd_info[3] = int(passwd_info[3]) self.passwd = struct_passwd(passwd_info)