Skip to content

Commit 5451ab1

Browse files
author
Justin
committed
fixes from init testing
1 parent 84be8de commit 5451ab1

File tree

4 files changed

+41
-55
lines changed

4 files changed

+41
-55
lines changed

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

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def get_validated_parameters(event: Dict[str, Any]) -> dict:
159159
parameter_pattern_validator(
160160
"RESOURCES_TO_PROTECT",
161161
os.environ.get("RESOURCES_TO_PROTECT"),
162-
pattern=r"arn:aws:[a-z0-9-]+:([a-z0-9-]+:){0,2}[0-9]{12}:.+",
162+
pattern=r"arn:aws:([a-z0-9-]+:+([a-z0-9-]+:){0,2}[0-9]{12}:[a-z0-9-]+\/?[a-zA-Z0-9-]+\/?[a-zA-Z0-9-]+\/?[a-zA-Z0-9-]+)+(?:,|$)*",
163163
)
164164
)
165165
params.update(
@@ -210,23 +210,23 @@ def get_validated_parameters(event: Dict[str, Any]) -> dict:
210210
parameter_pattern_validator(
211211
"SHIELD_PROACTIVE_ENGAGEMENT_EMAIL",
212212
os.environ.get("SHIELD_PROACTIVE_ENGAGEMENT_EMAIL"),
213-
pattern=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
213+
pattern=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$|^$",
214214
is_optional=True,
215215
)
216216
)
217217
params.update(
218218
parameter_pattern_validator(
219219
"SHIELD_PROACTIVE_ENGAGEMENT_PHONE_NUMBER",
220220
os.environ.get("SHIELD_PROACTIVE_ENGAGEMENT_PHONE_NUMBER"),
221-
pattern=r"^\+?[1-9]\d{1,14}$",
221+
pattern=r"^\+?[1-9]\d{1,14}$|^$",
222222
is_optional=True,
223223
)
224224
)
225225
params.update(
226226
parameter_pattern_validator(
227227
"SHIELD_PROACTIVE_ENGAGEMENT_NOTES",
228228
os.environ.get("SHIELD_PROACTIVE_ENGAGEMENT_NOTES"),
229-
pattern=r"^[a-zA-Z0-9\s]+$",
229+
pattern=r"^[a-zA-Z0-9\s]+$|^$",
230230
is_optional=True,
231231
)
232232
)
@@ -329,7 +329,7 @@ def get_validated_parameters(event: Dict[str, Any]) -> dict:
329329
params.update(
330330
parameter_pattern_validator(
331331
"PROTECTION_GROUP_2_ACCOUNT_ID",
332-
os.environ.get("PROTECTION_GROUP_0_ACCOUNT_ID"),
332+
os.environ.get("PROTECTION_GROUP_2_ACCOUNT_ID"),
333333
pattern=protection_group_account_id_pattern,
334334
is_optional=True,
335335
)
@@ -377,7 +377,7 @@ def get_validated_parameters(event: Dict[str, Any]) -> dict:
377377
params.update(
378378
parameter_pattern_validator(
379379
"PROTECTION_GROUP_3_ACCOUNT_ID",
380-
os.environ.get("PROTECTION_GROUP_0_ACCOUNT_ID"),
380+
os.environ.get("PROTECTION_GROUP_3_ACCOUNT_ID"),
381381
pattern=protection_group_account_id_pattern,
382382
is_optional=True,
383383
)
@@ -425,7 +425,7 @@ def get_validated_parameters(event: Dict[str, Any]) -> dict:
425425
params.update(
426426
parameter_pattern_validator(
427427
"PROTECTION_GROUP_4_ACCOUNT_ID",
428-
os.environ.get("PROTECTION_GROUP_0_ACCOUNT_ID"),
428+
os.environ.get("PROTECTION_GROUP_4_ACCOUNT_ID"),
429429
pattern=protection_group_account_id_pattern,
430430
is_optional=True,
431431
)
@@ -523,7 +523,9 @@ def setup_shield_global(params: dict, accounts: list) -> None:
523523
else:
524524
LOGGER.info("")
525525
accounts = []
526+
print(f'SHIELD_ACCOUNTS_TO_PROTECT {params["SHIELD_ACCOUNTS_TO_PROTECT"]}')
526527
for account in params["SHIELD_ACCOUNTS_TO_PROTECT"].split(","):
528+
print(f"Adding AccountId: {account} to accounts")
527529
accounts.append({"AccountId": account})
528530
for account in accounts:
529531
account_id = account["AccountId"]
@@ -532,7 +534,6 @@ def setup_shield_global(params: dict, accounts: list) -> None:
532534

533535
account_session: boto3.Session = common.assume_role(params["CONFIGURATION_ROLE_NAME"], "sra-configure-shield", account_id)
534536
shield_client: ShieldClient = account_session.client("shield")
535-
# shield.create_service_linked_role(account_id, params["CONFIGURATION_ROLE_NAME"])
536537
shield.create_subscription(shield_client)
537538
role_arn = shield.create_drt_role(account_id, params["SHIELD_DRT_ROLE_NAME"], account_session)
538539
shield.associate_drt_role(shield_client, role_arn)
@@ -582,11 +583,9 @@ def setup_shield(account_session: boto3.Session, account_id: str, params: dict)
582583
buckets_processed: list = []
583584
resources_processed: list = []
584585

585-
# for region in regions:
586-
LOGGER.info(f"setup shield in for account {account_id} in ")
586+
LOGGER.info(f"setup shield in account: {account_id}")
587587
shield.build_resources_by_account(account_session, params, account_id)
588588
shield_client = account_session.client("shield")
589-
# shield.create_subscription(shield_client)
590589
resources_already_protected = shield.list_protections(shield_client)
591590
shield.enable_proactive_engagement(shield_client, params)
592591
while len(shield.RESOURCES_BY_ACCOUNT[account_id]["buckets"]) > 0:
@@ -599,15 +598,11 @@ def setup_shield(account_session: boto3.Session, account_id: str, params: dict)
599598
if resource not in resources_already_protected and resource not in resources_processed:
600599
shield.create_protection(shield_client, resource)
601600
LOGGER.info(f"Create protection for {resource}")
602-
# shield.create_protection_group(shield_client, params, account_id)
603601
resources_processed.append(resource)
604-
# else:
605-
# shield.RESOURCES_BY_ACCOUNT[account_id]["resources_to_protect"].append(resource)
606602
if len(resources_already_protected) > 0 or len(resources_processed) > 0:
607603
shield.create_protection_group(shield_client, params, account_id)
608604

609605

610-
# COMMENT
611606
@helper.create
612607
@helper.update
613608
@helper.delete
@@ -649,8 +644,6 @@ def orchestrator(event: Dict[str, Any], context: Any) -> None:
649644
if event.get("RequestType"):
650645
LOGGER.info("...calling helper...")
651646
helper(event, context)
652-
# TODO uncomment line above remove line below
653-
# process_event_cloudformation(event, context)
654647
else:
655648
LOGGER.info("...else...just calling process_event...")
656649
process_event(event)
@@ -677,9 +670,3 @@ def lambda_handler(event: Dict[str, Any], context: Any) -> None:
677670
LOGGER.exception(ex)
678671
LOGGER.exception(UNEXPECTED)
679672
raise ValueError(f"Unexpected error executing Lambda function. Review CloudWatch logs ({context.log_group_name}) for details.") from None
680-
681-
682-
# lambda_handler({"RequestType": "Create"}, {})
683-
# lambda_handler({"RequestType": "Update"}, {})
684-
# lambda_handler({"RequestType": "Delete"}, {})
685-
"""COMMENT"""

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

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,11 @@
1616

1717
import boto3
1818
import common
19+
from botocore.exceptions import ClientError
1920

2021
if TYPE_CHECKING:
2122
from mypy_boto3_iam import IAMClient
22-
from mypy_boto3_iam.type_defs import (
23-
AttachRolePolicyResponseTypeDef,
24-
CreateRoleResponseTypeDef,
25-
DeleteRoleRequestRequestTypeDef,
26-
DetachRolePolicyRequestPolicyDetachRoleTypeDef,
27-
)
23+
from mypy_boto3_iam.type_defs import CreateRoleResponseTypeDef, DeleteRoleRequestRequestTypeDef, DetachRolePolicyRequestPolicyDetachRoleTypeDef
2824
from mypy_boto3_organizations import OrganizationsClient
2925
from mypy_boto3_route53 import Route53Client
3026
from mypy_boto3_route53.type_defs import ListHostedZonesResponseTypeDef
@@ -34,12 +30,8 @@
3430
AssociateDRTLogBucketRequestRequestTypeDef,
3531
AssociateProactiveEngagementDetailsRequestRequestTypeDef,
3632
CreateProtectionGroupRequestRequestTypeDef,
37-
CreateProtectionGroupResponseTypeDef,
3833
CreateProtectionResponseTypeDef,
39-
CreateSubscriptionRequestRequestTypeDef,
40-
CreateSubscriptionResponseTypeDef,
4134
DeleteProtectionGroupRequestRequestTypeDef,
42-
DeleteProtectionGroupResponseTypeDef,
4335
DeleteProtectionRequestRequestTypeDef,
4436
DescribeEmergencyContactSettingsResponseTypeDef,
4537
DescribeProtectionResponseTypeDef,
@@ -48,8 +40,6 @@
4840
DisassociateDRTLogBucketRequestRequestTypeDef,
4941
EmergencyContactTypeDef,
5042
ProtectionTypeDef,
51-
UpdateEmergencyContactSettingsRequestRequestTypeDef,
52-
UpdateEmergencyContactSettingsResponseTypeDef,
5343
UpdateProtectionGroupRequestRequestTypeDef,
5444
)
5545

@@ -137,7 +127,7 @@ def get_route_53_hosted_zones(account_session: boto3.Session) -> list:
137127
"""
138128
route53_client: Route53Client = account_session.client("route53")
139129
hosted_zones: ListHostedZonesResponseTypeDef = route53_client.list_hosted_zones()
140-
LOGGER.info("[INFO] Listing hosted zones from the Route53\n\n")
130+
LOGGER.info("[INFO] Listing hosted zones from the Route53")
141131
marker: bool = True
142132
hosted_zone_arns: list = []
143133
while marker:
@@ -218,7 +208,7 @@ def update_emergency_contacts(shield_client: ShieldClient, params: dict, is_dele
218208
"""
219209
emergency_contacts: Sequence[EmergencyContactTypeDef] = []
220210
if not is_delete:
221-
emergency_contacts: Sequence[EmergencyContactTypeDef] = build_emergency_contacts(params)
211+
emergency_contacts = build_emergency_contacts(params)
222212
LOGGER.info(f"Updating emergency contacts to {emergency_contacts}")
223213
shield_client.update_emergency_contact_settings(EmergencyContactList=emergency_contacts)
224214
else:
@@ -304,7 +294,7 @@ def create_subscription(shield_client: ShieldClient) -> None:
304294
if subscription_enabled:
305295
LOGGER.info("Shield Advanced Subscription is already enabled")
306296
else:
307-
enable_shield_response: CreateSubscriptionResponseTypeDef = shield_client.create_subscription()
297+
enable_shield_response = shield_client.create_subscription()
308298
api_call_details = {"API_Call": "shield:CreateSubscription", "API_Response": enable_shield_response}
309299
LOGGER.info(api_call_details)
310300

@@ -410,13 +400,13 @@ def create_drt_role(account: str, role_name: str, account_session: boto3.Session
410400
]
411401
}""",
412402
)
413-
attach_policy_response: AttachRolePolicyResponseTypeDef = iam_client.attach_role_policy(
403+
attach_policy_response = iam_client.attach_role_policy(
414404
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy", RoleName=role_name
415405
)
416406
role_arn: str = create_role_response["Role"]["Arn"]
417407
else:
418408
role_arn = role_exists
419-
attach_policy_response: AttachRolePolicyResponseTypeDef = iam_client.attach_role_policy(
409+
attach_policy_response = iam_client.attach_role_policy(
420410
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy", RoleName=role_name
421411
)
422412

@@ -549,8 +539,7 @@ def check_proactive_engagement_enabled(shield_client: ShieldClient, params: dict
549539
time.sleep(5)
550540
check_proactive_engagement_enabled(shield_client, params, retry + 1)
551541
else:
552-
# TODO take a look at this and see if I should raise an error instead
553-
return True
542+
raise ValueError("Proactive engagement status not found")
554543

555544

556545
def check_if_protection_group_exists(shield_client: ShieldClient, protection_group_id: str) -> bool:
@@ -596,7 +585,7 @@ def delete_protection_group(shield_client: ShieldClient, params: dict, account_i
596585
pg_id: str = params[f"PROTECTION_GROUP_{i}_ID"]
597586
if account_id == params[f"PROTECTION_GROUP_{i}_ACCOUNT_ID"]:
598587
if pg_id != "":
599-
delete_protection_group_response: DeleteProtectionGroupResponseTypeDef = shield_client.delete_protection_group(
588+
delete_protection_group_response: DeleteProtectionGroupRequestRequestTypeDef = shield_client.delete_protection_group(
600589
ProtectionGroupId=pg_id
601590
)
602591
api_call_details = {"API_Call": "shield:DeleteProtectionGroup", "API_Response": delete_protection_group_response}
@@ -651,10 +640,11 @@ def create_protection_group(shield_client: ShieldClient, params: dict, account_i
651640
652641
Args:
653642
shield_client: shield client
654-
params: environment variablrd
643+
params: environment variables
655644
account_id: AWS account id
656645
"""
657646
for i in range(0, 5):
647+
print(i)
658648
pg_id: str = params[f"PROTECTION_GROUP_{i}_ID"]
659649
pg_account_id: str = params[f"PROTECTION_GROUP_{i}_ACCOUNT_ID"]
660650
pg_aggregation: Literal["SUM", "MEAN", "MAX"] = params[f"PROTECTION_GROUP_{i}_AGGREGATION"]
@@ -667,24 +657,26 @@ def create_protection_group(shield_client: ShieldClient, params: dict, account_i
667657
"APPLICATION_LOAD_BALANCER",
668658
"GLOBAL_ACCELERATOR",
669659
] = params[f"PROTECTION_GROUP_{i}_RESOURCE_TYPE"]
670-
660+
print(f" pg_account_id {pg_account_id}")
671661
pg_members: list = params[f"PROTECTION_GROUP_{i}_MEMBERS"]
662+
print(f"pg_members{pg_members}")
663+
print(f"i {i}")
672664
if pg_id != "" and pg_account_id == account_id:
673665
if check_if_protection_group_exists(shield_client, pg_id):
674666
LOGGER.info(f"Protection_Group_{i} already exists in {account_id}")
675667
update_protection_group(shield_client, pg_id, pg_aggregation, pg_pattern, pg_resource_type, pg_members)
676668
break
677669
LOGGER.info(f"Creating Protection_Group_{i} in {account_id}")
678670
if pg_pattern == "BY_RESOURCE_TYPE":
679-
protection_group_response = shield_client.create_protection_group(
671+
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
680672
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, ResourceType=pg_resource_type
681673
)
682674
elif pg_pattern == "ARBITRARY":
683-
protection_group_response = shield_client.create_protection_group(
675+
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
684676
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern, Members=pg_members.split(",")
685677
)
686678
else:
687-
protection_group_response = shield_client.create_protection_group(
679+
protection_group_response: CreateProtectionGroupRequestRequestTypeDef = shield_client.create_protection_group(
688680
ProtectionGroupId=pg_id, Aggregation=pg_aggregation, Pattern=pg_pattern
689681
)
690682
api_call_details = {"API_Call": "shield:CreateProtectionGroup", "API_Response": protection_group_response}
@@ -715,6 +707,7 @@ def enable_proactive_engagement(shield_client: ShieldClient, params: dict) -> No
715707
shield_client: shield client
716708
params: environment variables
717709
"""
710+
print(f"Before IF SHIELD_ENABLE_PROACTIVE_ENGAGEMENT is set to {params['SHIELD_ENABLE_PROACTIVE_ENGAGEMENT']}")
718711
if params["SHIELD_ENABLE_PROACTIVE_ENGAGEMENT"] == "true":
719712
if check_proactive_engagement_enabled(shield_client, params):
720713
update_emergency_contacts(shield_client, params)
@@ -757,8 +750,14 @@ def disable_proactive_engagement(shield_client: ShieldClient) -> None:
757750
Args:
758751
shield_client: shield client
759752
"""
760-
disable_proactive_engagement_response: DisableApplicationLayerAutomaticResponseRequestRequestTypeDef = (
761-
shield_client.disable_proactive_engagement()
762-
)
763-
api_call_details = {"API_Call": "shield:DisableProactiveEngagement", "API_Response": disable_proactive_engagement_response}
764-
LOGGER.info(api_call_details)
753+
try:
754+
disable_proactive_engagement_response: DisableApplicationLayerAutomaticResponseRequestRequestTypeDef = (
755+
shield_client.disable_proactive_engagement()
756+
)
757+
api_call_details = {"API_Call": "shield:DisableProactiveEngagement", "API_Response": disable_proactive_engagement_response}
758+
LOGGER.info(api_call_details)
759+
except ClientError as e:
760+
if e.response["Error"]["Code"] == "InvalidOperationException":
761+
LOGGER.exception(e)
762+
else:
763+
raise e

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ Resources:
172172
- s3:ListAllMyBuckets
173173
- route53:ListHostedZones
174174
- elasticloadbalancing:DescribeLoadBalancers
175+
- ec2:DescribeAddresses
175176
Resource: '*'
176177

177178
- PolicyName: sra-shield-advanced-policy-iam

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,6 @@ Parameters:
559559

560560

561561
Conditions:
562-
cDeploymentTargets: !Equals [!Select ['0', !Ref pShieldAccountsToProtect], 'ALL']
563562
cNotGlobalRegionUsEast1: !Not [!Equals [!Ref 'AWS::Region', us-east-1]]
564563

565564
Rules:
@@ -589,7 +588,7 @@ Resources:
589588
StackInstancesGroup:
590589
- DeploymentTargets:
591590
OrganizationalUnitIds:
592-
- !If [cDeploymentTargets, !Ref pRootOrganizationalUnitId, !Ref pShieldAccountsToProtect]
591+
- !Ref pRootOrganizationalUnitId
593592
Regions:
594593
- !Ref AWS::Region
595594
TemplateURL: !Sub https://${pSRAStagingS3BucketName}.s3.${AWS::Region}.${AWS::URLSuffix}/${pSRASolutionName}/templates/sra-shield-advanced-configuration-role.yaml

0 commit comments

Comments
 (0)