generated from amazon-archives/__template_DevGuide
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathsra-guardduty-org-solution.yaml
More file actions
973 lines (926 loc) · 39.4 KB
/
sra-guardduty-org-solution.yaml
File metadata and controls
973 lines (926 loc) · 39.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
########################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
########################################################################
AWSTemplateFormatVersion: '2010-09-09'
Description: Installs the AWS SRA GuardDuty solution. If needed, the AWS SRA common prerequisite solution is also installed. (sra-1u3sd7f8m)
Metadata:
SRA:
Version: 1.0
Order: 1
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Common Prerequisites Properties
Parameters:
- pCommonPrerequisitesInstalled
- Label:
default: General Properties
Parameters:
- pSRASolutionTagKey
- pSRASolutionName
- pSRAStagingS3BucketNamePrefix
- pSRAStagingS3BucketStackName
- pRepoURL
- pRepoBranch
- Label:
default: Landing Zone
Parameters:
- pControlTower
- pGovernedRegions
- pSecurityAccountId
- pLogArchiveAccountId
- Label:
default: CodeBuild Properties
Parameters:
- pCodeBuildProjectName
- pCodeBuildRoleName
- Label:
default: AWS Code Build Project - Lambda Function Properties
Parameters:
- pCodeBuildProjectLambdaRoleName
- pCodeBuildProjectLambdaFunctionName
- Label:
default: SRA Solutions to deploy (more settings for each are found below)
Parameters:
- pDeployGuardDutySolution
- Label:
default: GuardDuty Solution
Parameters:
- pDisableGuardDuty
- pControlTowerRegionsOnly
- pEnabledRegions
- pAutoEnableS3Logs
- pAutoEnableKubernetesAuditLogs
- pAutoEnableMalwareProtection
- pEnableRdsLoginEvents
- pEnableRuntimeMonitoring
- pEnableEksAddonManagement
- pEnableEcsFargateAgentManagement
- pEnableEc2AgentManagement
- pEnableLambdaNetworkLogs
- pGuardDutyFindingPublishingFrequency
- pGuardDutyOrgDeliveryBucketPrefix
- pGuardDutyOrgDeliveryKeyAlias
- Label:
default: Common Properties
Parameters:
- pSRAAlarmEmail
- pCreateAWSControlTowerExecutionRole
- Label:
default: General Lambda Function and EventBridge Properties
Parameters:
- pCreateLambdaLogGroup
- pLambdaLogGroupRetention
- pLambdaLogGroupKmsKey
- pLambdaLogLevel
ParameterLabels:
pRepoURL:
default: The AWS SRA public code repository HTTPS URL
pRepoBranch:
default: The AWS SRA public code repository branch name
pCommonPrerequisitesInstalled:
default: AWS SRA Common Prerequisites solution installed (true or false)
pControlTower:
default: AWS Control Tower landing zone deployed/in-use
pGovernedRegions:
default: AWS regions (comma separated) if not using AWS Control Tower (leave set to ct-regions for AWS Control Tower environments)
pSecurityAccountId:
default: Security Tooling Account ID
pLogArchiveAccountId:
default: Log Archive Account ID
pSRASolutionName:
default: SRA Solution Name
pCodeBuildProjectName:
default: SRA CodeBuild Project Name
pCodeBuildRoleName:
default: SRA CodeBuild Role Name
pCodeBuildProjectLambdaRoleName:
default: SRA CodeBuild Project Lambda Role Name
pCodeBuildProjectLambdaFunctionName:
default: SRA CodeBuild Project Lambda Function Name
pSRAStagingS3BucketNamePrefix:
default: SRA Staging S3 Bucket Name Prefix
pSRAStagingS3BucketStackName:
default: SRA Staging S3 Bucket Stack Name
pCreateLambdaLogGroup:
default: Create Lambda Log Group
pLambdaLogGroupKmsKey:
default: (Optional) Lambda Log Group KMS Key
pLambdaLogGroupRetention:
default: Lambda Log Group Retention
pLambdaLogLevel:
default: Lambda Log Level
pSRAAlarmEmail:
default: (Optional) SRA Alarm Email
pCreateAWSControlTowerExecutionRole:
default: Create AWS Control Tower Execution Role
pDeployGuardDutySolution:
default: Deploy the GuardDuty Solution
pDisableGuardDuty:
default: Disable GuardDuty
pAutoEnableS3Logs:
default: Auto Enable S3 Logs
pAutoEnableKubernetesAuditLogs:
default: Auto Enable Kubernetes Audit Logs
pAutoEnableMalwareProtection:
default: Auto Enable Malware Protection
pEnableRdsLoginEvents:
default: Auto enable RDS Login Events
pEnableRuntimeMonitoring:
default: Auto enable Runtime Monitoring
pEnableEksAddonManagement:
default: Auto enable EKS Add-on Management
pEnableEcsFargateAgentManagement:
default: Auto enable ECS Fargate Agent Management
pEnableEc2AgentManagement:
default: Auto enable EC2 Agent Management
pEnableLambdaNetworkLogs:
default: Auto enable Lambda Network Logs
pGuardDutyFindingPublishingFrequency:
default: GuardDuty Finding Publishing Frequency
pGuardDutyOrgDeliveryBucketPrefix:
default: GuardDuty Delivery Bucket Prefix
pGuardDutyOrgDeliveryKeyAlias:
default: GuardDuty Delivery KMS Key Alias
pControlTowerRegionsOnly:
default: Control Tower Regions Only
pEnabledRegions:
default: (Optional) Enabled Regions
Parameters:
pRepoURL:
Default: https://github.com/aws-samples/aws-security-reference-architecture-examples.git
Description:
SRA Code Library Repository URL
Type: String
pRepoBranch:
Default: tags/v3.0.4
Description:
SRA Code Library Repository branch name. Can be used as branch or as tags (e.g. tags/v3.0.1)
Type: String
pCommonPrerequisitesInstalled:
AllowedValues: ['true', 'false']
Default: 'false'
Description:
Indicates whether or not the AWS SRA common prerequisites solution is already installed (true or false).
Type: String
pControlTower:
AllowedValues: ['true', 'false']
Default: 'true'
Description:
Indicates whether AWS Control Tower is deployed and being used for this AWS environment.
Type: String
pGovernedRegions:
AllowedPattern: '^(ct-regions)|((\b(?<!@)(af-south-1|ap-east-1|ap-northeast-1|ap-northeast-2|ap-northeast-3|ap-south-1|ap-south-2|ap-southeast-1|ap-southeast-2|ap-southeast-3|ap-southeast-4|ca-central-1|cn-north-1|cn-northwest-1|eu-central-1|eu-central-2|eu-north-1|eu-south-1|eu-south-2|eu-west-1|eu-west-2|eu-west-3|me-central-1|me-south-1|sa-east-1|us-east-1|us-east-2|us-gov-east-1|us-gov-west-1|us-west-1|us-west-2)\b,{0,1})*)$'
ConstraintDescription:
For AWS Control Tower, set to ct-regions (default). If not using AWS Control Tower, specify comma separated list of regions (e.g. us-west-2,us-east-1,ap-south-1) in lower case.
Default: ct-regions
Description: AWS regions (comma separated) if not using AWS Control Tower (leave set to ct-regions for AWS Control Tower environments)
Type: String
pSecurityAccountId:
AllowedPattern: '^\d{12}$'
Default: 111111111111
ConstraintDescription: Must be 12 digits.
Description: AWS Account ID of the Security Tooling account (ignored for AWS Control Tower environments).
Type: String
pLogArchiveAccountId:
AllowedPattern: '^\d{12}$'
Default: 222222222222
ConstraintDescription: Must be 12 digits.
Description: AWS Account ID of the Log Archive account (ignored for AWS Control Tower environments).
Type: String
pSRASolutionName:
AllowedValues: [sra-common-prerequisites]
Default: sra-common-prerequisites
Description: The SRA solution name. The default value is the folder name of the solution
Type: String
pSRASolutionTagKey:
AllowedValues: [sra-solution]
Default: sra-solution
Description: The SRA solution tag key applied to all resources created by the solution that support tagging. The value is the pSRASolutionName.
Type: String
pCodeBuildProjectName:
AllowedValues: [sra-guardduty-codebuild-project]
Default: sra-guardduty-codebuild-project
Description:
SRA CodeBuild project name
Type: String
pCodeBuildRoleName:
AllowedValues: [sra-guardduty-codebuild-role]
Default: sra-guardduty-codebuild-role
Description:
SRA CodeBuild role name
Type: String
pCodeBuildProjectLambdaRoleName:
AllowedPattern: '^[\w+=,.@-]{1,64}$'
ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [+, =, ., @, -].
Default: sra-guardduty-codebuild-lambda-role
Description: Lambda execution role for starting the code build project
Type: String
pCodeBuildProjectLambdaFunctionName:
AllowedPattern: '^[\w-]{1,64}$'
ConstraintDescription: Max 64 alphanumeric characters. Also special characters supported [_, -]
Default: sra-guardduty-codebuild-project-lambda
Description: Lambda function name for starting the code build project
Type: String
pSRAStagingS3BucketNamePrefix:
AllowedValues: [sra-staging]
Default: sra-staging
Description:
SRA Staging S3 bucket name prefix for the SRA artifacts relevant to the solutions. (e.g., lambda zips, CloudFormation templates). The account
and region are added to the prefix <bucket-name-prefix>-<account-id>-<region>. Example = sra-staging-123456789012-us-east-1.
Type: String
pSRAStagingS3BucketStackName:
AllowedValues: [sra-common-prerequisites-staging-s3-bucket]
Default: sra-common-prerequisites-staging-s3-bucket
Description:
SRA Common Prerequisite Staging S3 bucket stack name. This stack will be created by the SRA CodeBuild Project.
Type: String
pCreateLambdaLogGroup:
AllowedValues: ['Yes', 'No']
Default: 'No'
Description:
Indicates whether a CloudWatch Log Group should be explicitly created for the Lambda function, to allow for setting a Log Retention and/or KMS
Key for encryption.
Type: String
pLambdaLogGroupKmsKey:
AllowedPattern: '^$|^arn:(aws[a-zA-Z-]*){1}:kms:[a-z0-9-]+:\d{12}:key\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$'
ConstraintDescription: 'Key ARN example: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
Default: ''
Description:
(Optional) KMS Key ARN to use for encrypting the Lambda logs data. If empty, encryption is enabled with CloudWatch Logs managing the server-side
encryption keys.
Type: String
pLambdaLogGroupRetention:
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
Default: 14
Description: Specifies the number of days you want to retain log events
Type: String
pLambdaLogLevel:
AllowedValues: [INFO, ERROR, DEBUG]
Default: INFO
Description: Lambda Function Logging Level
Type: String
pSRAAlarmEmail:
AllowedPattern: '^$|^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$'
ConstraintDescription: Must be a valid email address.
Default: ''
Description: (Optional) Email address for receiving SRA alarms
Type: String
pCreateAWSControlTowerExecutionRole:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Indicates whether the AWS Control Tower Execution role should be created.
Type: String
pDeployGuardDutySolution:
AllowedValues: ['Yes', 'No']
Default: 'Yes'
Description: Deploy the GuardDuty solution
Type: String
pDisableGuardDuty:
AllowedValues: ['Yes', 'No']
Default: 'No'
Description: Disable the GuardDuty solution in all accounts and regions before deleting the stack.
Type: String
pAutoEnableS3Logs:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable S3 logs
Type: String
pAutoEnableKubernetesAuditLogs:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable Kubernetes Audit Logs
Type: String
pAutoEnableMalwareProtection:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable Malware Protection
Type: String
pEnableRdsLoginEvents:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable RDS Login Events
Type: String
pEnableRuntimeMonitoring:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable Runtime Monitoring
Type: String
pEnableEksAddonManagement:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable EKS Add-on Management
Type: String
pEnableEcsFargateAgentManagement:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable ECS Fargate Agent Management
Type: String
pEnableEc2AgentManagement:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable EC2 Agent Management
Type: String
pEnableLambdaNetworkLogs:
AllowedValues: ['true', 'false']
Default: 'true'
Description: Auto enable Lambda Network Logs
Type: String
pGuardDutyFindingPublishingFrequency:
AllowedValues: [FIFTEEN_MINUTES, ONE_HOUR, SIX_HOURS]
Default: FIFTEEN_MINUTES
Description: Finding publishing frequency
Type: String
pGuardDutyOrgDeliveryBucketPrefix:
AllowedPattern: '^$|^[0-9a-zA-Z]+([0-9a-zA-Z-]*[0-9a-zA-Z])*$'
ConstraintDescription:
S3 bucket name can include numbers, lowercase letters, uppercase letters, and hyphens (-). It cannot start or end with a hyphen (-).
Default: sra-guardduty-org-delivery
Description:
GuardDuty Delivery S3 bucket prefix. The account and region will get added to the end. e.g. sra-guardduty-delivery-123456789012-us-east-1
Type: String
pGuardDutyOrgDeliveryKeyAlias:
Default: sra-guardduty-org-delivery-key
Description: GuardDuty Delivery KMS Key Alias
Type: String
pControlTowerRegionsOnly:
Type: String
Description: Only enable in the Control Tower governed regions (set to false for environments without AWS Control Tower)
Default: 'true'
AllowedValues: ['true', 'false']
pEnabledRegions:
AllowedPattern: '^$|^([a-z0-9-]{1,64})$|^(([a-z0-9-]{1,64},)*[a-z0-9-]{1,64})$'
ConstraintDescription:
Only lowercase letters, numbers, and hyphens ('-') allowed. (e.g. us-east-1) Additional AWS regions can be provided, separated by commas. (e.g.
us-east-1,ap-southeast-2)
Default: ''
Description: (Optional) Enabled regions (AWS regions, separated by commas). Leave blank to enable all regions.
Type: String
# Rules:
Conditions:
cUsingKmsKey: !Not [!Equals [!Ref pLambdaLogGroupKmsKey, '']]
cUseGraviton: !Or
- !Equals [!Ref 'AWS::Region', ap-northeast-1]
- !Equals [!Ref 'AWS::Region', ap-south-1]
- !Equals [!Ref 'AWS::Region', ap-southeast-1]
- !Equals [!Ref 'AWS::Region', ap-southeast-2]
- !Equals [!Ref 'AWS::Region', eu-central-1]
- !Equals [!Ref 'AWS::Region', eu-west-1]
- !Equals [!Ref 'AWS::Region', eu-west-2]
- !Equals [!Ref 'AWS::Region', us-east-1]
- !Equals [!Ref 'AWS::Region', us-east-2]
- !Equals [!Ref 'AWS::Region', us-west-2]
cCommonPrerequisitesNotInstalled: !Equals [!Ref pCommonPrerequisitesInstalled, 'false']
cCreateLambdaLogGroup: !Equals [!Ref pCreateLambdaLogGroup, 'Yes']
cDeployGuardDutySolution: !Equals [!Ref pDeployGuardDutySolution, 'Yes']
cDisableGuardDuty: !Equals [!Ref pDisableGuardDuty, 'Yes']
cCreateLogGroupAndCommonPrereqInstalled: !And
- !Condition cCreateLambdaLogGroup
- !Condition cCommonPrerequisitesNotInstalled
Resources:
rCodeBuildProject:
Type: AWS::CodeBuild::Project
Condition: cCommonPrerequisitesNotInstalled
Properties:
Name: !Sub '${pCodeBuildProjectName}'
Artifacts:
Type: NO_ARTIFACTS
Description: "Codebuild project to get SRA code from github"
Environment:
ComputeType: BUILD_GENERAL1_SMALL
EnvironmentVariables:
- Name: AWS_DEFAULT_REGION
Value: !Ref AWS::Region
- Name: AWS_ACCOUNT_ID
Value: !Ref "AWS::AccountId"
- Name: SRA_STAGING_S3_BUCKET_STACK_NAME
Value: !Ref pSRAStagingS3BucketStackName
- Name: SRA_REPO_URL
Value: !Ref pRepoURL
- Name: SRA_REPO_BRANCH_NAME
Value: !Ref pRepoBranch
Image: "aws/codebuild/standard:5.0"
PrivilegedMode: true
Type: "LINUX_CONTAINER"
ServiceRole: !GetAtt rCodeBuildRole.Arn
TimeoutInMinutes: 120
Source:
Type: NO_SOURCE
BuildSpec: !Sub |
version: 0.2
phases:
pre_build:
commands:
- echo Build started on `date`...
build:
commands:
- echo Build started on `date` in ${AWS::Region} region
- echo Cloning SRA code repository from $SRA_REPO_URL...
- git clone $SRA_REPO_URL
- echo Listing current directory...
- ls
- cd aws-security-reference-architecture-examples
- git checkout $SRA_REPO_BRANCH_NAME
- echo Showing current caller identity...
- aws sts get-caller-identity
- echo Deploying SRA staging bucket cloudformation template...
- aws cloudformation deploy --template-file ./aws_sra_examples/solutions/common/common_prerequisites/templates/sra-common-prerequisites-staging-s3-bucket.yaml --stack-name $SRA_STAGING_S3_BUCKET_STACK_NAME --capabilities CAPABILITY_NAMED_IAM
- echo Staging SRA solutions...
- ./aws_sra_examples/utils/packaging_scripts/stage_solution.sh
post_build:
commands:
- echo Build completed on `date`
rCommonPrerequisitesManagementAccountParametersStack:
Type: AWS::CloudFormation::Stack
Condition: cCommonPrerequisitesNotInstalled
DependsOn: rStartCodeBuildProjectCustomResource
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
TemplateURL: !Sub
- https://${SRAStagingS3BucketName}.s3.${AWS::Region}.${AWS::URLSuffix}/${pSRASolutionName}/templates/sra-common-prerequisites-management-account-parameters.yaml
- SRAStagingS3BucketName: !Sub ${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}
Tags:
- Key: sra-solution
Value: !Ref pSRASolutionName
Parameters:
pControlTower: !Ref pControlTower
pGovernedRegions: !Ref pGovernedRegions
pSecurityAccountId: !Ref pSecurityAccountId
pLogArchiveAccountId: !Ref pLogArchiveAccountId
rCommonPrerequisitesMainSsm:
Type: AWS::CloudFormation::Stack
Condition: cCommonPrerequisitesNotInstalled
DependsOn: rCommonPrerequisitesManagementAccountParametersStack
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
TemplateURL: !Sub
- https://${SRAStagingS3BucketName}.s3.${AWS::Region}.${AWS::URLSuffix}/${pSRASolutionName}/templates/sra-common-prerequisites-main-ssm.yaml
- SRAStagingS3BucketName: !Sub ${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}
Tags:
- Key: sra-solution
Value: !Ref pSRASolutionName
Parameters:
pCreateAWSControlTowerExecutionRole: !Ref pCreateAWSControlTowerExecutionRole
pControlTower: !Ref pControlTower
rCodeBuildRole:
Type: AWS::IAM::Role
Condition: cCommonPrerequisitesNotInstalled
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: Allow * in resource when required
- id: W28
reason: The role name is defined to identify automation resources
Properties:
RoleName: !Sub '${pCodeBuildRoleName}'
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- "sts:AssumeRole"
Policies:
- PolicyName: "logs-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
- !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*"
- PolicyName: "cloudformation-changeset-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudformation:CreateChangeSet
- cloudformation:DescribeChangeSet
- cloudformation:ExecuteChangeSet
- cloudformation:GetTemplateSummary
Resource:
- !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/*"
- !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:changeSet/*"
- PolicyName: "cloudformation-describe-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudformation:DescribeStacks
Resource: "*"
- PolicyName: "IAM-Access-Policy"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- iam:GetRole
- iam:PassRole
- iam:GetRolePolicy
- iam:PutRolePolicy
- iam:CreateRole
- iam:DeleteRolePolicy
- iam:DeleteRole
- iam:TagRole
Resource:
- !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/sra*"
- PolicyName: "lambda-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- lambda:GetFunction
- lambda:GetFunctionCodeSigningConfig
- lambda:GetRuntimeManagementConfig
- lambda:CreateFunction
- lambda:DeleteFunction
- lambda:TagResource
- lambda:InvokeFunction
Resource:
- !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:sra*"
- PolicyName: "s3-staging-bucket-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- s3:GetObject
- s3:PutObject
- s3:ListBucket
- s3:GetBucketAcl
- s3:GetBucketPolicy
- s3:DeleteBucket
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}"
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}/*"
- PolicyName: "s3-create-bucket-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- s3:PutBucketPolicy
- s3:PutBucketTagging
- s3:PutBucketPublicAccessBlock
- s3:GetEncryptionConfiguration
- s3:PutEncryptionConfiguration
- s3:PutBucketOwnershipControls
- s3:CreateBucket
- s3:PutBucketAcl
- s3:PutBucketObjectLockConfiguration
- s3:PutBucketVersioning
- s3:SetBucketEncryption
- s3:PutBucketEncryption
Resource:
- "arn:aws:s3:::*"
- PolicyName: "ssm-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- ssm:GetParameter
- ssm:GetParameters
- ssm:PutParameter
- ssm:AddTagsToResource
Resource:
- !Sub "arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/sra*"
rStartCodeBuildProjectCustomResource:
Condition: cCommonPrerequisitesNotInstalled
DependsOn: rCodeBuildProject
Type: Custom::LambdaCustomResource
Version: '1.0'
Properties:
ServiceToken: !GetAtt rStartCodeBuildProjectLambdaFunction.Arn
rStartCodeBuildProjectLambdaFunction:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W58
reason: Lambda role provides access to CloudWatch Logs
- id: W89
reason: Lambda does not need to communicate with VPC resources.
- id: W92
reason: Lambda does not need reserved concurrent executions.
checkov:
skip:
- id: CKV_AWS_115
comment: Lambda does not need reserved concurrent executions.
- id: CKV_AWS_116
comment: DLQ not needed, as Lambda function only triggered by CloudFormation events.
- id: CKV_AWS_117
comment: Lambda does not need to communicate with VPC resources.
- id: CKV_AWS_173
comment: Environment variables are not sensitive.
Type: AWS::Lambda::Function
Condition: cCommonPrerequisitesNotInstalled
Properties:
FunctionName: !Ref pCodeBuildProjectLambdaFunctionName
Description: Start SRA codebuild project
Architectures: !If
- cUseGraviton
- [arm64]
- !Ref AWS::NoValue
Handler: index.lambda_handler
Role: !GetAtt rStartCodeBuildProjectLambdaRole.Arn
Runtime: python3.9
Timeout: 900
Environment:
Variables:
LOG_LEVEL: !Ref pLambdaLogLevel
CODE_BUILD_PROJECT_NAME: !Ref pCodeBuildProjectName
SRA_STAGING_S3_BUCKET_NAME: !Sub ${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}
SRA_STAGING_S3_BUCKET_STACK_NAME: !Ref pSRAStagingS3BucketStackName
SRA_CUSTOM_RESOURCE_NAME: !Sub ${pCodeBuildProjectLambdaFunctionName}-Custom-Resource
Tags:
- Key: !Ref pSRASolutionTagKey
Value: !Ref pSRASolutionName
Code:
ZipFile: |
# type: ignore
"""Custom Resource to start codebuild project.
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
import logging
import os
import boto3
import cfnresponse
import time
from botocore.exceptions import ClientError
LOGGER = logging.getLogger(__name__)
log_level: str = os.environ.get("LOG_LEVEL", "INFO")
LOGGER.setLevel(log_level)
CODE_BUILD_PROJECT_NAME: str = os.environ.get("CODE_BUILD_PROJECT_NAME")
SRA_CUSTOM_RESOURCE_NAME: str = os.environ.get("SRA_CUSTOM_RESOURCE_NAME")
def start_build():
management_account_session = boto3.Session()
codebuild_client = management_account_session.client("codebuild")
response = codebuild_client.start_build(projectName=CODE_BUILD_PROJECT_NAME)
LOGGER.info({"API_Call": "codebuild:StartBuild", "API_Response": response})
buildId = response["build"]["id"]
return wait_for_build([buildId], codebuild_client)
def wait_for_build(BuildId, client):
buildWaitStatus = "FAILURE_WAIT_TIMEOUT"
counter = 0
while counter < 60:
time.sleep(10)
counter = counter + 1
buildStatus = get_build_status(BuildId, client)
if buildStatus == "SUCCEEDED":
buildWaitStatus = "SUCCESS"
break
elif buildStatus == "FAILED" or buildStatus == "FAULT" or buildStatus == "STOPPED" or buildStatus == "TIMED_OUT":
buildWaitStatus = "BUILD " + buildStatus + " (check codebuild project cloudwatch log group for details)"
break
return buildWaitStatus
def get_build_status(buildId, client):
build = client.batch_get_builds(ids=buildId)
return build["builds"][0]["buildStatus"]
def create_event(event, context):
try:
data = {"data": start_build()}
if data["data"] == "SUCCESS":
cfnresponse.send(event, context, cfnresponse.SUCCESS, data, SRA_CUSTOM_RESOURCE_NAME)
else:
reason = f"See the details in CloudWatch Log Stream: '{context.log_group_name} and CloudFormation Events'"
cfnresponse.send(event, context, cfnresponse.FAILED, data, SRA_CUSTOM_RESOURCE_NAME)
except Exception:
LOGGER.exception("Unexpected!")
reason = f"See the details in CloudWatch Log Stream: '{context.log_group_name}'"
cfnresponse.send(event, context, cfnresponse.FAILED, {}, SRA_CUSTOM_RESOURCE_NAME, reason=reason)
return SRA_CUSTOM_RESOURCE_NAME
def delete_event(event, context):
LOGGER.info("entered delete_event function. Nothing to do...")
cfnresponse.send(event, context, cfnresponse.SUCCESS, {"delete_operation": "succeeded deleting"}, SRA_CUSTOM_RESOURCE_NAME)
def lambda_handler(event, context):
LOGGER.info(event)
if event["RequestType"] == "Create":
LOGGER.info("CREATE EVENT!!")
create_event(event, context)
if event["RequestType"] == "Update":
LOGGER.info("UPDATE EVENT!!")
if event["RequestType"] == "Delete":
LOGGER.info("DELETE EVENT!!")
delete_event(event, context)
rStartCodeBuildProjectLambdaLogGroup:
DeletionPolicy: Retain
Type: AWS::Logs::LogGroup
Condition: cCommonPrerequisitesNotInstalled
UpdateReplacePolicy: Retain
Properties:
LogGroupName: !Sub /aws/lambda/${pCodeBuildProjectLambdaFunctionName}
KmsKeyId: !If
- cUsingKmsKey
- !Ref pLambdaLogGroupKmsKey
- !Ref AWS::NoValue
RetentionInDays: !Ref pLambdaLogGroupRetention
rStartCodeBuildProjectLambdaRole:
Type: AWS::IAM::Role
Condition: cCommonPrerequisitesNotInstalled
Metadata:
cfn_nag:
rules_to_suppress:
# - id: W11
# reason: Allow * in resource when required
- id: W28
reason: The role name is defined to identify automation resources
Properties:
RoleName: !Ref pCodeBuildProjectLambdaRoleName
Description: !Sub Role for '${pCodeBuildProjectLambdaRoleName}' Lambda function
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action: sts:AssumeRole
Principal:
Service:
- lambda.amazonaws.com
Tags:
- Key: !Ref pSRASolutionTagKey
Value: !Ref pSRASolutionName
Policies:
- PolicyName: codebuild-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: codebuildStartBuild
Effect: Allow
Action:
- codebuild:StartBuild
- codebuild:BatchGetBuilds
Resource: !GetAtt rCodeBuildProject.Arn
- PolicyName: CloudWatchLogGroup-access
PolicyDocument:
Version: 2012-10-17
Statement:
- Sid: CloudWatchLogs
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${pCodeBuildProjectLambdaFunctionName}:log-stream:*
- PolicyName: "s3-staging-bucket-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Action:
- s3:GetObject
- s3:PutObject
- s3:ListBucket
- s3:GetBucketAcl
- s3:GetBucketPolicy
- s3:GetObjectAcl
- s3:PutObjectAcl
- s3:DeleteBucket
- s3:DeleteObject
- s3:DeleteObjectVersion
- s3:GetBucketVersioning
- s3:DeleteBucketPolicy
- s3:ListBucketVersions
- s3:PutBucketVersioning
Resource:
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}"
- !Sub "arn:${AWS::Partition}:s3:::${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}/*"
- PolicyName: "lambda-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- lambda:DeleteFunction
- lambda:InvokeFunction
Resource:
- !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:sra*"
- PolicyName: "cloudformation-stack-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- cloudformation:DeleteStack
- cloudformation:DescribeStacks
Resource:
- !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/sra*"
- PolicyName: "IAM-access"
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- iam:DeleteRole
- iam:DeleteRolePolicy
Resource:
- !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/sra*"
rGuardDutySolutionStack:
Type: AWS::CloudFormation::Stack
DependsOn: WaitCondition
Condition: cDeployGuardDutySolution
DeletionPolicy: Delete
UpdateReplacePolicy: Delete
Properties:
TemplateURL: !Sub https://${pSRAStagingS3BucketNamePrefix}-${AWS::AccountId}-${AWS::Region}.s3.${AWS::Region}.${AWS::URLSuffix}/sra-guardduty-org/templates/sra-guardduty-org-main-ssm.yaml
Parameters:
pAutoEnableS3Logs: !Ref pAutoEnableS3Logs
pAutoEnableKubernetesAuditLogs: !Ref pAutoEnableKubernetesAuditLogs
pAutoEnableMalwareProtection: !Ref pAutoEnableMalwareProtection
pEnableRdsLoginEvents: !Ref pEnableRdsLoginEvents
pEnableRuntimeMonitoring: !Ref pEnableRuntimeMonitoring
pEnableEksAddonManagement: !Ref pEnableEksAddonManagement
pEnableEcsFargateAgentManagement: !Ref pEnableEcsFargateAgentManagement
pEnableEc2AgentManagement: !Ref pEnableEc2AgentManagement
pEnableLambdaNetworkLogs: !Ref pEnableLambdaNetworkLogs
pCreateLambdaLogGroup: !If [cCreateLambdaLogGroup, true, false]
pDisableGuardDuty: !If [cDisableGuardDuty, true, false]
pFindingPublishingFrequency: !Ref pGuardDutyFindingPublishingFrequency
pGuardDutyOrgDeliveryBucketPrefix: !Ref pGuardDutyOrgDeliveryBucketPrefix
pGuardDutyOrgDeliveryKeyAlias: !Ref pGuardDutyOrgDeliveryKeyAlias
pLambdaLogGroupKmsKey: !Ref pLambdaLogGroupKmsKey
pLambdaLogGroupRetention: !Ref pLambdaLogGroupRetention
pLambdaLogLevel: !Ref pLambdaLogLevel
pSRAAlarmEmail: !Ref pSRAAlarmEmail
pControlTowerRegionsOnly: !Ref pControlTowerRegionsOnly
pEnabledRegions: !Ref pEnabledRegions
CommonPrerequisitesMainSsmWaitHandle:
Condition: cCommonPrerequisitesNotInstalled
DependsOn: rCommonPrerequisitesMainSsm
Type: "AWS::CloudFormation::WaitConditionHandle"
WaitHandle:
Type: "AWS::CloudFormation::WaitConditionHandle"
WaitCondition:
Type: "AWS::CloudFormation::WaitCondition"
Properties:
Handle: !If [cCommonPrerequisitesNotInstalled, !Ref CommonPrerequisitesMainSsmWaitHandle, !Ref WaitHandle]
Timeout: "1"
Count: 0
Outputs:
oAuditAccountId:
Condition: cCommonPrerequisitesNotInstalled
Description: Audit Account ID
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oAuditAccountId]
oCustomerControlTowerRegions:
Condition: cCommonPrerequisitesNotInstalled
Description: Customer Control Tower Regions
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oCustomerControlTowerRegions]
oEnabledRegions:
Condition: cCommonPrerequisitesNotInstalled
Description: Enabled Regions
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oEnabledRegions]
oEnabledRegionsWithoutHomeRegion:
Condition: cCommonPrerequisitesNotInstalled
Description: Enabled Regions without Home Region
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oEnabledRegionsWithoutHomeRegion]
oHomeRegion:
Condition: cCommonPrerequisitesNotInstalled
Description: Control Tower Home Region
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oHomeRegion]
oLogArchiveAccountId:
Condition: cCommonPrerequisitesNotInstalled
Description: Log Archive Account ID
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oLogArchiveAccountId]
oManagementAccountId:
Condition: cCommonPrerequisitesNotInstalled
Description: Management Account ID
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oManagementAccountId]
oRootOrganizationalUnitId:
Condition: cCommonPrerequisitesNotInstalled
Description: Root Organizational Unit ID
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oRootOrganizationalUnitId]
oManagementAccountParametersLambdaFunctionArn:
Condition: cCommonPrerequisitesNotInstalled
Description: Management Account Parameters Lambda Function ARN
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oManagementAccountParametersLambdaFunctionArn]
oManagementAccountParametersLambdaLogGroupArn:
Condition: cCreateLogGroupAndCommonPrereqInstalled
Description: Management Account Parameters Lambda Log Group ARN
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oManagementAccountParametersLambdaLogGroupArn]
oManagementAccountParametersLambdaRoleArn:
Condition: cCommonPrerequisitesNotInstalled
Description: Management Account Parameters Lambda Role ARN
Value: !GetAtt [rCommonPrerequisitesManagementAccountParametersStack, Outputs.oManagementAccountParametersLambdaRoleArn]
oPublishingDestinationBucketName:
Condition: cDeployGuardDutySolution
Description: Publishing Destination Bucket Name
Value: !GetAtt [rGuardDutySolutionStack, Outputs.oPublishingDestinationBucketName]
oPublishingDestinationBucketArn:
Condition: cDeployGuardDutySolution
Description: Publishing Destination Bucket Name
Value: !GetAtt [rGuardDutySolutionStack, Outputs.oPublishingDestinationBucketArn]
oGuardDutyDeliveryKeyArn:
Condition: cDeployGuardDutySolution
Description: GuardDuty Delivery KMS Key ARN
Value: !GetAtt [rGuardDutySolutionStack, Outputs.oGuardDutyDeliveryKeyArn]