Below Lambda script is supposed to add AWS account to Trend Micro DSM (which is also in an AWS account). Endpoints are set up between the accounts allowing communication. It's failing with 400, it cannot add the account:
Logs:
2020-11-06T13:28:37.612+00:00 START RequestId: 074eff37-00cc-480b-affb-2e28f0e2a8af Version: $LATEST
2020-11-06T13:28:42.034+00:00 Assuming role: arn:aws:iam::414025531860:role/pcs-pipeline-role
2020-11-06T13:28:42.575+00:00 Assumed successfully!
2020-11-06T13:28:42.575+00:00 /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the get() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.get() function instead.
2020-11-06T13:28:42.575+00:00 DeprecationWarning
2020-11-06T13:28:44.927+00:00 Allowing public IP for executing Lambda, 34.247.33.230/32, to temporarily call Trend DSM
2020-11-06T13:28:45.070+00:00 DONE!
2020-11-06T13:28:50.076+00:00 Logging into Trend DSM as Org tenant
2020-11-06T13:28:50.076+00:00 /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.post() function instead.
2020-11-06T13:28:50.076+00:00 DeprecationWarning
2020-11-06T13:28:50.233+00:00 /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'gdc-pcs-tre-dsmelb-fbsp95snsrjw-2115947587.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.233+00:00 InsecureRequestWarning,
2020-11-06T13:28:50.319+00:00 200
2020-11-06T13:28:50.319+00:00 Logged in!
2020-11-06T13:28:50.319+00:00 Getting cloud accounts for Trend org tenant...
2020-11-06T13:28:50.319+00:00 /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the get() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.get() function instead.
2020-11-06T13:28:50.319+00:00 DeprecationWarning
2020-11-06T13:28:50.493+00:00 /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.493+00:00 InsecureRequestWarning,
2020-11-06T13:28:50.528+00:00 Retrieved!
2020-11-06T13:28:50.528+00:00 Checking if tenant account already in Trend DSM Org Tenant
2020-11-06T13:28:50.528+00:00 Not found
2020-11-06T13:28:50.528+00:00 Adding 11994547362545 as Trend cloud account...
2020-11-06T13:28:50.528+00:00 /var/runtime/botocore/vendored/requests/api.py:72: DeprecationWarning: You are using the post() function from 'botocore.vendored.requests'. This dependency was removed from Botocore and will be removed from Lambda after 2021/01/30. https://aws.amazon.com/blogs/developer/removing-the-vendored-version-of-requests-from-botocore/. Install the requests package, 'import requests' directly, and use the requests.post() function instead.
2020-11-06T13:28:50.528+00:00 DeprecationWarning
2020-11-06T13:28:50.693+00:00 /var/runtime/urllib3/connectionpool.py:988: InsecureRequestWarning: Unverified HTTPS request is being made to host 'xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
2020-11-06T13:28:50.693+00:00 InsecureRequestWarning,
2020-11-06T13:28:51.373+00:00 400
2020-11-06T13:28:51.373+00:00 Failed!
`No lines are selected.
import os
import json
import time
import boto3
from botocore.vendored import requests
import layer as utils
def handler(event, context):
try:
# Extract the Job ID
job_id = event['CodePipeline.job']['id']
event_data = utils.parse_event_data(event)
print(event_data)
trend_micro_deep_security_integration(event_data['TenantAccountId'], event_data['Organisation'])
utils.put_job_success(job_id)
except Exception as err:
utils.put_job_failure(job_id, str(err))
def trend_micro_deep_security_integration(tenant_account_id, tenant_organisation):
#retrieve trend tenant password from ssm param store
client = boto3.client('ssm', region_name='eu-west-1')
TREND_TENANT_PASSWORD = client.get_parameter(Name='TrendTenantPassword', WithDecryption=True)['Parameter']['Value']
#assume role in aws provider account for trend dsm
sts_client = boto3.client('sts')
trend_account_role_arn = 'arn:aws:iam::654533721364:role/{}'.format(os.environ['DEPLOY_ROLE'])
TREND_SESSION = utils.get_sts_session(sts_client, trend_account_role_arn)
#determine public ip of executing lambda function
public_ip = requests.get('https://checkip.amazonaws.com').text.rstrip()
global LAMBDA_PUBLIC_IP
LAMBDA_PUBLIC_IP = '{}/32'.format(public_ip)
#add lambda public ip as temp ingress cidr ip
SG_ID = 'sg-01ct911f8ch7d2ed5'
changed = authorize_trend_elb_ingress(TREND_SESSION, SG_ID)
if changed:
time.sleep(5)
org_name = tenant_organisation.upper().strip()
#log into trend dsm
payload = get_trend_auth_payload_json(org_name, TREND_TENANT_PASSWORD)
cookie = get_trend_org_cookie(org_name, payload)
# check and if required, add tenant account into their trend tenant for the assigned org
dsm_account_names = get_trend_org_cloud_accounts(cookie)
if not is_account_in_trend_dsm(dsm_account_names, tenant_account_id):
success = add_trend_cloud_account(cookie, tenant_account_id)
else:
success = True
# always remove temp ingress rule
revoke_trend_elb_ingress(TREND_SESSION, SG_ID)
#if any error when adding account, throw exception
if not success:
raise Exception("Failed to add tenant as cloud account in Trend Deep Security Manager!")
print("Trend Micro Deep Security Manager integration complete!")
## TREND DEEP SECURITY HELPER FUNCTIONS ###
def trend_sg_ingress_rule_exists(sg_rules):
for elem in sg_rules:
matches = [ x for x in elem['IpRanges'] if x['CidrIp'] == LAMBDA_PUBLIC_IP ]
if any(matches):
return True
return False
def authorize_trend_elb_ingress(TREND_SESSION, SECURITY_GROUP_ID):
ec2 = TREND_SESSION.resource('ec2', region_name='eu-west-1')
elb_security_group = ec2.SecurityGroup(SECURITY_GROUP_ID)
if trend_sg_ingress_rule_exists(elb_security_group.ip_permissions):
return False
print("Allowing public IP for executing Lambda, {}, to temporarily call Trend DSM".format(LAMBDA_PUBLIC_IP))
elb_security_group.authorize_ingress(
CidrIp=LAMBDA_PUBLIC_IP,
FromPort=777,
ToPort=777,
IpProtocol='tcp',
)
print("DONE!")
return True
def revoke_trend_elb_ingress(TREND_SESSION, SECURITY_GROUP_ID):
ec2 = TREND_SESSION.resource('ec2', region_name='eu-west-1')
elb_security_group = ec2.SecurityGroup(SECURITY_GROUP_ID)
if not trend_sg_ingress_rule_exists(elb_security_group.ip_permissions):
return False
print("Revoking public IP for executing Lambda, {}, from Trend DSM ELB SG".format(LAMBDA_PUBLIC_IP))
elb_security_group.revoke_ingress(
CidrIp=LAMBDA_PUBLIC_IP,
FromPort=777,
ToPort=777,
IpProtocol='tcp',
)
print("DONE!")
def is_account_in_trend_dsm(dsm_names, account_id):
print("Checking if tenant account already in Trend DSM Org Tenant")
for dsm_account_name in dsm_names:
if account_id == dsm_account_name[-12:]:
print("Found!")
return True
print("Not found")
return False
def get_trend_org_cookie(org_name, payload):
print("Logging into Trend DSM as Org tenant")
headers = {'content-type': "application/json", 'accept': "application/json" }
r = requests.post(
url = "https://xyz-abc-tre-dsmelb-fbsp95snsrjw-2912957566.eu-west-1.elb.amazonaws.com/rest/authentication/login",
headers= headers,
data = payload,
verify=False
)
print(r.status_code)
print("Logged in!")
return r.text
def get_trend_auth_payload_json(org_name, org_tenant_password):
auth = {
'dsCredentials' : { 'userName' : 'MasterAdmin' , 'password' : org_tenant_password, 'tenantName' : org_name}
}
return json.dumps(auth)
def get_trend_org_cloud_accounts(cookie_string):
cookie = {'sID': cookie_string}
headers = {'content-type': "application/json", 'accept': "application/json" }
print("Getting cloud accounts for Trend org tenant...")
r = requests.get(
url = "https://xyz-abc-tre-dsmelb-fbsh952n1rbw-2185847414.eu-west-1.elb.amazonaws.com/rest/cloudaccounts/",
headers= headers,
cookies=cookie,
verify=False
)
resp = r.json()['ListCloudAccountsResponse']
print("Retrieved!")
return [ x['name'] for x in resp['cloudAccount'] ]
def add_trend_cloud_account(cookie_string, account_id):
cookie = {'sID': cookie_string}
headers = {'content-type': "application/json", 'accept': "application/json" }
info = {}
info['AddAwsAccountRequest'] = {}
info['AddAwsAccountRequest']['crossAccountRole'] = {}
info['AddAwsAccountRequest']['crossAccountRole']['roleArn'] = 'arn:aws:iam::{}:role/gdc-pcs-trend-micro-dsm-role'.format(account_id)
info['AddAwsAccountRequest']['crossAccountRole']['externalId'] = '7F4DC12D-53B2-1BEX-7CB7-8759CDADEB71'
print('Adding {} as Trend cloud account...'.format(account_id))
r = requests.post(
url = "https//xyz-abc-tre-dsmelb-fbsp95snsrjw-7443282981.eu-west-1.elb.amazonaws.com/rest/cloudaccounts/aws",
headers= headers,
cookies=cookie,
data = json.dumps(info),
verify=False
)
print(r.status_code)
if r.status_code == 200:
print("Done!")
return True
else:
print("Failed!")
return False`