-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2-aiml-security-codebuild.yaml
More file actions
620 lines (588 loc) · 21.6 KB
/
2-aiml-security-codebuild.yaml
File metadata and controls
620 lines (588 loc) · 21.6 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
AWSTemplateFormatVersion: 2010-09-09
Description: AIML Multi-Account Security Assessment Solution
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: ReSCO Assessment Options
Parameters:
- MultiAccountScan
- MultiAccountListOverride
- EmailAddress
- Label:
default: Advanced Options
Parameters:
- ConcurrentAccountScans
- CodeBuildTimeout
- ReSCORole
- GitHubRepoUrl
- GitHubBranch
Parameters:
GitHubRepoUrl:
Type: String
Description: GitHub repository URL
Default: https://github.com/aws-samples/sample-resco-aiml-assessment.git
AllowedPattern: ^https:\/\/github\.com\/[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+(\.git)?$
ConstraintDescription: Must be a valid GitHub repository URL (e.g., https://github.com/owner/repo or https://github.com/owner/repo.git)
GitHubBranch:
Type: String
Description: GitHub branch to build from
Default: main
ReSCORole:
Description: "The role that ReSCO should assume to perform the assessment."
Type: String
Default: ReSCOAIMLMemberRole
MultiAccountScan:
Description: "Set this to true if you want to scan all accounts in your organization."
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 assessment completes."
Type: String
Default: ""
AllowedPattern: ^$|^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
ConstraintDescription: Must be a valid email address or leave empty
ConcurrentAccountScans:
Description: "For multi-account scans, specify the number of accounts to scan concurrently."
Type: String
AllowedValues:
- "Three"
- "Six"
- "Twelve"
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:
CreateReSCORole: !Equals
- !Ref MultiAccountScan
- false
CreateEmailNotification: !Not [!Equals [!Ref EmailAddress, ""]]
Mappings:
CodeBuildPerformanceOptionMap:
Three:
ParallelAccounts: 3
CodeBuildComputeType: BUILD_GENERAL1_SMALL
Six:
ParallelAccounts: 6
CodeBuildComputeType: BUILD_GENERAL1_MEDIUM
Twelve:
ParallelAccounts: 12
CodeBuildComputeType: BUILD_GENERAL1_LARGE
Resources:
# Local ReSCO role for single account assessments
ReSCOMemberRole:
Condition: CreateReSCORole
Type: "AWS::IAM::Role"
Properties:
Path: "/service-role/"
RoleName: ReSCOAIMLMemberRole
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/ReSCOMultiAccountCodeBuildRole
Policies:
- PolicyName: ReSCOAIMLAssessmentPermissions
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- iam:ListRoles
- iam:ListUsers
- iam:ListAttachedRolePolicies
- iam:ListAttachedUserPolicies
- iam:ListRolePolicies
- iam:ListUserPolicies
- iam:GetRolePolicy
- iam:GetUserPolicy
- iam:GetPolicy
- iam:GetPolicyVersion
- iam:GenerateServiceLastAccessedDetails
- iam:GetServiceLastAccessedDetails
- sts:GetCallerIdentity
- bedrock:ListGuardrails
- bedrock:GetGuardrail
- bedrock:GetModelInvocationLoggingConfiguration
- bedrock:ListPrompts
- bedrock:GetPrompt
- bedrock:ListAgents
- bedrock:GetAgent
- sagemaker:ListNotebookInstances
- sagemaker:DescribeNotebookInstance
- sagemaker:ListDomains
- sagemaker:DescribeDomain
- sagemaker:ListTrainingJobs
- sagemaker:DescribeTrainingJob
- sagemaker:ListModelPackageGroups
- sagemaker:ListModelPackages
- sagemaker:ListFeatureGroups
- sagemaker:ListPipelines
- sagemaker:ListPipelineExecutions
- sagemaker:ListProcessingJobs
- sagemaker:DescribeProcessingJob
- sagemaker:ListMonitoringSchedules
- sagemaker:DescribeMonitoringSchedule
- cloudtrail:ListTrails
- cloudtrail:GetTrail
- cloudtrail:GetEventSelectors
- lambda:ListFunctions
- ecs:ListClusters
- ecs:ListTasks
- ecs:DescribeTasks
- ec2:DescribeVpcEndpoints
- ec2:DescribeVpcs
- kms:DescribeKey
- kms:ListAliases
- guardduty:GetFindings
- guardduty:ListFindings
- guardduty:ListDetectors
- guardduty:GetDetector
- guardduty:GetFindingsStatistics
- guardduty:ListPublishingDestinations
- guardduty:ListTagsForResource
- guardduty:GetMemberDetectors
- guardduty:DescribeMalwareScans
- guardduty:GetRemainingFreeTrialDays
- guardduty:GetUsageStatistics
# Bedrock AgentCore Permissions
- bedrock-agentcore:ListAgentRuntimes
- bedrock-agentcore:GetAgentRuntime
- bedrock-agentcore:ListMemories
- bedrock-agentcore:GetMemory
- bedrock-agentcore:ListGateways
# ECR Permissions for AgentCore encryption checks
- ecr:DescribeRepositories
- ecr:GetRepositoryPolicy
# CloudWatch Logs Permissions for AgentCore observability checks
- logs:DescribeLogGroups
- logs:DescribeLogStreams
# Additional EC2 Permissions for AgentCore VPC checks
- ec2:DescribeSubnets
- ec2:DescribeRouteTables
- ec2:DescribeNatGateways
Resource: "*"
# S3 bucket for assessment results
ReSCOAssessmentBucket:
Type: AWS::S3::Bucket
Properties:
VersioningConfiguration:
Status: Enabled
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
ReSCOAssessmentBucketPolicy:
Type: "AWS::S3::BucketPolicy"
Properties:
Bucket: !Ref ReSCOAssessmentBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowSSLRequestsOnly
Principal: "*"
Action: "s3:*"
Effect: Deny
Resource:
- !Sub "${ReSCOAssessmentBucket.Arn}"
- !Sub "${ReSCOAssessmentBucket.Arn}/*"
Condition:
Bool:
aws:SecureTransport: false
# CodeBuild role for running assessments
ReSCOMultiAccountCodeBuildRole:
Type: AWS::IAM::Role
Properties:
Path: "/service-role/"
RoleName: ReSCOMultiAccountCodeBuildRole
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action: "sts:AssumeRole"
Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
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
- s3:GetObject
Effect: Allow
Resource: !Sub "${ReSCOAssessmentBucket.Arn}/*"
- Action:
- s3:GetObject
- s3:ListBucket
Effect: Allow
Resource:
- !Sub "arn:${AWS::Partition}:s3:::resco-aiml-security-*"
- !Sub "arn:${AWS::Partition}:s3:::resco-aiml-security-*/*"
- PolicyName: AssumeRole
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Resource: !Sub "arn:${AWS::Partition}:iam::*:role/service-role/ReSCOAIMLMemberRole"
- PolicyName: ListOrganizationAccounts
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- organizations:ListAccounts
- organizations:DescribeAccount
- organizations:ListTagsForResource
Effect: Allow
Resource: "*"
- PolicyName: CloudFormationPermissions
PolicyDocument:
Version: "2012-10-17"
Statement:
- Action:
- cloudformation:CreateStack
- cloudformation:UpdateStack
- cloudformation:DeleteStack
- cloudformation:DescribeStacks
- cloudformation:DescribeStackEvents
- cloudformation:DescribeStackResources
- cloudformation:GetTemplate
- cloudformation:GetTemplateSummary
- cloudformation:ListStackResources
- cloudformation:CreateChangeSet
- cloudformation:DescribeChangeSet
- cloudformation:ExecuteChangeSet
- cloudformation:DeleteChangeSet
- cloudformation:ListStacks
Effect: Allow
Resource:
- !Sub "arn:${AWS::Partition}:cloudformation:*:${AWS::AccountId}:stack/resco-aiml-*/*"
- !Sub "arn:${AWS::Partition}:cloudformation:*:${AWS::AccountId}:stack/aws-sam-cli-managed-default/*"
- Action:
- cloudformation:GetTemplateSummary
- cloudformation:CreateChangeSet
Effect: Allow
Resource:
- !Sub "arn:${AWS::Partition}:cloudformation:*:aws:transform/Serverless-2016-10-31"
- Action:
- cloudformation:GetTemplateSummary
- cloudformation:ListStacks
Effect: Allow
Resource: "*"
- PolicyName: SAMPermissions
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: LambdaPermissions
Action:
- lambda:CreateFunction
- lambda:DeleteFunction
- lambda:GetFunction
- lambda:GetFunctionConfiguration
- lambda:UpdateFunctionCode
- lambda:UpdateFunctionConfiguration
- lambda:AddPermission
- lambda:RemovePermission
- lambda:TagResource
- lambda:UntagResource
- lambda:ListTags
- lambda:InvokeFunction
- lambda:PublishVersion
- lambda:GetPolicy
Effect: Allow
Resource: '*'
- Sid: IAMPermissions
Action:
- iam:CreateRole
- iam:DeleteRole
- iam:GetRole
- iam:AttachRolePolicy
- iam:DetachRolePolicy
- iam:PutRolePolicy
- iam:DeleteRolePolicy
- iam:GetRolePolicy
- iam:TagRole
- iam:UntagRole
- iam:ListRolePolicies
- iam:ListAttachedRolePolicies
Effect: Allow
Resource: '*'
- Sid: IAMPassRole
Action:
- iam:PassRole
Effect: Allow
Resource:
- !Sub 'arn:${AWS::Partition}:iam::*:role/resco-aiml-*'
- Sid: StepFunctionsPermissions
Action:
- states:CreateStateMachine
- states:DeleteStateMachine
- states:DescribeStateMachine
- states:UpdateStateMachine
- states:TagResource
- states:UntagResource
- states:ListStateMachines
- states:StartExecution
- states:DescribeExecution
- states:ListExecutions
Effect: Allow
Resource: '*'
- Sid: S3Permissions
Action:
- s3:CreateBucket
- s3:DeleteBucket
- s3:PutBucketPolicy
- s3:GetBucketPolicy
- s3:DeleteBucketPolicy
- s3:PutBucketVersioning
- s3:PutBucketPublicAccessBlock
- s3:GetBucketPublicAccessBlock
- s3:PutBucketAcl
- s3:GetBucketAcl
- s3:PutBucketTagging
- s3:GetBucketTagging
- s3:PutBucketNotification
- s3:GetBucketNotification
- s3:PutBucketLogging
- s3:GetBucketLogging
- s3:PutEncryptionConfiguration
- s3:GetEncryptionConfiguration
- s3:ListBucket
- s3:GetBucketLocation
- s3:GetBucketVersioning
- s3:PutObject
- s3:GetObject
- s3:DeleteObject
- s3:DeleteObjectVersion
Effect: Allow
Resource: "*"
# CodeBuild project for running assessments
ReSCOMultiAccountCodeBuild:
Type: AWS::CodeBuild::Project
Properties:
Name: ReSCOMultiAccountCodeBuild
Environment:
ComputeType:
!FindInMap [
CodeBuildPerformanceOptionMap,
!Ref ConcurrentAccountScans,
"CodeBuildComputeType",
]
Image: "aws/codebuild/amazonlinux2-x86_64-standard:4.0"
Type: "LINUX_CONTAINER"
EnvironmentVariables:
- Name: BUCKET_REPORT
Value: !Ref ReSCOAssessmentBucket
Type: PLAINTEXT
- Name: GITHUB_REPO_URL
Value: !Ref GitHubRepoUrl
Type: PLAINTEXT
- Name: GITHUB_BRANCH
Value: !Ref GitHubBranch
Type: PLAINTEXT
- Name: RESCO_ROLE
Value: !Ref ReSCORole
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 ReSCO AIML assessment
ServiceRole: !GetAtt ReSCOMultiAccountCodeBuildRole.Arn
TimeoutInMinutes: !Ref CodeBuildTimeout
Artifacts:
Type: NO_ARTIFACTS
SourceVersion: !Ref GitHubBranch
Source:
Type: GITHUB
Location: !Ref GitHubRepoUrl
GitCloneDepth: 1
# Lambda function to start CodeBuild
CodeBuildStartBuildLambdaRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action:
- "sts:AssumeRole"
Path: /
ManagedPolicyArns:
- !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: StartBuildInline
PolicyDocument:
Statement:
- Effect: Allow
Action:
- "codebuild:StartBuild"
Resource: !GetAtt ReSCOMultiAccountCodeBuild.Arn
CodeBuildStartBuildLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt CodeBuildStartBuildLambdaRole.Arn
Timeout: 120
Runtime: python3.12
Code:
ZipFile: |
import boto3
import logging
from botocore.exceptions import ClientError
import cfnresponse
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def startBuild(event, context):
responseData = {}
try:
project_name = event.get('ResourceProperties', {}).get('ProjectName')
if not project_name:
raise ValueError("ProjectName is required")
cb = boto3.client('codebuild')
logger.info(f"Starting build for project: {project_name}")
response = cb.start_build(projectName=project_name)
responseData['buildID'] = response['build']['id']
logger.info(f"Build started: {responseData['buildID']}")
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
except ClientError as e:
error_msg = e.response['Error']['Message']
logger.error(f"AWS error: {error_msg}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': error_msg})
except Exception as e:
logger.error(f"Error: {str(e)}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})
def no_op(event, context):
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
def lambda_handler(event, context):
logger.info(f"Request type: {event.get('RequestType')}")
try:
if event['RequestType'] == 'Create':
startBuild(event, context)
else:
no_op(event, context)
except Exception as e:
logger.error(f"Unhandled error: {str(e)}")
cfnresponse.send(event, context, cfnresponse.FAILED, {'Error': str(e)})
CodeBuildStartBuild:
Type: Custom::CodeBuildStartBuild
DependsOn: ReSCOAssessmentBucketPolicy
Properties:
ServiceToken: !GetAtt CodeBuildStartBuildLambda.Arn
ProjectName: !Ref ReSCOMultiAccountCodeBuild
# SNS topic for notifications (optional)
ReSCONotificationTopic:
Condition: CreateEmailNotification
Type: AWS::SNS::Topic
Properties:
Subscription:
- Endpoint: !Ref EmailAddress
Protocol: email
ReSCOSnsNotificationsPolicy:
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 ReSCONotificationTopic
Topics:
- !Ref ReSCONotificationTopic
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 ReSCOMultiAccountCodeBuild
State: ENABLED
Targets:
- Id: toSNS
Arn: !Ref ReSCONotificationTopic
InputTransformer:
InputPathsMap:
build-status: $.detail.build-status
bucket: $.detail.additional-information.environment.environment-variables[0].value
InputTemplate: >-
"The ReSCO AIML assessment has <build-status>."
"You can view your results in the <bucket> bucket."
Outputs:
AccountID:
Description: AWS Account ID where the AI-ML Security Assessment is executed from
Value: !Ref AWS::AccountId
AssessmentBucket:
Description: S3 bucket containing assessment results (HTML reports and CSV data)
Value: !Ref ReSCOAssessmentBucket
CodeBuildProjectName:
Description: CodeBuild project name for running assessments
Value: !Ref ReSCOMultiAccountCodeBuild