Sub topic 13
Automating response with Lambda and Security Hub automation
This chapter builds on the EventBridge routing chapter. It assumes you can read a GuardDuty finding, write an EventBridge event pattern, and read basic Python. You should also know how IAM roles and Lambda execution roles work. By the end you will have a Lambda function that receives high-severity findings, a plan for what it should do, and a clear view of when to use Security Hub automation instead.
Why automate, and what to automate
A finding that waits for a person to read it can sit for hours. Automation shortens that gap. Automation can also do damage, because it acts on your account without anyone looking first. The design question is how much to let the code do on its own.
A useful way to decide is to split responses into three tiers:
| Tier | Example actions | Risk if the finding is a false positive |
|---|---|---|
| Notify | Send to SNS, Slack, or a ticket queue | None |
| Enrich and tag | Add a tag to the instance, attach finding details to a ticket | Low |
| Contain | Isolate an instance, disable an access key, block an IP | Can interrupt production |
Start at the notify tier. Move a finding type to containment only after you have watched it for a while and know its false positive rate. Many teams automate containment only for finding types with a clear meaning, such as credential exfiltration, and keep a human approval step for the rest.
The event that reaches your function
The EventBridge rule from the previous chapter matches GuardDuty findings with severity 7 or higher:
{
"source": ["aws.guardduty"],
"detail-type": ["GuardDuty Finding"],
"detail": {
"severity": [{ "numeric": [">=", 7] }]
}
}EventBridge delivers the whole event to the target. The finding is in the detail field. The fields you use most often are:
detail.type: the finding type, such asUnauthorizedAccess:EC2/SSHBruteForce.detail.severity: a number from 0.1 to 8.9.detail.resource.resourceType: the kind of resource affected, such asInstanceorAccessKey.detail.resource.instanceDetails.instanceId: present only when the resource is an EC2 instance.detail.service.action: what the actor did, with details that vary by action type.
The resource fields differ by resource type. A finding about an IAM access key has accessKeyDetails and no instanceDetails. Code that assumes instanceDetails always exists will fail on those findings, so read these fields defensively.
A minimal handler
This handler extracts the finding type, severity, and instance ID. It is the starting point for any remediation:
def handler(event, context):
detail = event["detail"]
finding_type = detail["type"]
severity = detail["severity"]
instance_id = (
detail.get("resource", {})
.get("instanceDetails", {})
.get("instanceId")
)
print(f"{finding_type} severity={severity} instance={instance_id}")
return {"type": finding_type, "severity": severity, "instanceId": instance_id}Note the chained .get() calls. If a finding has no instance, instance_id is None and the function logs the finding instead of raising an error. That is the right behavior for a function that receives many kinds of findings.
Adding a containment action
A common first containment step for a compromised EC2 instance is to swap its security groups for a group that allows no traffic. The instance keeps running, so you keep its memory and disk for forensics, but it can no longer talk to the network. The sketch below shows the idea with boto3. It does nothing unless the environment variable QUARANTINE_SG_ID is set, and it has a dry-run mode controlled by DRY_RUN.
import os
import boto3
ec2 = boto3.client("ec2")
QUARANTINE_SG_ID = os.environ.get("QUARANTINE_SG_ID")
DRY_RUN = os.environ.get("DRY_RUN", "true").lower() == "true"
def handler(event, context):
detail = event["detail"]
finding_type = detail["type"]
severity = detail["severity"]
instance_id = (
detail.get("resource", {})
.get("instanceDetails", {})
.get("instanceId")
)
print(f"{finding_type} severity={severity} instance={instance_id}")
if not instance_id or not QUARANTINE_SG_ID:
return {"action": "none", "instanceId": instance_id}
if DRY_RUN:
print(f"DRY_RUN: would isolate {instance_id}")
return {"action": "dry-run", "instanceId": instance_id}
ec2.modify_instance_attribute(
InstanceId=instance_id,
Groups=[QUARANTINE_SG_ID],
)
ec2.create_tags(
Resources=[instance_id],
Tags=[{"Key": "guardduty-isolated", "Value": finding_type}],
)
return {"action": "isolated", "instanceId": instance_id}The execution role needs ec2:ModifyInstanceAttribute and ec2:CreateTags. Scope it as tightly as you can, for example with a condition on a resource tag, so a bug cannot isolate every instance in the account.
Testing with sample findings
You do not need a real attack to test the pipeline. Generate sample findings and watch the function log them:
DETECTOR_ID=$(aws guardduty list-detectors --query 'DetectorIds[0]' --output text)
aws guardduty create-sample-findings --detector-id "$DETECTOR_ID" --finding-types Recon:EC2/PortProbeUnprotectedPort UnauthorizedAccess:EC2/SSHBruteForceSample findings are marked as samples in the finding data, and the instance IDs in them are not real instances. This has two consequences. First, a call such as modify_instance_attribute fails with an InvalidInstanceID error, so test containment logic against a test instance you create yourself. Second, you should check that your handler copes with that error and still logs the finding. Also check that the sample findings are severe enough to match your rule. Some sample finding types have severity below 7 and your rule will ignore them, so lower the threshold temporarily or use the test event feature of EventBridge.
Making the function safe to run more than once
EventBridge delivers events at least once, and GuardDuty publishes updated findings again as new activity is added to an existing finding. The same finding can therefore reach your function several times. Design for this:
- Make each action idempotent. Replacing security groups with the same group twice gives the same result.
- Use the finding
id(detail.id) as a key. Store it in a DynamoDB table with a conditional write if you need to guarantee that a step runs once. - Check the current state before you act. If the instance already carries the
guardduty-isolatedtag, skip it. - Configure a dead-letter queue or an on-failure destination for the Lambda function so failed events are kept for review instead of lost.
Security Hub automation
Security Hub offers a second way to automate. Instead of matching GuardDuty events directly, you act on findings after Security Hub has collected them. This is useful when you want one response path for findings from many sources, such as GuardDuty, Inspector, and Security Hub's own control checks.
There are two mechanisms:
- Custom actions. You define an action in Security Hub, such as "Isolate instance." An analyst selects findings in the console and chooses the action. Security Hub then sends an event to EventBridge with the selected findings, and your rule starts a target. This is a human-triggered response, which fits containment you do not want to run without approval.
- Automation rules. You define criteria and actions inside Security Hub. When new or updated findings match, Security Hub changes them, for example by raising severity, setting a workflow status, adding a note, or suppressing them. These rules change the finding record. They do not call Lambda or change your resources.
For automatic responses that change resources, you still use EventBridge. Security Hub sends its findings to EventBridge too, with a different source and detail type (aws.securityhub and Security Hub Findings - Imported). Because Security Hub findings use a normalized format, the fields in detail are laid out differently than in a native GuardDuty event. Your handler needs to read the normalized fields, such as detail.findings[0].Resources.
Choosing between the paths
| Need | Better fit |
|---|---|
| Fast response to one GuardDuty finding type | Direct EventBridge rule on `aws.guardduty` |
| One handler for findings from several services | EventBridge rule on Security Hub findings |
| Analyst approval before action | Security Hub custom action |
| Bulk changes to findings, such as setting severity for a test account | Security Hub automation rule |
| Findings from many accounts and Regions in one place | Security Hub aggregation, with the rule in the aggregation Region |
Remember that EventBridge rules are Regional. A rule in one Region sees only events from that Region unless you forward events to a central event bus.
Common errors
- The function is never invoked. Check that the rule is enabled and that the Lambda resource policy allows
events.amazonaws.comto invoke it. Creating the target in the console adds this permission, but the CLI and infrastructure templates do not do it for you. KeyErroroninstanceDetails. The finding is about another resource type. Use.get()as shown above.- Containment fails with access denied. The execution role lacks the EC2 permissions, or a service control policy blocks them.
- Loops. A function that edits a Security Hub finding can trigger the rule that started it. Filter on workflow status or on a marker you set.
- Suppressed findings still trigger actions. Suppression rules archive findings, but check that your event pattern does not match archived findings you meant to ignore.
Exercise
Your Lambda function isolates an EC2 instance when a GuardDuty finding arrives. The same finding is published twice, 15 minutes apart, because GuardDuty updated it. Name two design choices that keep the second event from causing trouble, and explain why you should not test containment using only sample findings.
Show answer
First, make the action idempotent, so setting the quarantine security group a second time has the same effect, and check state before acting, for example by skipping instances that already have the isolation tag. You can also record detail.id in DynamoDB with a conditional write. Sample findings contain instance IDs that do not exist, so the EC2 call fails with an invalid instance error and never proves that containment works. Test against a real test instance, with DRY_RUN off only in a test account.
Exercise
A team wants analysts to approve isolation before it happens, and wants it available for findings from GuardDuty and Inspector alike. Which Security Hub feature fits, and why is an automation rule not enough?
Show answer
A custom action fits. An analyst selects findings and chooses the action, Security Hub sends an event to EventBridge, and a rule starts the Lambda function. This keeps a human in the loop and works for any finding in Security Hub. An automation rule only changes finding fields such as severity or workflow status. It does not invoke Lambda or change resources.