-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-anchore-fargate.yml
718 lines (667 loc) · 22.1 KB
/
02-anchore-fargate.yml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: This AWS CloudFormation Template configures an Anchore service that is used for the Container DevSecOps workshop.
Parameters:
ResourceName:
Type: String
Default: container-devsecops-wksp
AllowedValues:
- container-devsecops-wksp
Description: Prefix of Resources created for this workshop.
BucketName:
Type: String
Default: sa-security-specialist-workshops-us-east-2
Description: Source bucket for workshop CloudFormation yaml's
Resources:
### Cloud9 IDE
Cloud9IDE:
Type: AWS::Cloud9::EnvironmentEC2
Properties:
Description: This is the IDE you will be using to complete the Container DevSecOps workshop.
InstanceType: t2.small
Name: !Join [ '-', [ !Ref ResourceName, 'ide' ] ]
SubnetId: !ImportValue 'AnchoreVpcStack:PublicSubnet1'
### Anchore ECR Repository
AnchoreRepository:
Type: AWS::ECR::Repository
Properties:
RepositoryName: !Join [ '-', [ !Ref ResourceName, 'anchore' ] ]
AnchoreCodeBuildRole:
Type: AWS::IAM::Role
Properties:
RoleName: AnchoreCodeBuildRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- codebuild.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
-
PolicyName: ServicePolicy
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: '*'
-
Effect: Allow
Action:
- ecr:*
Resource: '*'
-
Effect: Allow
Action:
- s3:PutObject
- s3:GetObject
- s3:ListObject
Resource: '*'
AnchoreCodeBuild:
Type: AWS::CodeBuild::Project
Properties:
Artifacts:
Type:
NO_ARTIFACTS
Environment:
ComputeType: BUILD_GENERAL1_SMALL
Image: aws/codebuild/standard:2.0
PrivilegedMode: True
Type: LINUX_CONTAINER
ImagePullCredentialsType: CODEBUILD
EnvironmentVariables:
- Name: IMAGE
Value: !Sub
- ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${Repo}
- { Repo: !Ref AnchoreRepository}
Name: !Join [ '-', [ !Ref ResourceName, 'anchore', 'build' ] ]
ServiceRole: !GetAtt AnchoreCodeBuildRole.Arn
Source:
Type: S3
Location: !Join [ '/', [ !Ref BucketName, 'devsecops/containers/anchore-build.zip' ] ]
BuildSpec: |
version: 0.2
phases:
install:
runtime-versions:
docker: 18
python: 3.7
pre_build:
commands:
- curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
- apt-get update && apt-get install -y python-dev
- curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
- python3 get-pip.py
- pip3 install awscli
- $(aws ecr get-login --no-include-email)
build:
commands:
- docker build $CODEBUILD_SRC_DIR -t $IMAGE
- docker push $IMAGE
CodeBuildStarter:
Type: Custom::CodeBuildStarter
Properties:
ServiceToken: !GetAtt CodeBuildStarterLambda.Arn
ProjectName: !Ref AnchoreCodeBuild
CodeBuildStarterLambdaRole:
Type: AWS::IAM::Role
Properties:
RoleName: CodeBuildStarterLambdaRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
-
PolicyName: Policy
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- codebuild:*
Resource: '*'
CodeBuildStarterLambda:
Type: AWS::Lambda::Function
Properties:
FunctionName: !Join [ '-', [ !Ref ResourceName, 'codebuild', 'starter' ] ]
Role: !GetAtt CodeBuildStarterLambdaRole.Arn
Runtime: python3.7
Handler: index.handler
Code:
ZipFile: |
import json
import boto3
from botocore.vendored import requests
codebuild_client = boto3.client('codebuild')
def handler(event, context):
try:
if event['RequestType'] == 'Create':
response = codebuild_client.start_build(
projectName=event['ResourceProperties']['ProjectName']
)
send(event, context, "SUCCESS")
elif event['RequestType'] == 'Update':
response = codebuild_client.start_build(
projectName=event['ResourceProperties']['ProjectName']
)
send(event, context, "SUCCESS")
elif event['RequestType'] == 'Delete':
send(event, context, "SUCCESS")
else:
send(event, context, "FAILED")
except:
send(event, context, "FAILED")
def send(event, context, responseStatus):
responseUrl = event['ResponseURL']
print(responseUrl)
responseBody = {}
responseBody['Status'] = responseStatus
responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name
responseBody['PhysicalResourceId'] = context.log_stream_name
responseBody['StackId'] = event['StackId']
responseBody['RequestId'] = event['RequestId']
responseBody['LogicalResourceId'] = event['LogicalResourceId']
json_responseBody = json.dumps(responseBody,
indent=4,
sort_keys=True,
default=str)
print("Response body:\n" + json_responseBody)
headers = {
'content-type' : '',
'content-length' : str(len(json_responseBody))
}
try:
response = requests.put(responseUrl,
data=json_responseBody,
headers=headers)
print("Status code: " + response.reason)
except Exception as e:
print("send(..) failed executing requests.put(..): " + str(e))
dbPassword:
Type: AWS::SecretsManager::Secret
Properties:
GenerateSecretString:
ExcludePunctuation: True
AdminPassword:
Type: AWS::SecretsManager::Secret
Properties:
GenerateSecretString:
ExcludePunctuation: True
EcsSlr:
Type: AWS::IAM::ServiceLinkedRole
Properties:
AWSServiceName: ecs.amazonaws.com
Description: Role to enable Amazon ECS to manage your cluster.
Cluster:
Type: AWS::ECS::Cluster
DependsOn: EcsSlr
AnchoreTaskTaskRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service:
!Join
- ""
- - ecs-tasks.
- !Ref AWS::URLSuffix
Version: 2012-10-17
AnchoreTaskTaskRoleDefaultPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action:
- ecr:GetAuthorizationToken
- ecr:BatchCheckLayerAvailability
- ecr:GetDownloadUrlForLayer
- ecr:GetRepositoryPolicy
- ecr:DescribeRepositories
- ecr:ListImages
- ecr:DescribeImages
- ecr:BatchGetImage
- ecr:InitiateLayerUpload
- ecr:UploadLayerPart
- ecr:CompleteLayerUpload
- ecr:PutImage
Effect: Allow
Resource: "*"
Version: 2012-10-17
PolicyName: AnchoreTaskTaskRoleDefaultPolicy
Roles:
- !Ref AnchoreTaskTaskRole
TaskLoggingLogGroup:
Type: AWS::Logs::LogGroup
Properties:
# LogGroupName: !Join [ '', [ '/aws/ecs/task',!Ref ResourceName, '-anchore-engine' ] ]
RetentionInDays: 365
DeletionPolicy: Retain
AnchoreTaskExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service:
Fn::Join:
- ""
- - ecs-tasks.
- !Ref AWS::URLSuffix
Version: 2012-10-17
AnchoreTaskExecutionRoleDefaultPolicy:
Type: AWS::IAM::Policy
Properties:
PolicyDocument:
Statement:
- Action:
- ecr:BatchCheckLayerAvailability
- ecr:GetDownloadUrlForLayer
- ecr:BatchGetImage
Effect: Allow
Resource: "*"
- Action: ecr:GetAuthorizationToken
Effect: Allow
Resource: "*"
- Action:
- logs:CreateLogStream
- logs:PutLogEvents
Effect: Allow
Resource:
!GetAtt
- TaskLoggingLogGroup
- Arn
Version: 2012-10-17
PolicyName: AnchoreTaskExecutionRoleDefaultPolicy
Roles:
- !Ref AnchoreTaskExecutionRole
AnchoreTask:
Type: AWS::ECS::TaskDefinition
Properties:
ContainerDefinitions:
- Environment:
- Name: ANCHORE_DB_PASSWORD
Value:
!Join
- ""
- - "{{resolve:secretsmanager:"
- !Ref dbPassword
- ::::}}
- Name: ANCHORE_ADMIN_PASSWORD
Value:
!Join
- ""
- - "{{resolve:secretsmanager:"
- !Ref AdminPassword
- ::::}}
- Name: ANCHORE_DB_HOST
Value: 127.0.0.1
Essential: True
Image: !Sub
- ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${Repo}
- { Repo: !Ref AnchoreRepository}
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref TaskLoggingLogGroup
awslogs-stream-prefix: Anchore
awslogs-region:
Ref: AWS::Region
Name: AnchoreContainer
PortMappings:
- ContainerPort: 8228
Protocol: tcp
- Environment:
- Name: POSTGRES_PASSWORD
Value:
!Join
- ""
- - "{{resolve:secretsmanager:"
- !Ref dbPassword
- ::::}}
Essential: True
Image: postgres
LogConfiguration:
LogDriver: awslogs
Options:
awslogs-group: !Ref TaskLoggingLogGroup
awslogs-stream-prefix: AnchoreDb
awslogs-region:
Ref: AWS::Region
Name: postgres
PortMappings:
- ContainerPort: 5432
Protocol: tcp
Cpu: "1024"
ExecutionRoleArn:
!GetAtt
- AnchoreTaskExecutionRole
- Arn
Family: AnchoreFargateTask
Memory: "6144"
NetworkMode: awsvpc
RequiresCompatibilities:
- FARGATE
TaskRoleArn:
!GetAtt
- AnchoreTaskTaskRole
- Arn
DependsOn:
- CodeBuildStarter
LBSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Security Group for ELB
SecurityGroupEgress: []
SecurityGroupIngress:
- CidrIp: 0.0.0.0/0
Description: Allow from anyone on port 80
FromPort: 80
IpProtocol: tcp
ToPort: 80
VpcId: !ImportValue 'AnchoreVpcStack:VpcID'
LB:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
LoadBalancerAttributes: []
Scheme: internet-facing
SecurityGroups:
- !GetAtt
- LBSecurityGroup
- GroupId
Subnets:
!Split
- ","
- !ImportValue 'AnchoreVpcStack:PublicSubnets'
Type: application
AnchoreFargateServiceSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: AnchoreFargateService/SecurityGroup
SecurityGroupEgress:
- CidrIp: 0.0.0.0/0
Description: Allow all outbound traffic by default
IpProtocol: "-1"
SecurityGroupIngress: []
VpcId: !ImportValue 'AnchoreVpcStack:VpcID'
LBSecurityGrouptoAnchoreFargateServiceSecurityGroup:
Type: AWS::EC2::SecurityGroupEgress
Properties:
GroupId:
!GetAtt
- LBSecurityGroup
- GroupId
IpProtocol: tcp
Description: Load balancer to target
DestinationSecurityGroupId:
!GetAtt
- AnchoreFargateServiceSecurityGroup
- GroupId
FromPort: 8228
ToPort: 8228
LBPublicListenerECSGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 60
HealthCheckPath: /
HealthCheckPort: "8228"
HealthCheckTimeoutSeconds: 5
Matcher:
HttpCode: 200,404
Port: 80
Protocol: HTTP
TargetGroupAttributes: []
Targets: []
TargetType: ip
VpcId: !ImportValue 'AnchoreVpcStack:VpcID'
LBPublicListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- TargetGroupArn:
Ref: LBPublicListenerECSGroup
Type: forward
LoadBalancerArn: !Ref LB
Port: 80
Protocol: HTTP
Certificates: []
AnchoreFargateService:
Type: AWS::ECS::Service
Properties:
TaskDefinition: !Ref AnchoreTask
Cluster: !Ref Cluster
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 50
DesiredCount: 1
LaunchType: FARGATE
LoadBalancers:
- ContainerName: AnchoreContainer
ContainerPort: 8228
TargetGroupArn: !Ref LBPublicListenerECSGroup
NetworkConfiguration:
AwsvpcConfiguration:
AssignPublicIp: DISABLED
SecurityGroups:
- !GetAtt
- AnchoreFargateServiceSecurityGroup
- GroupId
Subnets:
!Split
- ","
- !ImportValue 'AnchoreVpcStack:PrivateSubnets'
DependsOn:
- LBPublicListener
AnchoreFargateServiceSecurityGroupfromAnchoreFargateCdkStackLBSecurityGroup:
Type: AWS::EC2::SecurityGroupIngress
Properties:
IpProtocol: tcp
Description: Load balancer to target
FromPort: 8228
GroupId:
!GetAtt
- AnchoreFargateServiceSecurityGroup
- GroupId
SourceSecurityGroupId:
!GetAtt
- LBSecurityGroup
- GroupId
ToPort: 8228
SendFindingsLambdaRole:
Type: AWS::IAM::Role
Properties:
RoleName: SendFindingsLambdaRole
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
-
PolicyName: SecurityHub
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- securityhub:BatchImportFindings
Resource: '*'
-
PolicyName: CloudWatchLogs
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: '*'
Boto3LambdaLayer:
Type: AWS::Lambda::LayerVersion
Properties:
LayerName: boto3-layer
Content:
S3Bucket: sa-security-specialist-workshops-us-east-2
S3Key: devsecops/layers/boto3.zip
CompatibleRuntimes:
- python3.7
LicenseInfo: Available under the MIT-0 license.
SendFindingsLambda:
Type: AWS::Lambda::Function
Properties:
Layers:
- !Ref Boto3LambdaLayer
FunctionName: !Join [ '-', [ !Ref ResourceName, 'sendfindings', 'securityhub' ] ]
Description: Sends payload with vulnerabilities findings to Security Hub
Handler: index.lambda_handler
Role: !GetAtt SendFindingsLambdaRole.Arn
Environment:
Variables:
ACCOUNT_ID: !Ref AWS::AccountId
REGION: !Ref AWS::Region
Code:
ZipFile: |
from __future__ import print_function
import boto3
import traceback
import os
import uuid
import datetime
from enum import Enum
from itertools import zip_longest
client = boto3.client('securityhub')
account_id = os.environ['ACCOUNT_ID']
region = os.environ['REGION']
uuid = str(uuid.uuid4())
def chunker(seq, size):
"""Chunk it up"""
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
class Severity(Enum):
NONE = 0
UNKNOWN = 0
LOW = 39
NEGLIGIBLE = 39
MEDIUM = 69
HIGH = 89
CRITICAL = 100
def lambda_handler(event, context):
"""Get the results of the scan and send them to Security Hub"""
if 'vulnerabilities' in event:
# product arn format arn:aws:securityhub:us-west-2:123456789012:product/123456789012/default
product_arn = "arn:aws:securityhub:{0}:{1}:product/{2}/default".format(
region,
account_id,
account_id
)
image_id = event['image_id']
image_arn = event['image_arn']
curr_time = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
for group in chunker(event['vulnerabilities'], 100):
findings = []
i = 0
for vuln in group:
finding = {
'SchemaVersion': '2018-10-08',
'Id': '{0}-{1}-{2}'.format(image_id,
vuln['vuln'],
str(i)),
'ProductArn': product_arn,
'ProductFields': {
'ProviderName': 'Anchore',
'ProviderVersion': 'v0.8.2',
},
'GeneratorId': uuid,
'AwsAccountId': account_id,
'Types': [
"Software and Configuration Checks/Vulnerabilities/CVE"
],
'CreatedAt': curr_time,
'UpdatedAt': curr_time,
'Severity': {
'Normalized': Severity[vuln['severity'].upper()].value
},
'Title': 'Vulnerability {0} found in {1}'.format(vuln['vuln'],
image_id),
'Description': 'Vulnerability {0} found in {1} for {2}'.format(vuln['vuln'],
vuln['package'],
image_id),
'SourceUrl': vuln['url'],
'Resources': [
{
'Type': 'Container',
'Id': image_arn,
'Details': {
'Container': {
'ImageId': image_id,
}
}
}
],
'Remediation': {
'Recommendation': {
'Text': 'Update {0} to version {1}'.format(vuln['package'],
vuln['fix'])
}
},
'UserDefinedFields': {
'feedGroup': vuln['feed_group'],
'package': vuln['package'],
'packageType': vuln['package_type'],
'severity': vuln['severity'],
}
}
findings.append(finding)
i += 1
# Report the chunk of findings
client.batch_import_findings(Findings=findings)
Runtime: python3.7
Timeout: 300
Outputs:
AnchoreLB:
Value:
!GetAtt
- LB
- DNSName
Export:
Name: AnchoreFargateStack:AnchoreLB
AnchoreAdminPasswordArn:
Value: !Ref AdminPassword
Export:
Name: AnchoreFargateStack:AnchoreAdminPasswordArn
SendFindingsLambda:
Value:
!GetAtt
- SendFindingsLambda
- Arn
Export:
Name: AnchoreFargateStack:SendFindingsToSecurityHub