4. Automate responses for GuardDuty

What will we build

In this section we will build a blacklist of IPs that we want to mitigate against. This could be a list that is automatically updated based on known threats, In this scenario we will build a manual list and will build automation to quarantine any ec2 instance that tries to communicate with those IPs

Configure GuardDuty and custom threat list

In the AWS Management Console, under Services, select GuardDuty

  • From left panel select Lists
  • In Threat List section select Add a threat list
  • Provide List name as GD-Custom-Threat-List
  • Provide Location as https://summit-threat-detection-artifacts.s3-us-west-2.amazonaws.com/ts-sec-wk.txt
  • Select Format as Plaintext
  • Select I Agree and Add list
  • You should recieve a message that Successfully created the list
  • Now activate threat list by selecting Activate checkbox for our threat list
  • Refresh the page and verify that threat list is activated

Create a security group with inbound rules only for HTTP and HTTPS

Open the Amazon VPC console

  • In the navigation pane, choose Security Groups
  • Select Create Security group
  • Provide Group Name and Description as QuarantineSG
  • Ensure that you select the VPC labelled smdemo-vpc
  • On the Inbound Rules and Outbound Rules DELETE all the traffic rules
  • Select Create Make note of ID of security group we have created. This is required for the Lambda code

Create IAM policy for lambda function remediate security group

Open the IAM console

  • Select Policy from left panel of IAM console and then select Create Policy
  • Select JSON. Delete default JSON policy and use the below text
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeInstances",
                "ec2:DescribeVpcs",
                "ec2:ModifyInstanceAttribute",
                "lambda:InvokeFunction",
                "cloudwatch:PutMetricData",
                "xray:PutTraceSegments",
                "xray:PutTelemetryRecords"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "logs:*"
            ],
            "Resource": "arn:aws:logs:*:*:*",
            "Effect": "Allow"
        }
    ]
}
  • Click Review Policy
  • Provide Policy name as GDEC2MaliciousIPCallerLambdaPolicy
  • Click Create Policy

Create IAM role for your Lambda function

On AWS IAM console, select Role from left panel

  • Select Create Role
  • Select Lambda from the list of services that will use this role and then select Next: Permission
  • In search box provide the policy name we created previously - GDEC2MaliciousIPCallerLambdaPolicy
  • Select the check box next to the policy you created previously and then select Next: Tags then Next: Review
  • Name your role GDEC2MaliciousIPCallerLambdaRole and provide description
  • Select Create role

Create the Lambda function

In the AWS Management Console, under Services, select Lambda to go to the Lambda Console

  • From the Dashboard, select Create function button in the upper-right
  • On the Create function page: Choose Author from scratch
  • Provide a name for the function. We’re using GDEC2MaliciousIPCallerResponder
  • In the Runtime dropdown list, select Python 2.7 as our lambda function in in python
  • Under Role, select use an existing role. Select GDEC2MaliciousIPCallerLambdaRole and then select Create function
  • On function Configuration page, scroll down to Basic settings
    • Change Timeout value to 1 Min
    • Change the Memory to 1024 MB
  • Scroll up to the Designer section and select the name of your Lambda function and use this code:
from __future__ import print_function
from botocore.exceptions import ClientError
import boto3
import json
import os

def lambda_handler(event, context):

  # Log out event
  print("log -- Event: %s " % json.dumps(event))

  ec2 = boto3.client('ec2')

  # Set Variables
#  vpc_id = event["detail"]["resource"]["instanceDetails"]["networkInterfaces"][0]["vpcId"]
  instanceID = event["detail"]["resource"]["instanceDetails"]["instanceId"]
#  instanceID = event["resource"]["instanceDetails"]["instanceId"]


  # Replace below value with Quarantine SG ID in your account
  security_group_id = "sg-0bb91436b38887c3f"
     
  # Isolate Instance
  ec2 = boto3.resource('ec2')
  instance = ec2.Instance(instanceID)
  print("Starting Remediation for Instance -- %s, %s" % (instance.id, instance.instance_type))
  instance.modify_attribute(Groups=[security_group_id])
  print("Quarantine Instance -- %s, %s" % (instance.id, instance.instance_type))
  • Note: Please ensure that you change value of security_group_id to match the SG ID you have created in step-1
  • Click on Save

Create and Configure a CloudWatch Rule to detect event and trigger remediation

In the AWS Management Console, under Services, select CloudWatch

  • On the left-hand side, under Events, select Rules
  • Click Create rule
    • Under Event Source, select the dropdown list and select Custom event pattern
    • Copy the following pattern and paste it into the text box
    {
       "source": [
          "aws.guardduty"
       ],
       "detail": {
          "type": [
             "UnauthorizedAccess:EC2/MaliciousIPCaller.Custom"
          ]
       }
    }
    
  • Add trigger for remediation by selecting Add Target
    • Select Lambda Function from drop down
    • For Function select name of the lambda function you created earlier GDEC2MaliciousIPCallerResponder
    • Give your rule a name and description GDEC2MaliciousIPCallerRemediation
    • Select Create rule
    • Verify that rule has been created

Verify it works

On AWS Systems Manager console

  • Navigate to Session Manager
  • click on start session
  • select the smdemo-host instance
  • Click on Start session
  • In the session run these 2 commands
    ping -c 5 54.167.214.0
    ping -c 5 171.51.238.116
    

GuardDuty will detect this and log this event as finding type UnauthorizedAccess:EC2/MaliciousIPCaller.Custom This will be detected by CloudWatch and it will execute the lambda function to quarantine the instance by changing the security group

After 10 minutes you will see that your EC2 instance on which you have simulated connection to threat IP has been isolated by changing security group “QuarantineSG”