in aws_sra_examples/solutions/securityhub/securityhub_enabler_acct/lambda/src/app.py [0:0]
def processing_accounts(mgmt_session, aws_account_dict, securityhub_regions, partition, action):
"""
Process all accounts provided
:param mgmt_session: Management account session
:param aws_account_dict: Account dictionary
:param securityhub_regions: Regions to enable
:param partition: AWS partition
:param action: CloudFormation event action
:return: None
"""
# Processing Accounts
logger.info(f"Processing: {json.dumps(aws_account_dict)}")
for account in aws_account_dict.keys():
email_address = aws_account_dict[account]
if account == MGMT_ACCOUNT_ID:
logger.info(f"Account {account} cannot become a member of itself")
continue
logger.debug(
f"Working on SecurityHub on Account {account} in \
regions %{securityhub_regions}"
)
failed_invitations = []
member_session = assume_role(account, ASSUME_ROLE_NAME)
# Process Regions
for aws_region in securityhub_regions:
sh_member_client = member_session.client(
"securityhub", region_name=aws_region
)
sh_mgmt_client = mgmt_session.client("securityhub", region_name=aws_region)
mgmt_members = get_mgmt_members(mgmt_session, aws_region)
logger.info(f"Beginning {aws_region} in Account {account}")
if account in mgmt_members:
if mgmt_members[account] == "Associated":
logger.info(
f"Account {account} is already associated "
f"with Management Account {MGMT_ACCOUNT_ID} in "
f"{aws_region}"
)
if action == "Delete":
try:
sh_mgmt_client.disassociate_members(AccountIds=[account])
except ClientError:
continue
try:
sh_mgmt_client.delete_members(AccountIds=[account])
except ClientError:
continue
else:
logger.warning(
f"Account {account} exists, but not "
f"associated to Management Account "
f"{MGMT_ACCOUNT_ID} in {aws_region}"
)
logger.info(
f"Disassociating Account {account} from "
f"Management Account {MGMT_ACCOUNT_ID} in "
f"{aws_region}"
)
try:
sh_mgmt_client.disassociate_members(AccountIds=[account])
except ClientError:
continue
try:
sh_mgmt_client.delete_members(AccountIds=[account])
except ClientError:
continue
try:
sh_member_client.get_findings()
except Exception as exc:
logger.debug(str(exc))
logger.info(
f"SecurityHub not currently Enabled on Account "
f"{account} in {aws_region}"
)
if action != "Delete":
logger.info(
f"Enabled SecurityHub on Account {account} " f"in {aws_region}"
)
try:
sh_member_client.enable_security_hub(EnableDefaultStandards=False)
except ClientError:
logger.info(f"Unable to Enable Security Hub in {account} and {aws_region}")
continue
else:
# Security Hub is already enabled
if action != "Delete":
logger.info(
f"SecurityHub already Enabled in Account "
f"{account} in {aws_region}"
)
else:
logger.info(
f"Disabled SecurityHub in Account " f"{account} in {aws_region}"
)
try:
sh_member_client.disable_security_hub()
except ClientError:
continue
if action != "Delete":
process_security_standards(sh_member_client, partition, aws_region, account)
process_integrations(sh_member_client, partition, aws_region, account)
logger.info(
f"Creating member for Account {account} and "
f"Email, {email_address} in {aws_region}"
)
member_response = sh_mgmt_client.create_members(
AccountDetails=[{"AccountId": account, "Email": email_address}]
)
if len(member_response["UnprocessedAccounts"]) > 0:
logger.warning(
f"Could not create member Account " f"{account} in {aws_region}"
)
failed_invitations.append(
{"AccountId": account, "Region": aws_region}
)
continue
logger.info(f"Inviting Account {account} in {aws_region}")
sh_mgmt_client.invite_members(AccountIds=[account])
# go through each invitation (hopefully only 1)
# and pull the one matching the Security Management Account ID
try:
paginator = sh_member_client.get_paginator("list_invitations")
invitation_iterator = paginator.paginate()
for invitation in invitation_iterator:
mgmt_invitation = next(
item
for item in invitation["Invitations"]
if item["AccountId"] == MGMT_ACCOUNT_ID
)
logger.info(
f"Accepting invitation on Account {account} "
f"from Management Account {MGMT_ACCOUNT_ID} in "
f"{aws_region}"
)
sh_member_client.accept_invitation(
MasterId=MGMT_ACCOUNT_ID,
InvitationId=mgmt_invitation["InvitationId"],
)
except Exception as exc:
logger.warning(
f"Account {account} could not accept "
f"invitation from Management Account "
f"{MGMT_ACCOUNT_ID} in {aws_region}"
)
logger.warning(f"{exc}")
if len(failed_invitations) > 0:
failed_accounts = json.dumps(
failed_invitations, sort_keys=True, default=str
)
logger.warning(
f"Error Processing the following Accounts: {failed_accounts}"
)