class InstanceProcessingTest(unittest.TestCase): pvwa_integration_class = PvwaIntegration() def test_delete_instance(self): print('test_delete_instance') ec2_class = EC2Details() ec2_resource = boto3.resource('ec2') linux, windows = generate_ec2(ec2_resource) req = Mock() req.status_code = 200 dynamodb = boto3.resource('dynamodb') table = dynamo_create_instances_table(dynamodb) dynamo_put_ec2_object(dynamodb, linux) @patch('requests.get', return_value='', status_code='') @patch('pvwa_integration.PvwaIntegration.call_rest_api_delete', return_value=req) def invoke(*args): with patch('pvwa_api_calls.retrieve_account_id_from_account_name') as mp: mp.return_value = '1231' deleted_instance = instance_processing.delete_instance(windows, 1,ec2_class.sp_class, ec2_class.instance_data, ec2_class.details) failed_instance = instance_processing.delete_instance(linux, 2, ec2_class.sp_class, ec2_class.instance_data, ec2_class.details) return deleted_instance, failed_instance return_windows, return_linux = invoke('a', 'b') self.assertTrue(return_windows) self.assertTrue(return_linux) table.delete() def test_get_instance_password_data(self): print('test_get_instance_password_data') ec2_resource = boto3.resource('ec2') linux, windows = generate_ec2(ec2_resource) with patch('boto.ec2.connection.EC2Connection.get_password_data', return_value='StrongPassword'): #### to improve respone = instance_processing.get_instance_password_data(windows, MOTO_ACCOUNT, 'eu-west-2', MOTO_ACCOUNT) self.assertEqual(None, respone) def test_create_instance_windows(self): #### split this module!!!! print('test_create_instance_windows') ec2_resource = boto3.resource('ec2') linux, windows = generate_ec2(ec2_resource) ec2_class = EC2Details() response = func_create_instance(ec2_class, windows) self.assertTrue(response) def test_create_instance_linux(self): print('test_create_instance_linux') ec2_resource = boto3.resource('ec2') linux, windows = generate_ec2(ec2_resource) ec2_class = EC2Details() ec2_class.set_platform('linix') ec2_class.set_image_description('Linix') response = func_create_instance(ec2_class, windows) self.assertTrue(response) def test_get_os_distribution_user(self): user = instance_processing.get_os_distribution_user('centos') self.assertEqual(user, 'centos') user = instance_processing.get_os_distribution_user('ubuntu') self.assertEqual(user, 'ubuntu') user = instance_processing.get_os_distribution_user('debian') self.assertEqual(user, 'admin') user = instance_processing.get_os_distribution_user('opensuse') self.assertEqual(user, 'root') user = instance_processing.get_os_distribution_user('fedora') self.assertEqual(user, 'fedora') user = instance_processing.get_os_distribution_user('Lemon') self.assertEqual(user, 'ec2-user')
import requests import json from pvwa_integration import PvwaIntegration from log_mechanism import LogMechanism DEBUG_LEVEL_DEBUG = 'debug' # Outputs all information DEFAULT_HEADER = {"content-type": "application/json"} pvwa_integration_class = PvwaIntegration() logger = LogMechanism() def create_account_on_vault(session, account_name, account_password, store_parameters_class, platform_id, address, instance_id, username, safe_name): logger.trace(session, account_name, store_parameters_class, platform_id, address, instance_id, username, safe_name, caller_name='create_account_on_vault') logger.info(f'Creating account in vault for {instance_id}') header = DEFAULT_HEADER header.update({"Authorization": session}) url = f"{store_parameters_class.pvwa_url}/WebServices/PIMServices.svc/Account" data = { "account": { "safe": safe_name, "platformID": platform_id, "address": address, "accountName": account_name, "password": account_password, "username": username, "disableAutoMgmt": "false" } }
def lambda_handler(event, context): logger.trace(event, context, caller_name='lambda_handler') try: physical_resource_id = str(uuid.uuid4()) if 'PhysicalResourceId' in event: physical_resource_id = event['PhysicalResourceId'] # only deleting the vault_pass from parameter store if event['RequestType'] == 'Delete': aob_mode = get_aob_mode() logger.info('Delete request received') delete_params = delete_password_from_param_store(aob_mode) if not delete_params: return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to delete 'AOB_Vault_Pass' from parameter store, see detailed error in logs", {}, physical_resource_id) delete_sessions_table() return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) if event['RequestType'] == 'Create': logger.info('Create request received') request_unix_cpm_name = event['ResourceProperties']['CPMUnix'] request_windows_cpm_name = event['ResourceProperties'][ 'CPMWindows'] request_username = event['ResourceProperties']['Username'] request_unix_safe_name = event['ResourceProperties'][ 'UnixSafeName'] request_windows_safe_name = event['ResourceProperties'][ 'WindowsSafeName'] request_pvwa_ip = event['ResourceProperties']['PVWAIP'] request_password = event['ResourceProperties']['Password'] request_key_pair_safe = event['ResourceProperties']['KeyPairSafe'] request_key_pair_name = event['ResourceProperties']['KeyPairName'] request_aws_region_name = event['ResourceProperties'][ 'AWSRegionName'] request_aws_account_id = event['ResourceProperties'][ 'AWSAccountId'] request_s3_bucket_name = event['ResourceProperties'][ 'S3BucketName'] request_verification_key_name = event['ResourceProperties'][ 'PVWAVerificationKeyFileName'] aob_mode = event['ResourceProperties']['Environment'] logger.info('Adding AOB_Vault_Pass to parameter store', DEBUG_LEVEL_DEBUG) is_password_saved = add_param_to_parameter_store( request_password, "AOB_Vault_Pass", "Vault Password") if not is_password_saved: # if password failed to be saved return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to create Vault user's password in Parameter Store", {}, physical_resource_id) if request_s3_bucket_name == '' and request_verification_key_name != '': raise Exception( 'Verification Key cannot be empty if S3 Bucket is provided' ) elif request_s3_bucket_name != '' and request_verification_key_name == '': raise Exception( 'S3 Bucket cannot be empty if Verification Key is provided' ) else: logger.info('Adding AOB_mode to parameter store', DEBUG_LEVEL_DEBUG) is_aob_mode_saved = add_param_to_parameter_store(aob_mode, 'AOB_mode', 'Dictates if the solution will work in POC(no SSL) or ' \ 'Production(with SSL) mode') if not is_aob_mode_saved: # if password failed to be saved return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to create AOB_mode parameter in Parameter Store", {}, physical_resource_id) if aob_mode == 'Production': logger.info('Adding verification key to Parameter Store', DEBUG_LEVEL_DEBUG) is_verification_key_saved = save_verification_key_to_param_store( request_s3_bucket_name, request_verification_key_name) if not is_verification_key_saved: # if password failed to be saved return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to create PVWA Verification Key in Parameter Store", {}, physical_resource_id) pvwa_integration_class = PvwaIntegration(IS_SAFE_HANDLER, aob_mode) pvwa_url = f"https://{request_pvwa_ip}/PasswordVault" pvwa_session_id = pvwa_integration_class.logon_pvwa( request_username, request_password, pvwa_url, "1") if not pvwa_session_id: return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to connect to PVWA, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_unix_safe_name, request_unix_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send( event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_unix_safe_name}, see detailed error in logs", {}, physical_resource_id) is_safe_created = create_safe(pvwa_integration_class, request_windows_safe_name, request_windows_cpm_name, request_pvwa_ip, pvwa_session_id, 1) if not is_safe_created: return cfnresponse.send( event, context, cfnresponse.FAILED, f"Failed to create the Safe {request_windows_safe_name}, see detailed error in logs", {}, physical_resource_id) if not create_session_table(): return cfnresponse.send( event, context, cfnresponse.FAILED, "Failed to create 'Sessions' table in DynamoDB, see detailed error in logs", {}, physical_resource_id) # Creating KeyPair Safe is_safe_created = create_safe(pvwa_integration_class, request_key_pair_safe, "", request_pvwa_ip, pvwa_session_id) if not is_safe_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create the Key Pairs safe: {request_key_pair_safe}, " \ "see detailed error in logs", {}, physical_resource_id) # key pair is optional parameter if not request_key_pair_name: logger.info( "Key Pair name parameter is empty, the solution will not create a new Key Pair" ) return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) aws_key_pair = create_new_key_pair_on_aws(request_key_pair_name) if aws_key_pair is False: # Account already exist, no need to create it, can't insert it to the vault return cfnresponse.send( event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in AWS", {}, physical_resource_id) if aws_key_pair is True: return cfnresponse.send( event, context, cfnresponse.FAILED, f"Key Pair {request_key_pair_name} already exists in AWS", {}, physical_resource_id) # Create the key pair account on KeyPairs vault is_aws_account_created = create_key_pair_in_vault( pvwa_integration_class, pvwa_session_id, request_key_pair_name, aws_key_pair, request_pvwa_ip, request_key_pair_safe, request_aws_account_id, request_aws_region_name) if not is_aws_account_created: return cfnresponse.send(event, context, cfnresponse.FAILED, f"Failed to create Key Pair {request_key_pair_name} in safe " \ f"{request_key_pair_safe}. see detailed error in logs", {}, physical_resource_id) return cfnresponse.send(event, context, cfnresponse.SUCCESS, None, {}, physical_resource_id) except Exception as e: logger.error(f"Exception occurred:{str(e)}:") return cfnresponse.send(event, context, cfnresponse.FAILED, f"Exception occurred: {str(e)}", {}) finally: if 'pvwa_session_id' in locals(): # pvwa_session_id has been declared if pvwa_session_id: # Logging off the session in case of successful logon pvwa_integration_class.logoff_pvwa(pvwa_url, pvwa_session_id)