forked from CruzCloud/amazon-guardduty-hands-on
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguardduty-cfn-template.yml
966 lines (896 loc) · 29.4 KB
/
guardduty-cfn-template.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
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
AWSTemplateFormatVersion: '2010-09-09'
Description: This CloudFormation Template can be used to quickly get started with AWS GuardDuty by configuring an environment to generate and remediate AWS GuardDuty findings.
Parameters:
ResourceName:
Type: String
Default: GuardDuty-Example
AllowedValues:
- GuardDuty-Example
Description: Prefix for the resources that are created.
AdminIP:
Type: String
AllowedPattern: '((\d{1,3})\.){3}\d{1,3}/\d{1,2}'
Description: 'Administrative IP Address (your IP) in CIDR notation (x.x.x.x/32). This is used to allow SSH access to the instances created in this scenario.'
KeyName:
Type: AWS::EC2::KeyPair::KeyName
ConstraintDescription: This must be the name of an existing EC2 KeyPair.
Description: 'Name of an existing EC2 KeyPair to enable SSH access to the instances created in this scenario.'
EmailAddress:
Description: Email address for receiving alerts.
Type: String
Metadata: {}
Mappings:
RegionMap:
us-east-1:
"64": "ami-afd15ed0"
us-east-2:
"64": "ami-2a0f324f"
us-west-1:
"64": "ami-00d8c660"
us-west-2:
"64": "ami-31394949"
ap-south-1:
"64": "ami-7d95b612"
ap-northeast-1:
"64": "ami-2724cf58"
ap-northeast-2:
"64": "ami-d117bebf"
ap-southeast-1:
"64": "ami-a7f0c4db"
ap-southeast-2:
"64": "ami-c267b0a0"
ca-central-1:
"64": "ami-c59818a1"
eu-central-1:
"64": "ami-43eec3a8"
eu-west-1:
"64": "ami-921423eb"
eu-west-2:
"64": "ami-924aa8f5"
eu-west-3:
"64": "ami-a88233d5"
sa-east-1:
"64": "ami-4fd48923"
Conditions: {}
Resources:
# GuardDuty Bucket
GDThreatListBucket:
Type: 'AWS::S3::Bucket'
Properties:
BucketName:
Fn::Join:
- '-'
- ['guardduty-example', !Ref "AWS::AccountId", !Ref "AWS::Region"]
# VPC & EC2 Creation
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.0.0.0/24
EnableDnsHostnames: true
EnableDnsSupport: true
Tags:
- Key: Name
Value: !Ref ResourceName
InternetGateway:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Ref ResourceName
GatewayAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId:
Ref: InternetGateway
VpcId: !Ref VPC
RouteTable:
DependsOn:
- VPC
Type: AWS::EC2::RouteTable
Properties:
Tags:
- Key: Name
Value: !Ref ResourceName
VpcId: !Ref VPC
PublicRoute:
Type: AWS::EC2::Route
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
RouteTableId: !Ref RouteTable
Subnet:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: 10.0.0.0/26
MapPublicIpOnLaunch: true
Tags:
- Key: Name
Value: !Ref ResourceName
VpcId: !Ref VPC
SubnetAssoc:
DependsOn:
- Subnet
- RouteTable
Type: AWS::EC2::SubnetRouteTableAssociation
Properties:
RouteTableId: !Ref RouteTable
SubnetId: !Ref Subnet
PublicNACL:
Type: AWS::EC2::NetworkAcl
Properties:
VpcId: !Ref VPC
Tags:
-
Key: Name
Value: !Ref ResourceName
-
Key: Network
Value: Public
InboundPublicNACLEntry:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref PublicNACL
RuleNumber: 100
Protocol: -1
RuleAction: allow
Egress: false
CidrBlock: '0.0.0.0/0'
PortRange:
From: 0
To: 65535
OutboundPublicNACLEntry:
Type: AWS::EC2::NetworkAclEntry
Properties:
NetworkAclId: !Ref PublicNACL
RuleNumber: 100
Protocol: -1
RuleAction: allow
Egress: true
CidrBlock: 0.0.0.0/0
PortRange:
From: 0
To: 65535
SubnetNACLAssociation:
Type: AWS::EC2::SubnetNetworkAclAssociation
Properties:
SubnetId: !Ref Subnet
NetworkAclId: !Ref PublicNACL
TargetSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Ref ResourceName
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '22'
ToPort: '22'
CidrIp: !Ref AdminIP
- IpProtocol: icmp
FromPort: '-1'
ToPort: '-1'
CidrIp: 0.0.0.0/0
ForensicSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription:
Fn::Join:
- '-'
- [!Ref ResourceName,'Forensics']
VpcId: !Ref VPC
SecurityGroupIngress:
- IpProtocol: icmp
FromPort: '-1'
ToPort: '-1'
CidrIp: 10.0.0.0/24
SecurityGroupEgress:
- IpProtocol: icmp
FromPort: '-1'
ToPort: '-1'
CidrIp: 10.0.0.0/24
# Malicious IAM User
CompromisedUser:
Type: "AWS::IAM::User"
Properties:
UserName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Compromised', 'Simulated']
CompromisedUserKey:
Type: "AWS::IAM::AccessKey"
Properties:
UserName: !Ref CompromisedUser
CompromisedUserPolicy:
Type: "AWS::IAM::Policy"
Properties:
PolicyName: "CompromisedUserPolicy"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: Allow
Action:
- ssm:GetParameter
- ssm:GetParameters
- ssm:DescribeParameters
Resource:
Fn::Join:
- ':'
- ["arn:aws:ssm", !Ref "AWS::Region", !Ref "AWS::AccountId", "*"]
Users:
- !Ref CompromisedUser
# Malicious Instance - For GuardDuty Finding: UnauthorizedAccess:EC2/MaliciousIPCaller.Custom
MaliciousIP:
DependsOn:
- GatewayAttachment
Type: AWS::EC2::EIP
Properties:
InstanceId: !Ref MaliciousInstance
Domain: vpc
MaliciousInstance:
DependsOn:
- GDThreatListBucket
Type: AWS::EC2::Instance
Properties:
InstanceType: t2.micro
ImageId:
Fn::FindInMap:
- RegionMap
- !Ref AWS::Region
- '64'
KeyName: !Ref KeyName
NetworkInterfaces:
- AssociatePublicIpAddress: 'false'
DeviceIndex: '0'
GroupSet:
- !Ref TargetSecurityGroup
SubnetId:
Ref: Subnet
Tags:
- Key: Name
Value:
Fn::Join:
- ': '
- [!Ref ResourceName, 'Malicious Instance', 'Scenario 1 & 2']
- Key: GD-Finding
Value: 'UnauthorizedAccess:EC2/MaliciousIPCaller.Custom'
UserData:
Fn::Base64: !Sub
- |
#!/bin/bash -ex
# Create Creds and Config files
mkdir /home/ec2-user/.aws
touch /home/ec2-user/.aws/credentials
touch /home/ec2-user/.aws/config
cat <<EOT >> /home/ec2-user/.aws/credentials
[default]
aws_access_key_id = ${AccessKey}
aws_secret_access_key = ${SecretKey}
EOT
# Modify Permissions and Ownership
chmod 746 /home/ec2-user/.aws/credentials
chown ec2-user /home/ec2-user/.aws/credentials
chmod 746 /home/ec2-user/.aws/config
chown ec2-user /home/ec2-user/.aws/config
cat <<EOT >> /home/ec2-user/gd-findings.sh
#!/bin/bash
aws configure set default.region ${Region}
aws iam get-user
aws iam create-user --user-name Sarah
aws dynamodb list-tables
aws s3api list-buckets
aws ssm describe-parameters
aws ssm get-parameters --names "gd_prod_dbpwd_sample"
EOT
chmod 744 /home/ec2-user/gd-findings.sh
chown ec2-user /home/ec2-user/gd-findings.sh
echo "* * * * * /home/ec2-user/gd-findings.sh > /home/ec2-user/gd-findings.log 2>&1" | tee -a /var/spool/cron/ec2-user
-
Region:
!Ref "AWS::Region"
AccessKey:
!Ref CompromisedUserKey
SecretKey:
Fn::GetAtt:
- "CompromisedUserKey"
- "SecretAccessKey"
# Compromised Instance - For GuardDuty Finding: UnauthorizedAccess:EC2/MaliciousIPCaller.Custom
CompromisedInstance:
Type: AWS::EC2::Instance
DependsOn: MaliciousIP
Properties:
InstanceType: t2.micro
ImageId:
Fn::FindInMap:
- RegionMap
- !Ref AWS::Region
- '64'
KeyName: !Ref KeyName
NetworkInterfaces:
- AssociatePublicIpAddress: 'true'
DeviceIndex: '0'
GroupSet:
- !Ref TargetSecurityGroup
SubnetId:
Ref: Subnet
Tags:
- Key: Name
Value:
Fn::Join:
- ': '
- [!Ref ResourceName, 'Compromised Instance', 'Scenario 1']
- Key: GD-Finding
Value: 'UnauthorizedAccess:EC2/MaliciousIPCaller.Custom'
UserData:
Fn::Base64: !Sub |
#!/bin/bash -ex
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo BEGIN
echo "* * * * * ping -c 6 -i 10 ${MaliciousIP}" | tee -a /var/spool/cron/ec2-user
# Compromised Instance IAM Role - For GuardDuty Finding: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration
CompromisedRole:
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'EC2', 'Compromised']
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
Path: /
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM
Policies:
-
PolicyName: GuardDutyCompromisedPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- ssm:PutParameter
- ssm:DescribeParameters
- ssm:GetParameters
- ssm:DeleteParameter
Resource:
Fn::Join:
- ':'
- ["arn:aws:ssm", !Ref "AWS::Region", !Ref "AWS::AccountId", "parameter/*"]
-
Effect: Allow
Action:
- ssm:DescribeParameters
Resource: "*"
-
Effect: Allow
Action:
- dynamodb:*
Resource:
Fn::GetAtt:
- "CustDynamoDBTable"
- "Arn"
-
Effect: Allow
Action:
- dynamodb:ListTables
- dynamodb:DescribeTable
Resource: '*'
-
Effect: Allow
Action:
- guardduty:GetDetector
- guardduty:ListDetectors
- guardduty:CreateThreatIntelSet
- guardduty:UpdateThreatIntelSet
Resource: '*'
-
Effect: Allow
Action: 's3:PutObject'
Resource: !Sub 'arn:aws:s3:::${GDThreatListBucket}/*'
-
Effect: Allow
Action:
- iam:PutRolePolicy
Resource:
Fn::Join:
- ':'
- ["arn:aws:iam:",!Ref "AWS::AccountId", "role/aws-service-role/guardduty.amazonaws.com/*"]
CompromisedInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
InstanceProfileName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Compromised','Profile']
Path: /
Roles:
- !Ref CompromisedRole
# IAM Credential Parameter Placeholders
DBPWDParameter:
Type: "AWS::SSM::Parameter"
Properties:
Name: "gd_prod_dbpwd_sample"
Type: "StringList"
Value: "NA"
Description: "Sample secret for generating GuardDuty findings."
# Compromised Instance - For GuardDuty Finding: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration
CompromisedInstance2:
Type: AWS::EC2::Instance
Properties:
InstanceType: t2.micro
IamInstanceProfile: !Ref CompromisedInstanceProfile
KeyName: !Ref KeyName
ImageId:
Fn::FindInMap:
- RegionMap
- !Ref "AWS::Region"
- '64'
NetworkInterfaces:
- AssociatePublicIpAddress: true
DeviceIndex: 0
GroupSet:
- !Ref TargetSecurityGroup
SubnetId:
Ref: Subnet
Tags:
- Key: Name
Value:
Fn::Join:
- ': '
- [!Ref ResourceName, 'Compromised Instance', 'Scenario 3']
- Key: GD-Finding
Value: 'UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration'
UserData:
Fn::Base64: !Sub
- |
#!/bin/bash
# Start SSM Agent
sudo systemctl start amazon-ssm-agent
# Set Variables
aws configure set default.region ${Region}
uuid=$(uuidgen)
list="gd-threat-list-example-$uuid.txt"
maliciousip=`curl http://169.254.169.254/latest/meta-data/public-ipv4`
# Create Threatlist
echo ${IP} >> $list
# Upload list to S3
aws s3 cp $list s3://${Bucket}/$list
sleep 5
# Create GuardDuty Threat List
id=`aws guardduty list-detectors --query 'DetectorIds[0]' --output text`
aws guardduty create-threat-intel-set --activate --detector-id $id --format TXT --location https://s3.amazonaws.com/${Bucket}/$list --name Example-Threat-List
# Set Parameters in SSM
aws ssm put-parameter --name 'gd_prod_dbpwd_sample' --type "SecureString" --value 'Password123' --overwrite
# Add Item to Customer DB
aws dynamodb put-item --table-name ${DB} --item '{ "name": { "S": "Joshua Tree" }, "state": {"S": "California"}, "website":{"S": "https://www.nps.gov/jotr/index.htm"} }'
-
Profile:
!Ref CompromisedInstanceProfile
Region:
!Ref "AWS::Region"
DB:
!Ref CustDynamoDBTable
Bucket:
!Ref GDThreatListBucket
IP:
!Ref MaliciousIP
# Mock Customer Database
CustDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
-
AttributeName: "name"
AttributeType: "S"
KeySchema:
-
AttributeName: "name"
KeyType: "HASH"
ProvisionedThroughput:
ReadCapacityUnits: "5"
WriteCapacityUnits: "5"
TableName: 'GuardDuty-Example-Customer-DB'
# Remediation Lambda Role - Instance Credential Exfiltration (ICE)
RemediationLambdaICERole:
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Lambda', 'InstanceCredentialExfiltration']
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: /
Policies:
-
PolicyName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'InstanceCredentialExfiltration']
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Action:
- ssm:DescribeParameters
Resource: '*'
-
Effect: Allow
Action:
- ssm:GetParameter
- ssm:GetParameters
Resource: '*'
-
Effect: Allow
Action:
- ec2:ReplaceIamInstanceProfileAssociation
Resource: '*'
-
Effect: Allow
Action:
- ec2:DescribeIamInstanceProfileAssociations
Resource: '*'
-
Effect: Allow
Action:
- iam:CreateInstanceProfile
Resource: '*'
-
Effect: Allow
Action:
- iam:AddRoleToInstanceProfile
- iam:RemoveRoleFromInstanceProfile
- iam:ListInstanceProfilesForRole
Resource: '*'
-
Effect: Allow
Action:
- iam:DeleteInstanceProfile
Resource:
Fn::GetAtt:
- "CompromisedInstanceProfile"
- "Arn"
-
Effect: Allow
Action:
- iam:PassRole
Resource:
Fn::GetAtt:
- "CompromisedRole"
- "Arn"
-
Effect: Allow
Action:
- iam:PutRolePolicy
Resource:
Fn::GetAtt:
- "CompromisedRole"
- "Arn"
-
Effect: Allow
Action:
- sns:Publish
Resource: !Ref GuardDutySNSTopic
-
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: '*'
# Remediation Lambda - Instance Credential Exfiltration (ICE)
RemediationLambdaICE:
Type: "AWS::Lambda::Function"
Properties:
FunctionName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Remediation', 'InstanceCredentialExfiltration']
Handler: "index.handler"
Environment:
Variables:
TOPIC_ARN: !Ref GuardDutySNSTopic
Role:
Fn::GetAtt:
- "RemediationLambdaICERole"
- "Arn"
Code:
ZipFile: |
from __future__ import print_function
from botocore.exceptions import ClientError
import json
import datetime
import boto3
import os
def handler(event, context):
# Log out event
print("log -- Event: %s " % json.dumps(event))
# Create generic function response
response = "Error auto-remediating the finding."
try:
# Set Clients
iam = boto3.client('iam')
ec2 = boto3.client('ec2')
# Set Role Variable
role = event['detail']['resource']['accessKeyDetails']['userName']
# Current Time
time = datetime.datetime.utcnow().isoformat()
# Set Revoke Policy
policy = """
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Deny",
"Action": "*",
"Resource": "*",
"Condition": {"DateLessThan": {"aws:TokenIssueTime": "%s"}}
}
}
""" % time
# Add policy to Role to Revoke all Current Sessions
iam.put_role_policy(
RoleName=role,
PolicyName='RevokeOldSessions',
PolicyDocument=policy.replace('\n', '').replace(' ', '')
)
# Send Response Email
response = "GuardDuty Remediation | ID:%s: GuardDuty discovered EC2 IAM credentials (Role: %s) being used outside of the EC2 service. All sessions have been revoked. Please follow up with any additional remediation actions." % (event['detail']['id'], role)
sns = boto3.client('sns')
sns.publish(
TopicArn=os.environ['TOPIC_ARN'],
Message=response
)
except ClientError as e:
print(e)
print("log -- Response: %s " % response)
return response
Runtime: "python2.7"
Timeout: "35"
RemediationLambdaICEInvokePermissions:
DependsOn:
- RemediationLambdaICE
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref "RemediationLambdaICE"
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
# Remediation Lambda Role - EC2/MaliciousIPCaller
RemediationLambdaEC2Role:
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Lambda', 'EC2MaliciousIPCaller']
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: '/'
Policies:
-
PolicyName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'EC2MaliciousIPCaller']
PolicyDocument:
Version: '2012-10-17'
Statement:
-
Effect: Allow
Action:
- ssm:PutParameter
- ec2:AuthorizeSecurityGroupEgress
- ec2:AuthorizeSecurityGroupIngress
- ec2:CreateSecurityGroup
- ec2:DescribeSecurityGroups
- ec2:RevokeSecurityGroupEgress
- ec2:RevokeSecurityGroupIngress
- ec2:UpdateSecurityGroupRuleDescriptionsEgress
- ec2:UpdateSecurityGroupRuleDescriptionsIngress
- ec2:DescribeInstances
- ec2:UpdateSecurityGroupRuleDescriptionsIngress
- ec2:DescribeVpcs
- ec2:ModifyInstanceAttribute
- lambda:InvokeFunction
- cloudwatch:PutMetricData
- xray:PutTraceSegments
- xray:PutTelemetryRecords
Resource: '*'
-
Effect: Allow
Action:
- logs:*
Resource: arn:aws:logs:*:*:*
-
Effect: Allow
Action:
- sns:Publish
Resource: !Ref GuardDutySNSTopic
# Remediation Lambda - EC2MaliciousIPCaller
RemediationLambdaEC2:
Type: "AWS::Lambda::Function"
Properties:
FunctionName:
Fn::Join:
- '-'
- [!Ref ResourceName, 'Remediation', 'EC2MaliciousIPCaller']
Handler: "index.handler"
Environment:
Variables:
TOPIC_ARN: !Ref GuardDutySNSTopic
FORENSICS_SG: !Ref ForensicSecurityGroup
INSTANCE_ID: !Ref CompromisedInstance
Role:
Fn::GetAtt:
- "RemediationLambdaEC2Role"
- "Arn"
Code:
ZipFile: |
from __future__ import print_function
from botocore.exceptions import ClientError
import boto3
import json
import os
def handler(event, context):
# Log out event
print("log -- Event: %s " % json.dumps(event))
# Create generic function response
response = "Error auto-remediating the finding."
try:
ec2 = boto3.client('ec2')
# Set Variables
vpc_id = event["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["vpcId"]
instanceID = event["detail"]["resource"]["instanceDetails"]["instanceId"]
security_group_id = os.environ['FORENSICS_SG']
if instanceID == os.environ['INSTANCE_ID']:
print("log -- Security Group Created %s in vpc %s." % (security_group_id, vpc_id))
# Isolate Instance
ec2 = boto3.resource('ec2')
instance = ec2.Instance(instanceID)
print("log -- %s, %s" % (instance.id, instance.instance_type))
instance.modify_attribute(Groups=[security_group_id])
# Send Response Email
response = "GuardDuty Remediation | ID:%s: GuardDuty discovered an EC2 instance (Instance ID: %s) that is communicating outbound with an IP Address on a threat list that you uploaded. All security groups have been removed and it has been isolated. Please follow up with any additional remediation actions." % (event['detail']['id'], event['detail']['resource']['instanceDetails']['instanceId'])
sns = boto3.client('sns')
sns.publish(
TopicArn=os.environ['TOPIC_ARN'],
Message=response
)
print("log -- Response: %s " % response)
else:
print("log -- Instance unrelated to GuardDuty-Hands-On environment.")
except ClientError as e:
print(e)
print("log -- Response: %s " % response)
return response
Runtime: "python2.7"
Timeout: "35"
RemediationLambdaEC2InvokePermissions:
DependsOn:
- RemediationLambdaEC2
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref "RemediationLambdaEC2"
Action: "lambda:InvokeFunction"
Principal: "events.amazonaws.com"
# Findings SNS Topic
GuardDutySNSTopic:
Type: AWS::SNS::Topic
Properties:
TopicName: !Ref ResourceName
Subscription:
- Endpoint: !Ref EmailAddress
Protocol: email
GuardDutySNSTopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
PolicyDocument:
Id: ID-GD-Topic-Policy
Version: '2012-10-17'
Statement:
- Sid: SID-GD-Example
Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sns:Publish
Resource: !Ref GuardDutySNSTopic
Topics:
- !Ref GuardDutySNSTopic
# GuardDuty CloudWatch Event - For GuardDuty Finding: UnauthorizedAccess:EC2/MaliciousIPCaller.Custom
GuardDutyEvent:
Type: AWS::Events::Rule
Properties:
Name: GuardDuty-Event-EC2-MaliciousIPCaller
Description: "GuardDuty Event: UnauthorizedAccess:EC2/MaliciousIPCaller.Custom"
EventPattern:
source:
- aws.guardduty
detail:
type:
- UnauthorizedAccess:EC2/MaliciousIPCaller.Custom
State: ENABLED
Targets:
-
Arn: !GetAtt RemediationLambdaEC2.Arn
Id: "GuardDutyEvent-Lambda-Trigger"
-
Arn: !Ref GuardDutySNSTopic
Id: "GuardDutySNSTopic-EC2-ThreatList"
InputTransformer:
InputTemplate: '"GuardDuty Finding | ID:<gdid>: The EC2 instance <instanceid> may be compromised and should be investigated. Go to https://console.aws.amazon.com/guardduty"'
InputPathsMap:
instanceid: $.detail.resource.instanceDetails.instanceId
gdid: "$.detail.id"
# GuardDuty CloudWatch Event - For GuardDuty Finding: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration
GuardDutyEventIAM:
Type: "AWS::Events::Rule"
Properties:
Name: GuardDuty-Event-IAMUser-InstanceCredentialExfiltration
Description: "GuardDuty Event: UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration"
EventPattern:
source:
- aws.guardduty
detail:
type:
- "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration"
State: "ENABLED"
Targets:
-
Arn: !GetAtt RemediationLambdaICE.Arn
Id: "GuardDutyEvent-Lambda-Trigger"
-
Arn:
Ref: "GuardDutySNSTopic"
Id: "GuardDutySNSTopic-EC2-IAM"
InputTransformer:
InputTemplate: '"GuardDuty Finding | ID:<gdid>: An EC2 instance IAM credentials (Role: <userName>) may be compromised and should be investigated. Go to https://console.aws.amazon.com/guardduty"'
InputPathsMap:
userName: "$.detail.resource.accessKeyDetails.userName"
gdid: "$.detail.id"
# GuardDuty CloudWatch Event - For GuardDuty Finding: UnauthorizedAccess:IAMUser/MaliciousIPCaller.Custom
GuardDutyEventIAM2:
Type: "AWS::Events::Rule"
Properties:
Name: GuardDuty-Event-IAMUser-MaliciousIPCaller
Description: "GuardDuty Event: UnauthorizedAccess:IAMUser/MaliciousIPCaller.Custom"
EventPattern:
source:
- aws.guardduty
detail:
type:
- "UnauthorizedAccess:IAMUser/MaliciousIPCaller.Custom"
State: "ENABLED"
Targets:
-
Arn:
Ref: "GuardDutySNSTopic"
Id: "GuardDutySNSTopic-IAM-ThreatList"
InputTransformer:
InputTemplate: '"GuardDuty Finding | ID:<gdid>: An AWS API operation was invoked (userName: <userName>) from an IP address that is included on your threat list and should be investigated. Go to https://console.aws.amazon.com/guardduty"'
InputPathsMap:
userName: "$.detail.resource.accessKeyDetails.userName"
gdid: "$.detail.id"
Outputs: {}