Charitha Reddysecurity engineering
← All writing

Quarantining a compromised EC2 instance in seconds with GuardDuty and Lambda

When GuardDuty raises a high-severity finding at 3 a.m., the first minutes matter most. This responder takes the first containment steps automatically: it isolates the instance, snapshots its disks for forensics, disables a leaked access key, and emails the team what it did.

The flow

GuardDuty finding
  -> EventBridge rule (severity >= 7)
    -> Lambda responder
         EC2 instance  -> quarantine security group + tags + EBS snapshots
         IAM user key  -> deactivate the access key
         anything else -> notify only
    -> SNS email to the security team
    -> failed deliveries -> SQS dead-letter queue

Everything is Terraform. GuardDuty severities of 7 to 8.9 are High and 9 to 10 Critical, so the default threshold of 7 means only High and Critical findings trigger automatic action; lower ones stay with humans.

Isolating an instance

The responder moves the instance into a quarantine security group with no inbound and no outbound rules, then tags it and starts snapshots of every attached EBS volume for forensics. Two gotchas showed up while building it.

New security groups allow all outbound traffic by default. Creating an empty group isn't enough: you have to revoke its default egress rule, or the "quarantined" instance can still reach the internet.

# New security groups allow all outbound traffic by default.
# Remove every egress rule (IPv4 and IPv6) so nothing can leave.
egress = group.get("IpPermissionsEgress", [])
if egress:
    ec2.revoke_security_group_egress(GroupId=sg_id, IpPermissions=egress)

Snapshot before anything destructive. The responder never stops or terminates the instance. The disks are evidence, and a snapshot preserves them for investigation.

Two safety valves keep automation from causing an outage: instances tagged AutoResponseExempt=true are skipped by policy (some systems need a human decision), and an instance that's already isolated isn't processed twice.

Disabling a leaked key

For credential findings, the responder deactivates the IAM user's access key. Deactivated, not deleted, so it can be restored if the finding turns out to be benign. Keys are masked in the notification email, so the alert doesn't spread the secret further.

The catch is temporary credentials. Keys starting with ASIA belong to roles and sessions and can't simply be switched off. The responder recognises them, takes no automatic action, and tells a human to revoke the role's active sessions. Doing nothing loudly is better than doing the wrong thing quietly.

Shipping it safely

Limitations

Code, tests and full resultsaws-threat-containment on GitHub ↗

More writing