Skip to content

Commit 96bff01

Browse files
author
Justin
committed
added cfn usage code
1 parent 7318195 commit 96bff01

File tree

5 files changed

+39
-56
lines changed

5 files changed

+39
-56
lines changed

aws_sra_examples/solutions/shield_advanced/shield_advanced/lambda/src/shield.py

Lines changed: 34 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -19,27 +19,21 @@
1919

2020
if TYPE_CHECKING:
2121
from mypy_boto3_iam import IAMClient
22-
from mypy_boto3_iam.type_defs import CreateRoleResponseTypeDef, DeleteRoleRequestRequestTypeDef, DetachRolePolicyRequestPolicyDetachRoleTypeDef
22+
from mypy_boto3_iam.type_defs import CreateRoleResponseTypeDef
2323
from mypy_boto3_organizations import OrganizationsClient
2424
from mypy_boto3_route53 import Route53Client
2525
from mypy_boto3_route53.type_defs import ListHostedZonesResponseTypeDef
2626
from mypy_boto3_s3 import S3Client
2727
from mypy_boto3_shield import ShieldClient
2828
from mypy_boto3_shield.type_defs import (
29-
AssociateDRTLogBucketRequestRequestTypeDef,
3029
AssociateProactiveEngagementDetailsRequestRequestTypeDef,
31-
CreateProtectionGroupRequestRequestTypeDef,
3230
CreateProtectionResponseTypeDef,
33-
DeleteProtectionGroupRequestRequestTypeDef,
34-
DeleteProtectionRequestRequestTypeDef,
3531
DescribeEmergencyContactSettingsResponseTypeDef,
3632
DescribeProtectionResponseTypeDef,
3733
DescribeSubscriptionResponseTypeDef,
3834
DisableApplicationLayerAutomaticResponseRequestRequestTypeDef,
39-
DisassociateDRTLogBucketRequestRequestTypeDef,
4035
EmergencyContactTypeDef,
4136
ProtectionTypeDef,
42-
UpdateProtectionGroupRequestRequestTypeDef,
4337
)
4438

4539

@@ -51,6 +45,7 @@
5145

5246
UNEXPECTED = "Unexpected!"
5347
RESOURCES_BY_ACCOUNT: dict = {}
48+
SHIELD_DRT_POLICY = "arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy"
5449

5550
try:
5651
MANAGEMENT_ACCOUNT_SESSION = boto3.Session()
@@ -86,10 +81,10 @@ def build_resources_by_account(account_session: boto3.Session, params: dict, acc
8681
"""
8782
buckets: list = get_buckets_to_protect(account_session, params["SHIELD_DRT_LOG_BUCKETS"].split(","))
8883
check_if_key_in_object("buckets", RESOURCES_BY_ACCOUNT[account_id], "list")
89-
RESOURCES_BY_ACCOUNT[account_id]["buckets"]: list = buckets
84+
RESOURCES_BY_ACCOUNT[account_id]["buckets"] = buckets
9085
check_if_key_in_object("resources_to_protect", RESOURCES_BY_ACCOUNT[account_id], "list")
9186
hosted_zones: list = get_route_53_hosted_zones(account_session)
92-
RESOURCES_BY_ACCOUNT[account_id]["resources_to_protect"]: list = hosted_zones
87+
RESOURCES_BY_ACCOUNT[account_id]["resources_to_protect"] = hosted_zones
9388
resources_to_protect: list = get_resources_to_protect_in_account(account_id, params["RESOURCES_TO_PROTECT"].split(","))
9489
RESOURCES_BY_ACCOUNT[account_id]["resources_to_protect"].extend(resources_to_protect)
9590

@@ -321,14 +316,12 @@ def detach_drt_role_policy(account_session: boto3.Session, role_name: str) -> No
321316
try:
322317
LOGGER.info("detaching DRT role policy")
323318
iam_client: IAMClient = account_session.client("iam")
324-
detach_policy_response: DetachRolePolicyRequestPolicyDetachRoleTypeDef = iam_client.detach_role_policy(
325-
RoleName=role_name, PolicyArn="arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy"
326-
)
319+
detach_policy_response = iam_client.detach_role_policy(RoleName=role_name, PolicyArn=SHIELD_DRT_POLICY)
327320
api_call_details = {"API_Call": "iam:DetachRolePolicy", "API_Response": detach_policy_response}
328321
LOGGER.info(api_call_details)
329322
except iam_client.exceptions.NoSuchEntityException as nse:
330323
LOGGER.info(f"NoSuchEntityException {nse}")
331-
LOGGER.info(f"Continuing...")
324+
LOGGER.info("Continuing...")
332325

333326

334327
def delete_drt_role(account_session: boto3.Session, role_name: str) -> None:
@@ -342,7 +335,7 @@ def delete_drt_role(account_session: boto3.Session, role_name: str) -> None:
342335
LOGGER.info("deleting DRT role")
343336
iam_client: IAMClient = account_session.client("iam")
344337
detach_drt_role_policy(account_session, role_name)
345-
delete_role_response: DeleteRoleRequestRequestTypeDef = iam_client.delete_role(RoleName=role_name)
338+
delete_role_response = iam_client.delete_role(RoleName=role_name)
346339
api_call_details = {"API_Call": "iam:DeleteRole", "API_Response": delete_role_response}
347340
LOGGER.info(api_call_details)
348341
except iam_client.exceptions.NoSuchEntityException as nse:
@@ -379,9 +372,9 @@ def create_drt_role(account: str, role_name: str, account_session: boto3.Session
379372

380373
iam_client: IAMClient = account_session.client("iam")
381374
role_exists = check_if_role_exists(iam_client, role_name)
382-
role_arn = ""
375+
role_arn: str = ""
383376
if role_exists == "":
384-
create_role_response: CreateRoleResponseTypeDef = iam_client.create_role(
377+
create_role_response = iam_client.create_role(
385378
RoleName=role_name,
386379
AssumeRolePolicyDocument="""{
387380
"Version": "2012-10-17",
@@ -396,15 +389,11 @@ def create_drt_role(account: str, role_name: str, account_session: boto3.Session
396389
]
397390
}""",
398391
)
399-
attach_policy_response = iam_client.attach_role_policy(
400-
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy", RoleName=role_name
401-
)
402-
role_arn: str = create_role_response["Role"]["Arn"]
392+
attach_policy_response = iam_client.attach_role_policy(PolicyArn=SHIELD_DRT_POLICY, RoleName=role_name)
393+
role_arn = create_role_response["Role"]["Arn"]
403394
else:
404395
role_arn = role_exists
405-
attach_policy_response = iam_client.attach_role_policy(
406-
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy", RoleName=role_name
407-
)
396+
attach_policy_response = iam_client.attach_role_policy(PolicyArn=SHIELD_DRT_POLICY, RoleName=role_name)
408397

409398
api_call_details = {"API_Call": "iam:AttachRolePolicy", "API_Response": attach_policy_response}
410399
LOGGER.info(api_call_details)
@@ -453,7 +442,7 @@ def delete_protection(shield_client: ShieldClient, resource_arn: str) -> None:
453442
protection_id: str = get_protection_id(shield_client, resource_arn)
454443
if protection_id != "":
455444
LOGGER.info(f"Deleting protection for {resource_arn} and protectionId {protection_id}")
456-
delete_protection_response: DeleteProtectionRequestRequestTypeDef = shield_client.delete_protection(ProtectionId=protection_id)
445+
delete_protection_response = shield_client.delete_protection(ProtectionId=protection_id)
457446
api_call_details = {"API_Call": "shield:DeleteProtection", "API_Response": delete_protection_response}
458447
LOGGER.info(api_call_details)
459448
else:
@@ -468,7 +457,7 @@ def associate_drt_log_bucket(shield_client: ShieldClient, log_bucket: str) -> No
468457
shield_client: shield client
469458
log_bucket: bucket to grant access via bucket policy
470459
"""
471-
associate_drt_log_response: AssociateDRTLogBucketRequestRequestTypeDef = shield_client.associate_drt_log_bucket(LogBucket=log_bucket)
460+
associate_drt_log_response = shield_client.associate_drt_log_bucket(LogBucket=log_bucket)
472461
api_call_details = {"API_Call": "shield:AssociateDRTLogBucket", "API_Response": associate_drt_log_response}
473462
LOGGER.info(api_call_details)
474463

@@ -480,7 +469,7 @@ def disassociate_drt_log_bucket(shield_client: ShieldClient, log_bucket: str) ->
480469
shield_client: shield client
481470
log_bucket: bucket to update the policy
482471
"""
483-
disassociate_drt_log_response: DisassociateDRTLogBucketRequestRequestTypeDef = shield_client.disassociate_drt_log_bucket(LogBucket=log_bucket)
472+
disassociate_drt_log_response = shield_client.disassociate_drt_log_bucket(LogBucket=log_bucket)
484473
api_call_details = {"API_Call": "shield:DisassociateDRTLogBucket", "API_Response": disassociate_drt_log_response}
485474
LOGGER.info(api_call_details)
486475

@@ -535,7 +524,7 @@ def check_proactive_engagement_enabled(shield_client: ShieldClient, params: dict
535524
time.sleep(5)
536525
check_proactive_engagement_enabled(shield_client, params, retry + 1)
537526
else:
538-
raise ValueError("Proactive engagement status not found")
527+
return False
539528

540529

541530
def check_if_protection_group_exists(shield_client: ShieldClient, protection_group_id: str) -> bool:
@@ -581,9 +570,7 @@ def delete_protection_group(shield_client: ShieldClient, params: dict, account_i
581570
pg_id: str = params[f"PROTECTION_GROUP_{i}_ID"]
582571
if account_id == params[f"PROTECTION_GROUP_{i}_ACCOUNT_ID"]:
583572
if pg_id != "":
584-
delete_protection_group_response: DeleteProtectionGroupRequestRequestTypeDef = shield_client.delete_protection_group(
585-
ProtectionGroupId=pg_id
586-
)
573+
delete_protection_group_response = shield_client.delete_protection_group(ProtectionGroupId=pg_id)
587574
api_call_details = {"API_Call": "shield:DeleteProtectionGroup", "API_Response": delete_protection_group_response}
588575
LOGGER.info(api_call_details)
589576
else:
@@ -603,7 +590,7 @@ def update_protection_group(
603590
"APPLICATION_LOAD_BALANCER",
604591
"GLOBAL_ACCELERATOR",
605592
],
606-
pg_members: list,
593+
pg_members: list[str],
607594
) -> None:
608595
"""Updates an existing protection group
609596
@@ -616,17 +603,15 @@ def update_protection_group(
616603
pg_members: protection group members
617604
"""
618605
if pg_pattern == "BY_RESOURCE_TYPE":
619-
protection_group_response: UpdateProtectionGroupRequestRequestTypeDef = shield_client.update_protection_group(
606+
protection_group_response = shield_client.update_protection_group(
620607
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, ResourceType=pg_resource_type
621608
)
622609
elif pg_pattern == "ARBITRARY":
623-
protection_group_response: UpdateProtectionGroupRequestRequestTypeDef = shield_client.update_protection_group(
610+
protection_group_response = shield_client.update_protection_group(
624611
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, Members=pg_members.split(",")
625612
)
626613
else:
627-
protection_group_response: UpdateProtectionGroupRequestRequestTypeDef = shield_client.update_protection_group(
628-
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern
629-
)
614+
protection_group_response = shield_client.update_protection_group(ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern)
630615
api_call_details = {"API_Call": "shield:UpdateProtectionGroup", "API_Response": protection_group_response}
631616
LOGGER.info(api_call_details)
632617

@@ -660,15 +645,15 @@ def create_protection_group(shield_client: ShieldClient, params: dict, account_i
660645
break
661646
LOGGER.info(f"Creating Protection_Group_{i} in {account_id}")
662647
if pg_pattern == "BY_RESOURCE_TYPE":
663-
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
648+
protection_group_response = shield_client.create_protection_group(
664649
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, ResourceType=pg_resource_type
665650
)
666651
elif pg_pattern == "ARBITRARY":
667-
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
652+
protection_group_response = shield_client.create_protection_group(
668653
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, Members=pg_members.split(",")
669654
)
670655
else:
671-
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
656+
protection_group_response = shield_client.create_protection_group(
672657
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern
673658
)
674659
api_call_details = {"API_Call": "shield:CreateProtectionGroup", "API_Response": protection_group_response}
@@ -687,7 +672,7 @@ def check_emergency_contacts(shield_client: ShieldClient) -> bool:
687672
emergency_contacts_response: DescribeEmergencyContactSettingsResponseTypeDef = shield_client.describe_emergency_contact_settings()
688673
api_call_details = {"API_Call": "shield:DescribeEmergencyContactSettings", "API_Response": emergency_contacts_response}
689674
LOGGER.info(api_call_details)
690-
if len(emergency_contacts_response) > 0:
675+
if "EmergencyContactList" in emergency_contacts_response and len(emergency_contacts_response["EmergencyContactList"]) > 0:
691676
return True
692677
else:
693678
return False
@@ -716,23 +701,21 @@ def enable_proactive_engagement(shield_client: ShieldClient, params: dict) -> No
716701
LOGGER.info(f"SHIELD_ENABLE_PROACTIVE_ENGAGEMENT is set to {params['SHIELD_ENABLE_PROACTIVE_ENGAGEMENT']}")
717702

718703

719-
def associate_proactive_engagement_details(shield_client: ShieldClient, params: dict):
704+
def associate_proactive_engagement_details(shield_client: ShieldClient, params: dict) -> None:
720705
"""Allow the DRT to use the contact information to reach out to the contacts
721706
722707
Args:
723708
shield_client: shield client
724709
params: environment variables
725710
"""
726-
associate_proactive_engagement_response: AssociateProactiveEngagementDetailsRequestRequestTypeDef = (
727-
shield_client.associate_proactive_engagement_details(
728-
EmergencyContactList=[
729-
{
730-
"EmailAddress": params["SHIELD_PROACTIVE_ENGAGEMENT_EMAIL"],
731-
"PhoneNumber": params["SHIELD_PROACTIVE_ENGAGEMENT_PHONE_NUMBER"],
732-
"ContactNotes": params["SHIELD_PROACTIVE_ENGAGEMENT_NOTES"],
733-
},
734-
]
735-
)
711+
associate_proactive_engagement_response = shield_client.associate_proactive_engagement_details(
712+
EmergencyContactList=[
713+
{
714+
"EmailAddress": params["SHIELD_PROACTIVE_ENGAGEMENT_EMAIL"],
715+
"PhoneNumber": params["SHIELD_PROACTIVE_ENGAGEMENT_PHONE_NUMBER"],
716+
"ContactNotes": params["SHIELD_PROACTIVE_ENGAGEMENT_NOTES"],
717+
},
718+
]
736719
)
737720
api_call_details = {"API_Call": "shield:AssociateProactiveEngagementDetails", "API_Response": associate_proactive_engagement_response}
738721
LOGGER.info(api_call_details)

aws_sra_examples/solutions/shield_advanced/shield_advanced/templates/sra-shield-advanced-configuration-role.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
########################################################################
55
AWSTemplateFormatVersion: 2010-09-09
66
Description:
7-
This template creates an IAM role to configure the delegated administrator account - - 'shield_org' solution in the repo,
8-
https://github.com/aws-samples/aws-security-reference-architecture-examples (REPLACE_ME)
7+
This template creates an IAM role to configure the delegated administrator account - 'shield_org' solution in the repo,
8+
https://github.com/aws-samples/aws-security-reference-architecture-examples sra-1u3sd7f8u
99

1010
Metadata:
1111
SRA:

aws_sra_examples/solutions/shield_advanced/shield_advanced/templates/sra-shield-advanced-configuration.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
AWSTemplateFormatVersion: 2010-09-09
66
Description:
77
This template creates a custom resource Lambda to delegate administration and configure shield within an AWS Organization - 'shield_org' solution in
8-
the repo, https://github.com/aws-samples/aws-security-reference-architecture-examples (REPLACE_ME)
8+
the repo, https://github.com/aws-samples/aws-security-reference-architecture-examples sra-1u3sd7f8u
99

1010
Metadata:
1111
SRA:

aws_sra_examples/solutions/shield_advanced/shield_advanced/templates/sra-shield-advanced-global-events.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
AWSTemplateFormatVersion: 2010-09-09
66
Description:
77
This template creates an event rule to send organization events to the home region. - 'shield_org' solution in the repo,
8-
https://github.com/aws-samples/aws-security-reference-architecture-examples (REPLACE_ME)
8+
https://github.com/aws-samples/aws-security-reference-architecture-examples sra-1u3sd7f8u
99
Metadata:
1010
SRA:
1111
Version: 1.0

aws_sra_examples/solutions/shield_advanced/shield_advanced/templates/sra-shield-advanced-main-ssm.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
AWSTemplateFormatVersion: 2010-09-09
66
Description:
77
This template creates a custom resource Lambda to delegate administration and configure shield within an AWS Organization - 'shield_org' solution in
8-
the repo, https://github.com/aws-samples/aws-security-reference-architecture-examples (REPLACE_ME)
8+
the repo, https://github.com/aws-samples/aws-security-reference-architecture-examples sra-1u3sd7f8u
99

1010
Metadata:
1111
SRA:

0 commit comments

Comments
 (0)