def add_user(self, username, encrypted_password, account_expiration): try: expiration_date = (account_expiration + timedelta(days=1)).strftime(DATE_FORMAT) logger.verbose("Adding user {0} with expiration date {1}".format( username, expiration_date)) self.os_util.useradd(username, expiration_date, REMOTE_ACCESS_ACCOUNT_COMMENT) except Exception as e: raise RemoteAccessError("Error adding user {0}. {1}".format( username, ustr(e))) try: prv_key = os.path.join(conf.get_lib_dir(), TRANSPORT_PRIVATE_CERT) pwd = self.cryptUtil.decrypt_secret(encrypted_password, prv_key) self.os_util.chpasswd(username, pwd, conf.get_password_cryptid(), conf.get_password_crypt_salt_len()) self.os_util.conf_sudoer(username) logger.info( "User '{0}' added successfully with expiration in {1}".format( username, expiration_date)) except Exception as e: error = "Error adding user {0}. {1} ".format(username, str(e)) try: self.handle_failed_create(username) error += "cleanup successful" except RemoteAccessError as rae: error += "and error cleaning up {0}".format(str(rae)) raise RemoteAccessError( "Error adding user {0} cleanup successful".format(username), ustr(e))
def handle_failed_create(self, username): try: self.delete_user(username) except Exception as e: raise RemoteAccessError( "Failed to clean up after account creation for {0}.".format( username), e)
def test_remote_access_handler_run_error(self, _): mock_protocol = WireProtocol("foo.bar") mock_protocol.get_incarnation = MagicMock( side_effect=RemoteAccessError("foobar!")) rah = RemoteAccessHandler(mock_protocol) rah.os_util = MockOSUtil() rah.run() print(TestRemoteAccessHandler.eventing_data) check_message = "foobar!" self.assertTrue( check_message in TestRemoteAccessHandler.eventing_data[4], "expected message {0} not found in {1}".format( check_message, TestRemoteAccessHandler.eventing_data[4])) self.assertEqual(False, TestRemoteAccessHandler.eventing_data[2], "is_success is true")
class TestRemoteAccessHandler(AgentTestCase): eventing_data = [()] def setUp(self): super(TestRemoteAccessHandler, self).setUp() del info_messages[:] del error_messages[:] for data in TestRemoteAccessHandler.eventing_data: del data # add_user tests @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_add_user(self, _1, _2, _3): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "******" tstuser = "******" expiration_date = datetime.utcnow() + timedelta(days=1) pwd = tstpassword rah.add_user(tstuser, pwd, expiration_date) users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) actual_user = users[tstuser] expected_expiration = (expiration_date + timedelta(days=1)).strftime("%Y-%m-%d") self.assertEqual(actual_user[7], expected_expiration) self.assertEqual(actual_user[4], "JIT_Account") self.assertEqual(0, len(error_messages)) self.assertEqual(1, len(info_messages)) self.assertEqual( info_messages[0], "User '{0}' added successfully with expiration in {1}".format( tstuser, expected_expiration)) @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_add_user_bad_creation_data(self, _1, _2, _3): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "******" tstuser = "" expiration = datetime.utcnow() + timedelta(days=1) pwd = tstpassword error = "Error adding user {0}. test exception for bad username".format( tstuser) self.assertRaisesRegex(RemoteAccessError, error, rah.add_user, tstuser, pwd, expiration) self.assertEqual(0, len(rah.os_util.get_users())) self.assertEqual(0, len(error_messages)) self.assertEqual(0, len(info_messages)) @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="") def test_add_user_bad_password_data(self, _1, _2, _3): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "" tstuser = "******" expiration = datetime.utcnow() + timedelta(days=1) pwd = tstpassword error = "Error adding user {0} cleanup successful\nInner error: test exception for bad password".format( tstuser) self.assertRaisesRegex(RemoteAccessError, error, rah.add_user, tstuser, pwd, expiration) self.assertEqual(0, len(rah.os_util.get_users())) self.assertEqual(0, len(error_messages)) self.assertEqual(1, len(info_messages)) self.assertEqual("User deleted {0}".format(tstuser), info_messages[0]) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_add_user_already_existing(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "******" tstuser = "******" expiration_date = datetime.utcnow() + timedelta(days=1) pwd = tstpassword rah.add_user(tstuser, pwd, expiration_date) users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) self.assertEqual(1, len(users.keys())) actual_user = users[tstuser] self.assertEqual(actual_user[7], (expiration_date + timedelta(days=1)).strftime("%Y-%m-%d")) # add the new duplicate user, ensure it's not created and does not overwrite the existing user. # this does not test the user add function as that's mocked, it tests processing skips the remaining # calls after the initial failure new_user_expiration = datetime.utcnow() + timedelta(days=5) self.assertRaises(RemoteAccessError, rah.add_user, tstuser, pwd, new_user_expiration) # refresh users users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue( tstuser in users, "{0} missing from users after dup user attempted".format(tstuser)) self.assertEqual(1, len(users.keys())) actual_user = users[tstuser] self.assertEqual(actual_user[7], (expiration_date + timedelta(days=1)).strftime("%Y-%m-%d")) # delete_user tests @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_delete_user(self, _1, _2, _3): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "******" tstuser = "******" expiration_date = datetime.utcnow() + timedelta(days=1) expected_expiration = (expiration_date + timedelta(days=1)).strftime("%Y-%m-%d") pwd = tstpassword rah.add_user(tstuser, pwd, expiration_date) users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) rah.delete_user(tstuser) # refresh users users = get_user_dictionary(rah.os_util.get_users()) self.assertFalse(tstuser in users) self.assertEqual(0, len(error_messages)) self.assertEqual(2, len(info_messages)) self.assertEqual( "User '{0}' added successfully with expiration in {1}".format( tstuser, expected_expiration), info_messages[0]) self.assertEqual("User deleted {0}".format(tstuser), info_messages[1]) def test_handle_failed_create_with_bad_data(self): mock_os_util = MockOSUtil() testusr = "******" mock_os_util.all_users[testusr] = (testusr, None, None, None, None, None, None, None) rah = RemoteAccessHandler() rah.os_util = mock_os_util self.assertRaises(RemoteAccessError, rah.handle_failed_create, "") users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(1, len(users.keys())) self.assertTrue(testusr in users, "Expected user {0} missing".format(testusr)) @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) def test_delete_user_does_not_exist(self, _1, _2): mock_os_util = MockOSUtil() testusr = "******" mock_os_util.all_users[testusr] = (testusr, None, None, None, None, None, None, None) rah = RemoteAccessHandler() rah.os_util = mock_os_util testuser = "******" error = "Failed to clean up after account creation for {0}.\n" \ "Inner error: test exception, user does not exist to delete".format(testuser) self.assertRaisesRegex(RemoteAccessError, error, rah.handle_failed_create, testuser) users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(1, len(users.keys())) self.assertTrue(testusr in users, "Expected user {0} missing".format(testusr)) self.assertEqual(0, len(error_messages)) self.assertEqual(0, len(info_messages)) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_new_user(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_single_account.xml') remote_access = RemoteAccess(data_str) tstuser = remote_access.user_list.users[0].name expiration_date = datetime.utcnow() + timedelta(days=1) expiration = expiration_date.strftime("%a, %d %b %Y %H:%M:%S ") + "UTC" remote_access.user_list.users[0].expiration = expiration rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) actual_user = users[tstuser] expected_expiration = (expiration_date + timedelta(days=1)).strftime("%Y-%m-%d") self.assertEqual(actual_user[7], expected_expiration) self.assertEqual(actual_user[4], "JIT_Account") def test_do_not_add_expired_user(self): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_single_account.xml') remote_access = RemoteAccess(data_str) expiration = (datetime.utcnow() - timedelta(days=2) ).strftime("%a, %d %b %Y %H:%M:%S ") + "UTC" remote_access.user_list.users[0].expiration = expiration rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertFalse("testAccount" in users) @patch('azurelinuxagent.common.logger.Logger.info', side_effect=log_info) @patch('azurelinuxagent.common.logger.Logger.error', side_effect=log_error) def test_error_add_user(self, _1, _2): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstuser = "******" expiration = datetime.utcnow() + timedelta(days=1) pwd = "bad password" error = "Error adding user foobar cleanup successful\n" \ "Inner error: \[CryptError\] Error decoding secret\n" \ "Inner error: Incorrect padding".format(tstuser) self.assertRaisesRegex(RemoteAccessError, error, rah.add_user, tstuser, pwd, expiration) users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(0, len(users)) self.assertEqual(0, len(error_messages)) self.assertEqual(1, len(info_messages)) self.assertEqual("User deleted {0}".format(tstuser), info_messages[0]) def test_handle_remote_access_no_users(self): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_no_accounts.xml') remote_access = RemoteAccess(data_str) rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(0, len(users.keys())) def test_handle_remote_access_validate_jit_user_valid(self): rah = RemoteAccessHandler() comment = "JIT_Account" result = rah.validate_jit_user(comment) self.assertTrue( result, "Did not identify '{0}' as a JIT_Account".format(comment)) def test_handle_remote_access_validate_jit_user_invalid(self): rah = RemoteAccessHandler() test_users = ["John Doe", None, "", " "] failed_results = "" for user in test_users: if rah.validate_jit_user(user): failed_results += "incorrectly identified '{0} as a JIT_Account'. ".format( user) if len(failed_results) > 0: self.fail(failed_results) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_multiple_users(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_two_accounts.xml') remote_access = RemoteAccess(data_str) testusers = [] count = 0 while count < 2: user = remote_access.user_list.users[count].name expiration_date = datetime.utcnow() + timedelta(days=count + 1) expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" remote_access.user_list.users[count].expiration = expiration testusers.append(user) count += 1 rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(testusers[0] in users, "{0} missing from users".format(testusers[0])) self.assertTrue(testusers[1] in users, "{0} missing from users".format(testusers[1])) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") # max fabric supports in the Goal State def test_handle_remote_access_ten_users(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(10, len(users.keys())) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_user_removed(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(10, len(users.keys())) del rah.remote_access.user_list.users[:] self.assertEqual(10, len(users.keys())) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_bad_data_and_good_data(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) if count is 2: user.name = "" expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertEqual(9, len(users.keys())) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_deleted_user_readded(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_single_account.xml') remote_access = RemoteAccess(data_str) tstuser = remote_access.user_list.users[0].name expiration_date = datetime.utcnow() + timedelta(days=1) expiration = expiration_date.strftime("%a, %d %b %Y %H:%M:%S ") + "UTC" remote_access.user_list.users[0].expiration = expiration rah.remote_access = remote_access rah.handle_remote_access() users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) os_util = rah.os_util os_util.__class__ = MockOSUtil os_util.all_users.clear() # refresh users users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser not in users) rah.handle_remote_access() # refresh users users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") @patch('azurelinuxagent.common.osutil.get_osutil', return_value=MockOSUtil()) @patch('azurelinuxagent.common.protocol.util.ProtocolUtil.get_protocol', return_value=WireProtocol("12.34.56.78")) @patch('azurelinuxagent.common.protocol.wire.WireProtocol.get_incarnation', return_value="1") @patch('azurelinuxagent.common.protocol.wire.WireClient.get_remote_access', return_value="asdf") def test_remote_access_handler_run_bad_data(self, _1, _2, _3, _4, _5): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() tstpassword = "******" tstuser = "******" expiration_date = datetime.utcnow() + timedelta(days=1) pwd = tstpassword rah.add_user(tstuser, pwd, expiration_date) users = get_user_dictionary(rah.os_util.get_users()) self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) rah.run() self.assertTrue(tstuser in users, "{0} missing from users".format(tstuser)) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_multiple_users_one_removed(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(10, len(users)) # now remove the user from RemoteAccess deleted_user = rah.remote_access.user_list.users[3] del rah.remote_access.user_list.users[3] rah.handle_remote_access() users = rah.os_util.get_users() self.assertTrue(deleted_user not in users, "{0} still in users".format(deleted_user)) self.assertEqual(9, len(users)) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_multiple_users_null_remote_access(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(10, len(users)) # now remove the user from RemoteAccess rah.remote_access = None rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(0, len(users)) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_multiple_users_error_with_null_remote_access( self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(10, len(users)) # now remove the user from RemoteAccess rah.remote_access = None rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(0, len(users)) def test_remove_user_error(self): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() error = "Failed to delete user {0}\nInner error: test exception, bad data".format( "") self.assertRaisesRegex(RemoteAccessError, error, rah.remove_user, "") def test_remove_user_not_exists(self): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() user = "******" error = "Failed to delete user {0}\n" \ "Inner error: test exception, user does not exist to delete".format(user) self.assertRaisesRegex(RemoteAccessError, error, rah.remove_user, user) @patch('azurelinuxagent.common.utils.cryptutil.CryptUtil.decrypt_secret', return_value="]aPPEv}uNg1FPnl?") def test_handle_remote_access_remove_and_add(self, _): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() data_str = load_data('wire/remote_access_10_accounts.xml') remote_access = RemoteAccess(data_str) count = 0 for user in remote_access.user_list.users: count += 1 user.name = "tstuser{0}".format(count) expiration_date = datetime.utcnow() + timedelta(days=count) user.expiration = expiration_date.strftime( "%a, %d %b %Y %H:%M:%S ") + "UTC" rah.remote_access = remote_access rah.handle_remote_access() users = rah.os_util.get_users() self.assertEqual(10, len(users)) # now remove the user from RemoteAccess new_user = "******" deleted_user = rah.remote_access.user_list.users[3] rah.remote_access.user_list.users[3].name = new_user rah.handle_remote_access() users = rah.os_util.get_users() self.assertTrue(deleted_user not in users, "{0} still in users".format(deleted_user)) self.assertTrue(new_user in [u[0] for u in users], "user {0} not in users".format(new_user)) self.assertEqual(10, len(users)) @patch('azurelinuxagent.ga.remoteaccess.add_event', side_effect=mock_add_event) @patch('azurelinuxagent.common.protocol.util.ProtocolUtil.get_protocol', side_effect=RemoteAccessError("foobar!")) def test_remote_access_handler_run_error(self, _1, _2): rah = RemoteAccessHandler() rah.os_util = MockOSUtil() rah.run() print(TestRemoteAccessHandler.eventing_data) check_message = "foobar!" self.assertTrue( check_message in TestRemoteAccessHandler.eventing_data[4], "expected message {0} not found in {1}".format( check_message, TestRemoteAccessHandler.eventing_data[4])) self.assertEqual(False, TestRemoteAccessHandler.eventing_data[2], "is_success is true")
def remove_user(self, username): try: self.delete_user(username) except Exception as e: raise RemoteAccessError( "Failed to delete user {0}".format(username), e)