-
Notifications
You must be signed in to change notification settings - Fork 100
/
2-sat2-codebuild-prowler.yaml
1175 lines (1116 loc) · 40.6 KB
/
2-sat2-codebuild-prowler.yaml
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
AWSTemplateFormatVersion: 2010-09-09
Description: Self-Service Security Assessment Solutions (v2)
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: SATv2 options
Parameters:
- ProwlerScanType
- MultiAccountScan
- Reporting
- EmailAddress
- Label:
default: Advanced options
Parameters:
- ConcurrentAccountScans
- CodeBuildTimeout
- MultiAccountListOverride
- ProwlerOptions
- ProwlerRole
ParameterLabels:
ProwlerOptions:
default: Prowler options
ProwlerScanType:
default: Prowler scan type
ProwlerRole:
default: Prowler role
MultiAccountScan:
default: Multi-Account scan
MultiAccountListOverride:
default: Multi-Account list override
EmailAddress:
default: (Optional) Email address
Reporting:
default: Reporting
ConcurrentAccountScans:
default: Concurrent account scans
CodeBuildTimeout:
default: CodeBuild timeout
Parameters:
ProwlerOptions:
Description: 'Specify the parameters for Prowler. The --role and ARN will automatically be added to the end of the parameters you specify.'
Type: String
Default: aws --ignore-exit-code-3
ProwlerScanType:
Description: 'Specify which type of scan to perform. A basic scan runs 13 checks. An Intermediate scan runs all 109+ critical and high checks. A Full scan runs all 383+ checks.'
Type: String
AllowedValues:
- 'Basic'
- 'Intermediate'
- 'Full'
Default: 'Basic'
ProwlerRole:
Description: 'The role that Prowler should assume to perform the scan.'
Type: String
Default: ProwlerMemberRole
MultiAccountScan:
Description: 'Set this to true if you want to scan all accounts in your organization. You must have deployed the prerequisite template to provision a role, or specify a different ProwlerRole with the appropriate permissions.'
Type: String
AllowedValues:
- 'true'
- 'false'
Default: 'false'
MultiAccountListOverride:
Description: 'Specify a space delimited list of accounts to scan. Leaving this blank will scan all accounts in your organization.'
Type: String
Default: ''
EmailAddress:
Description: 'Specify an address if you want to receive an email when the scan completes.'
Type: String
Default: ''
Reporting:
Description: 'Set this to true if you want to summarize the Prowler reports using Amazon Athena. This is helpful when scanning multiple accounts.'
Type: String
AllowedValues:
- 'true'
- 'false'
Default: 'false'
ConcurrentAccountScans:
Description: 'For multi-account scans, specify the number of accounts to scan concurrently. This is useful for large organizations with many accounts. Selecting more than three may incur additional costs.'
Type: String
AllowedValues:
- 'Three'
- 'Six'
- 'Twelve'
- 'FortyEight'
Default: 'Three'
CodeBuildTimeout:
Description: 'Set the timeout for the CodeBuild job. The default is 300 minutes (5 hours).'
Type: Number
MinValue: 5
MaxValue: 2160
Default: 300
Conditions:
CreateProwlerRole: !Equals
- !Ref MultiAccountScan
- false
CreateEmailNotification: !Not [!Equals [!Ref EmailAddress, '']]
EnableReporting: !Equals
- !Ref Reporting
- true
Mappings:
ProwlerScanParameters:
Basic:
ProwlerOptions: >
-c
account_maintain_current_contact_details
awslambda_function_using_supported_runtimes
cloudtrail_multi_region_enabled
config_recorder_all_regions_enabled
ec2_securitygroup_allow_ingress_from_internet_to_any_port
guardduty_is_enabled
iam_password_policy_lowercase
iam_password_policy_number
iam_password_policy_symbol
iam_password_policy_uppercase
iam_root_mfa_enabled
iam_rotate_access_key_90_days
s3_bucket_public_access
Intermediate:
ProwlerOptions: --severity critical high
Full:
ProwlerOptions: ''
CodeBuildPerformanceOptionMap:
Three:
ParallelAccounts: 3
CodeBuildComputeType: BUILD_GENERAL1_SMALL
Six:
ParallelAccounts: 6
CodeBuildComputeType: BUILD_GENERAL1_MEDIUM
Twelve:
ParallelAccounts: 12
CodeBuildComputeType: BUILD_GENERAL1_LARGE
FortyEight:
ParallelAccounts: 48
CodeBuildComputeType: BUILD_GENERAL1_XLARGE
Resources:
#This is the role that CodeBuild assumes to perform the Prowler scan
ProwlerIntegrationCodeBuildRole:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: Role allows * in resource policy. The role needs broad, read-only privileges to review all resources. Only the CodeBuild role created as part of this solution can assume this role.
- id: W28
reason: Resource has an explicit name so Prowler can loop through and assume it in each account.
- id: W76
reason: SPCM for IAM policy is higher than 25 due to managed polices, and additional polices. Each section of the role has a comment with the Prowler documentation describing the need for the privileges.
Condition: CreateProwlerRole
Type: 'AWS::IAM::Role'
Properties:
Path: '/service-role/'
RoleName: ProwlerMemberRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:root'
Action:
- 'sts:AssumeRole'
Condition:
ArnEquals:
aws:PrincipalArn: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:role/service-role/ProwlerCodeBuildRole
ManagedPolicyArns:
# Prowler requires these managed polices to perform all the checks
# https://docs.prowler.cloud/en/latest/getting-started/requirements/
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/SecurityAudit'
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/job-function/ViewOnlyAccess'
Policies:
# Prowler requires these additional read-only permissions. They are documented in the Prowler documentation.
# https://github.com/prowler-cloud/prowler/blob/master/permissions/prowler-additions-policy.json
- PolicyName: ProwlerAdditions
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- account:Get*
- appstream:Describe*
- appstream:List*
- backup:List*
- cloudtrail:GetInsightSelectors
- codeartifact:List*
- codebuild:BatchGet*
- cognito-idp:GetUserPoolMfaConfig
- dlm:Get*
- drs:Describe*
- ds:Get*
- ds:Describe*
- ds:List*
- dynamodb:GetResourcePolicy
- ec2:GetEbsEncryptionByDefault
- ec2:GetSnapshotBlockPublicAccessState
- ec2:GetInstanceMetadataDefaults
- ecr:Describe*
- ecr:GetRegistryScanningConfiguration
- elasticfilesystem:DescribeBackupPolicy
- glue:GetConnections
- glue:GetSecurityConfiguration*
- glue:SearchTables
- lambda:GetFunction*
- lightsail:GetRelationalDatabases
- logs:FilterLogEvents
- macie2:GetMacieSession
- s3:GetAccountPublicAccessBlock
- shield:DescribeProtection
- shield:GetSubscriptionState
- securityhub:BatchImportFindings
- securityhub:GetFindings
- ssm:GetDocument
- ssm-incidents:List*
- support:Describe*
- tag:GetTagKeys
- wellarchitected:List*
Effect: Allow
Resource: '*'
- Action:
- apigateway:GET
Effect: Allow
Resource:
- !Sub arn:${AWS::Partition}:apigateway:*::/restapis/*
- !Sub arn:${AWS::Partition}:apigateway:*::/apis/*
ProwlerFindingsBucket:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W35
reason: No bucket logging needed.
UpdateReplacePolicy: Retain
DeletionPolicy: Retain
Type: AWS::S3::Bucket
Properties:
NotificationConfiguration:
EventBridgeConfiguration:
EventBridgeEnabled: !If [ EnableReporting, true, false ]
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
ProwlerFindingsBucketPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
Bucket: !Ref ProwlerFindingsBucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: AllowSSLRequestsOnly
Principal: '*'
Action: 's3:*'
Effect: Deny
Resource:
- !Sub '${ProwlerFindingsBucket.Arn}'
- !Sub '${ProwlerFindingsBucket.Arn}/*'
Condition:
Bool:
aws:SecureTransport: false
CodeBuildStartBuild:
Type: Custom::CodeBuildStartBuild
Properties:
ServiceToken: !GetAtt CodeBuildStartBuildLambda.Arn
ProjectName: !Ref ProwlerCodeBuild
CodeBuildStartBuildLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Condition:
StringEquals:
aws:SourceAccount: !Sub ${AWS::AccountId}
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: StartBuildInline
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'codebuild:StartBuild'
Resource: !GetAtt ProwlerCodeBuild.Arn
CodeBuildStartBuildLogsGroup:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W84
reason: CloudWatch Logs protects data at rest using encryption. All log groups are encrypted. By default, the CloudWatch Logs service manages the server-side encryption keys.
UpdateReplacePolicy: Delete
DeletionPolicy: Delete
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${CodeBuildStartBuildLambda}'
RetentionInDays: 7
CodeBuildStartBuildLambda:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W58
reason: The CodeBuildStartBuildLambdaRole gives Lambda access to write CloudWatch logs.
- id: W89
reason: Lambda is not deployed inside of a VPC. The Lambda function is used to start the CodeBuild job as a custom CloudFormation resource.
- id: W92
reason: Reserved concurrent executions is not set.
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !Sub ${CodeBuildStartBuildLambdaRole.Arn}
Timeout: 120
Runtime: python3.10
Code:
ZipFile: |
import os
import boto3
from botocore.exceptions import ClientError
import cfnresponse
def startBuild(event, context):
responseData = {}
cb = boto3.client('codebuild')
try:
print("Starting build...")
response = cb.start_build(projectName=event['ResourceProperties']['ProjectName'])
responseData['buildID'] = response['build']['id']
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except ClientError as e:
print("Failed to start build")
print(e)
cfnresponse.send(event, context, cfnresponse.FAILED, e.response)
def no_op(event, context):
responseData = {}
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
def lambda_handler(event,context):
print(event)
if event['RequestType'] == 'Create':
startBuild(event, context)
else:
no_op(event,context)
#This is the role that has privileges to assume Prowler member roles
ProwlerCodeBuildRole:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W11
reason: ListAccounts does not support resource types.
- id: W28
reason: This role is given an explicit name to further restrict the more permissive ProwlerMemberRole to only be assumed by this role.
Type: AWS::IAM::Role
Properties:
Path: '/service-role/'
RoleName: ProwlerCodeBuildRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: 'sts:AssumeRole'
Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Condition:
StringEquals:
aws:SourceArn: !Sub 'arn:${AWS::Partition}:codebuild:${AWS::Region}:${AWS::AccountId}:project/ProwlerCodeBuild'
Policies:
- PolicyName: LogGroup
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Effect: Allow
Resource: !Sub 'arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/*'
- PolicyName: UploadtoS3
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- s3:PutObject
Effect: Allow
Resource: !Sub '${ProwlerFindingsBucket.Arn}/*'
- PolicyName: AssumeRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Resource: !Sub 'arn:${AWS::Partition}:iam::*:role/service-role/ProwlerMemberRole'
- PolicyName: ListOrganizationAccounts
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- organizations:ListAccounts
- organizations:DescribeAccount
- organizations:ListTagsForResource
Effect: Allow
Resource: '*'
ProwlerCodeBuild:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W32
reason: CodeBuild uses the managed KMS key for S3.
Type: AWS::CodeBuild::Project
Properties:
Name: ProwlerCodeBuild
Environment:
ComputeType: !FindInMap [CodeBuildPerformanceOptionMap, !Ref ConcurrentAccountScans, 'CodeBuildComputeType']
Image: "aws/codebuild/amazonlinux2-x86_64-standard:5.0"
Type: "LINUX_CONTAINER"
EnvironmentVariables:
- Name: BUCKET_REPORT
Value: !Ref ProwlerFindingsBucket
Type: PLAINTEXT
- Name: PROWLER_OPTIONS
Value: !Ref 'ProwlerOptions'
Type: PLAINTEXT
- Name: PROWLER_SCAN_OPTIONS
Value: !FindInMap [ProwlerScanParameters, !Ref ProwlerScanType, 'ProwlerOptions']
Type: PLAINTEXT
- Name: PROWLER_ROLE
Value: !Ref ProwlerRole
Type: PLAINTEXT
- Name: MULTI_ACCOUNT_SCAN
Value: !Ref MultiAccountScan
Type: PLAINTEXT
- Name: MULTI_ACCOUNT_LIST_OVERRIDE
Value: !Ref MultiAccountListOverride
Type: PLAINTEXT
- Name: AWS_PARTITION
Value: !Sub ${AWS::Partition}
Type: PLAINTEXT
- Name: AWS_ACCOUNT_ID
Value: !Sub ${AWS::AccountId}
Type: PLAINTEXT
- Name: PARALLEL_ACCOUNTS
Value: !FindInMap [CodeBuildPerformanceOptionMap, !Ref ConcurrentAccountScans, 'ParallelAccounts']
Type: PLAINTEXT
Description: Run Prowler assessment
ServiceRole: !GetAtt ProwlerCodeBuildRole.Arn
TimeoutInMinutes: !Ref CodeBuildTimeout
Artifacts:
Type: NO_ARTIFACTS
Source:
Type: NO_SOURCE
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
python: 3.11
commands:
- echo "Installing Prowler and dependencies..."
- pip3 install prowler
- prowler -v
build:
commands:
- |
if [[ $MULTI_ACCOUNT_SCAN = 'true' ]]; then
echo "Running multi-account scan."
if [[ $MULTI_ACCOUNT_LIST_OVERRIDE != '' ]]; then
echo "Using account overrides."
account_list=$MULTI_ACCOUNT_LIST_OVERRIDE
elif [[ $MULTI_ACCOUNT_LIST_OVERRIDE = '' ]]; then
echo "Using accounts from aws organizations."
account_list=$(aws organizations list-accounts --query 'Accounts[?Status==`ACTIVE`].Id' --output text)
fi
echo "Using accounts $account_list."
for accountId in $account_list; do
test "$(jobs | wc -l)" -ge $PARALLEL_ACCOUNTS && wait || true
{
echo "Running Prowler as prowler $PROWLER_OPTIONS $PROWLER_SCAN_OPTIONS --role arn:$AWS_PARTITION:iam::$accountId:role/service-role/$PROWLER_ROLE "
prowler $PROWLER_OPTIONS $PROWLER_SCAN_OPTIONS --role arn:$AWS_PARTITION:iam::$accountId:role/service-role/$PROWLER_ROLE
} &
done
elif [[ $MULTI_ACCOUNT_SCAN != 'true' ]]; then
echo "Running a single account scan."
echo "Running Prowler as prowler $PROWLER_OPTIONS $PROWLER_SCAN_OPTIONS --role arn:$AWS_PARTITION:iam::$AWS_ACCOUNT_ID:role/service-role/$PROWLER_ROLE "
prowler $PROWLER_OPTIONS $PROWLER_SCAN_OPTIONS --role arn:$AWS_PARTITION:iam::$AWS_ACCOUNT_ID:role/service-role/$PROWLER_ROLE
fi
wait
post_build:
commands:
- echo "Uploading reports to S3..."
- aws s3 cp --exclude "*" --include "*.csv" --exclude "compliance**" output/ s3://$BUCKET_REPORT/csv/ --recursive
- aws s3 cp --exclude "*" --include "*.csv" output/compliance/ s3://$BUCKET_REPORT/compliance/ --recursive
- aws s3 cp --exclude "*" --include "*.ocsf.json" output/ s3://$BUCKET_REPORT/ocsf-json/ --recursive
- aws s3 cp --exclude "*" --include "*.json" --exclude "*.ocsf.json" --exclude "*.asff.json" output/ s3://$BUCKET_REPORT/json/ --recursive
- aws s3 cp --exclude "*" --include "*.html" output/ s3://$BUCKET_REPORT/html/ --recursive
- aws s3 cp --exclude "*" --include "*.asff.json" output/ s3://$BUCKET_REPORT/asff-json/ --recursive
- echo "Done!"
ProwlerLogGroup:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W84
reason: CloudWatch Logs protects data at rest using encryption. All log groups are encrypted. By default, the CloudWatch Logs service manages the server-side encryption keys.
UpdateReplacePolicy: Delete
DeletionPolicy: Delete
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/codebuild/${ProwlerCodeBuild}'
RetentionInDays: 7
ProwlerScanNotificationTopic:
Metadata:
cfn_nag:
rules_to_suppress:
- id: W47
reason: Topic is used to send notification that the scan is done. Topic does not use AWS KMS CMK or default key. If SNS uses the default AWS KMS key alias/aws/sns, then EventBridge can't publish messages to the SNS topic. The default KMS key policy for SNS doesn't allow EventBridge kms:decrypt and kms:GenerateDataKey.
Condition: CreateEmailNotification
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint: !Ref EmailAddress
Protocol: email
ProwlerSnsNotificationsPolicy:
Condition: CreateEmailNotification
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Id: snsNotificationsPolicy
Version: '2012-10-17'
Statement:
- Sid: Allow events
Effect: Allow
Principal:
Service: 'events.amazonaws.com'
Action:
- sns:Publish
Resource: !Ref ProwlerScanNotificationTopic
Topics:
- !Ref ProwlerScanNotificationTopic
CodeBuildStateChangeRule:
Condition: CreateEmailNotification
Type: AWS::Events::Rule
Properties:
EventBusName: default
EventPattern:
source:
- aws.codebuild
detail-type:
- CodeBuild Build State Change
detail:
build-status:
- SUCCEEDED
- FAILED
- STOPPED
project-name:
- !Ref ProwlerCodeBuild
State: ENABLED
Targets:
- Id: toSNS
Arn: !Ref ProwlerScanNotificationTopic
InputTransformer:
InputPathsMap:
build-status: $.detail.build-status
bucket: $.detail.additional-information.environment.environment-variables[0].value
InputTemplate: >-
"The Prowler scan has <build-status>."
"You can view your results in the <bucket> bucket."
GlueDatabaseSATv2Findings:
Condition: EnableReporting
Type: AWS::Glue::Database
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseInput:
Name: !Ref ProwlerFindingsBucket
Description: !Sub "SATv2 assessment results in the ${ProwlerFindingsBucket}"
GlueTableProwlerResults:
Condition: EnableReporting
Type: AWS::Glue::Table
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref GlueDatabaseSATv2Findings
TableInput:
Name: "prowler"
Description: "Results of the Prowler scan from SATv2"
TableType: EXTERNAL_TABLE
Parameters: {
"skip.header.line.count": "1",
"classification": "csv",
}
StorageDescriptor:
Columns:
- Name: auth_method
Type: string
- Name: timestamp
Type: string
- Name: account_uid
Type: string
- Name: account_namse
Type: string
- Name: account_email
Type: string
- Name: account_organization_uid
Type: string
- Name: account_organization_name
Type: string
- Name: account_tags
Type: string
- Name: finding_uid
Type: string
- Name: provider
Type: string
- Name: check_id
Type: string
- Name: check_title
Type: string
- Name: check_type
Type: string
- Name: status
Type: string
- Name: status_extended
Type: string
- Name: muted
Type: boolean
- Name: service_name
Type: string
- Name: subservice_name
Type: string
- Name: severity
Type: string
- Name: resource_type
Type: string
- Name: resource_uid
Type: string
- Name: resource_name
Type: string
- Name: resource_details
Type: string
- Name: resource_tags
Type: string
- Name: partition
Type: string
- Name: region
Type: string
- Name: description
Type: string
- Name: risk
Type: string
- Name: related_url
Type: string
- Name: remediation_recommendation_text
Type: string
- Name: remediation_recommendation_url
Type: string
- Name: remediation_code_nativeiac
Type: string
- Name: remediation_code_terraform
Type: string
- Name: remediation_code_cli
Type: string
- Name: remediation_code_other
Type: string
- Name: compliance
Type: string
- Name: categories
Type: string
- Name: depends_on
Type: string
- Name: related_to
Type: string
- Name: notes
Type: string
- Name: prowler_version
Type: string
Location: !Sub s3://${ProwlerFindingsBucket}/csv
InputFormat: org.apache.hadoop.mapred.TextInputFormat
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Compressed: False
StoredAsSubDirectories: False
SerdeInfo:
SerializationLibrary: org.apache.hadoop.hive.serde2.OpenCSVSerde
Parameters: {
"escapeChar": "\\",
"quoteChar": "\"",
"separatorChar": ";"
}
Retention: 0
LakeFormationPermissionsLambda:
Condition: EnableReporting
Type: AWS::LakeFormation::Permissions
Properties:
DataLakePrincipal:
DataLakePrincipalIdentifier: !Sub ${AthenaStartQueryLambdaRole.Arn}
Permissions:
- SELECT
Resource:
TableResource:
DatabaseName: !Ref GlueDatabaseSATv2Findings
Name: !Ref GlueTableProwlerResults
SATv2Reporting:
Condition: EnableReporting
Type: AWS::Athena::WorkGroup
Properties:
Name: !Ref GlueDatabaseSATv2Findings
RecursiveDeleteOption: True
State: ENABLED
WorkGroupConfiguration:
PublishCloudWatchMetricsEnabled: false
RequesterPaysEnabled: false
ResultConfiguration:
OutputLocation: !Sub s3://${ProwlerFindingsBucket}/athena_results
EnforceWorkGroupConfiguration: false
qProwlerOrgSummary:
Condition: EnableReporting
Type: AWS::Athena::NamedQuery
Properties:
Database: !Ref GlueDatabaseSATv2Findings
Description: "Count the number of recommendations across all assessed accounts"
Name: "Prowler organization summary"
QueryString: !Sub |
-- Count the number of recommendations across all assessed accounts.
SELECT
check_id,
count(*) as count
FROM
"${GlueDatabaseSATv2Findings}"."prowler"
WHERE
status = 'FAIL'
GROUP BY
check_id
ORDER BY
count desc
WorkGroup: !Ref SATv2Reporting
AthenaStartQueryLambdaRole:
Condition: EnableReporting
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Condition:
StringEquals:
aws:SourceAccount: !Sub ${AWS::AccountId}
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: AccessToAthena
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'athena:StartQueryExecution'
Resource: !Sub arn:${AWS::Partition}:athena:${AWS::Region}:${AWS::AccountId}:workgroup/${SATv2Reporting}
- Effect: Allow
Action:
- s3:GetBucketLocation
- s3:GetObject
- s3:ListBucket
- s3:ListBucketMultipartUploads
- s3:AbortMultipartUpload
- s3:PutObject
- s3:ListMultipartUploadPart
Resource:
- !GetAtt ProwlerFindingsBucket.Arn
- !Sub ${ProwlerFindingsBucket.Arn}/*
- Effect: Allow
Action:
- 'glue:GetTable'
- 'glue:GetDatabase'
Resource:
- !Sub arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:catalog
- !Sub arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:database/${GlueDatabaseSATv2Findings}
- !Sub arn:${AWS::Partition}:glue:${AWS::Region}:${AWS::AccountId}:table/${GlueDatabaseSATv2Findings}/${GlueTableProwlerResults}
AthenaStartQueryLogGroup:
Condition: EnableReporting
Metadata:
cfn_nag:
rules_to_suppress:
- id: W84
reason: CloudWatch Logs protects data at rest using encryption. All log groups are encrypted. By default, the CloudWatch Logs service manages the server-side encryption keys.
UpdateReplacePolicy: Delete
DeletionPolicy: Delete
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${AthenaStartQueryLambda}'
RetentionInDays: 7
AthenaStartQueryLambda:
Condition: EnableReporting
Metadata:
cfn_nag:
rules_to_suppress:
- id: W58
reason: The AthenaStartQueryLambdaRole gives Lambda access to write CloudWatch logs.
- id: W89
reason: Lambda is not deployed inside of a VPC. The Lambda function is used to start the CodeBuild job as a custom CloudFormation resource.
- id: W92
reason: Reserved concurrent executions is not set.
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !Sub ${AthenaStartQueryLambdaRole.Arn}
Timeout: 120
Environment:
Variables:
ATHENA_WORKGROUP: !Ref SATv2Reporting
BUCKET_REPORT: !Ref ProwlerFindingsBucket
Runtime: python3.10
Code:
ZipFile: |
import os
import boto3
from botocore.exceptions import ClientError
S3_BUCKET = os.environ['BUCKET_REPORT']
WORKGROUP = os.environ['ATHENA_WORKGROUP']
def startQuery(event, context):
responseData = {}
athena = boto3.client('athena')
try:
print("Starting query...")
response = athena.start_query_execution(
QueryString="""SELECT * FROM \"AwsDataCatalog\".\"{}\".\"prowler\"""".format(S3_BUCKET),
WorkGroup=WORKGROUP,
ResultConfiguration={'OutputLocation': f's3://{S3_BUCKET}/reports'}
)
print(response)
except ClientError as e:
print("Failed to start query")
print(e)
def lambda_handler(event,context):
print(event)
startQuery(event, context)
AthenaStartQueryLambdaInvokePermission:
Condition: EnableReporting
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt AthenaStartQueryLambda.Arn
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
SourceArn: !GetAtt CodeBuildCompleteRunSummary.Arn
CodeBuildCompleteRunSummary:
Condition: EnableReporting
Type: AWS::Events::Rule
Properties:
EventBusName: default
EventPattern:
source:
- aws.codebuild
detail-type:
- CodeBuild Build State Change
detail:
build-status:
- SUCCEEDED
project-name:
- !Ref ProwlerCodeBuild
State: ENABLED
Targets:
- Id: AthenaStartQueryLambda
Arn: !GetAtt AthenaStartQueryLambda.Arn
AthenaSummaryQueryStateChangeRule:
Condition: CreateEmailNotification
Type: AWS::Events::Rule
Properties:
EventBusName: default
EventPattern:
source:
- aws.athena
detail-type:
- Athena Query State Change
detail:
currentState:
- SUCCEEDED
- FAILED
workgroupName:
- !Ref ProwlerFindingsBucket
State: ENABLED
Targets:
- Id: toSNS
Arn: !Ref ProwlerScanNotificationTopic
InputTransformer:
InputPathsMap:
status: $.detail.currentState
InputTemplate: !Sub >-
"The query to summarize reporting has <status>."
"You can view your results in the ${ProwlerFindingsBucket}/reports bucket."
# PPTX reporting
ProwlerReportingLambdaRole:
Condition: EnableReporting
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Condition:
StringEquals:
aws:SourceAccount: !Sub ${AWS::AccountId}
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: AccessToS3
PolicyDocument:
Statement:
- Effect: Allow
Action:
- s3:GetBucketLocation
- s3:GetObject
- s3:ListBucket
- s3:ListBucketMultipartUploads
- s3:AbortMultipartUpload
- s3:PutObject
- s3:ListMultipartUploadPart
Resource:
- !GetAtt ProwlerFindingsBucket.Arn
- !Sub ${ProwlerFindingsBucket.Arn}/*
- PolicyName: AccessToCodeBuild
PolicyDocument:
Statement:
- Effect: Allow
Action:
- 'codebuild:StartBuild'
Resource: !GetAtt ProwlerReportingCodeBuild.Arn
ProwlerReportingLogGroup:
Condition: EnableReporting
Metadata:
cfn_nag:
rules_to_suppress:
- id: W84
reason: CloudWatch Logs protects data at rest using encryption. All log groups are encrypted. By default, the CloudWatch Logs service manages the server-side encryption keys.
UpdateReplacePolicy: Delete
DeletionPolicy: Delete
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${ProwlerReportingLambda}'
RetentionInDays: 7
ProwlerReportingLambda: