Docs / Use Cases / GuardDuty Finding Auto-Remediation
Diagram: GuardDuty finding to EventBridge to Lambda responder, quarantining an assumed-role session with a TokenIssueTime-gated Deny or an IAM user with a Deny-all plus key deactivation, logging an incident and publishing an SNS alert.

GuardDuty Finding Auto-Remediation

A GuardDuty finding → EventBridge → Lambda containment loop, a minimal Cloud Detection & Response (CDR) pipeline. GuardDuty flags a compromised identity (e.g. an EC2 instance role whose credentials were phished via SSRF → IMDS), and the responder Lambda quarantines it, deactivates any leaked access key, logs the incident (deduped by finding id), and publishes an SNS alert.

What the demo does. Provisions a GuardDuty detector, a "victim" IAM role standing in for a phished EC2 instance role, a DynamoDB incidents table, an SNS alerts topic, an EventBridge rule matching source: aws.guardduty, and the responder Lambda. The Lambda quarantines an assumed-role session with a aws:TokenIssueTime-gated Deny (only sessions already issued are cut off), or an IAM user with an unconditional Deny-all plus access-key deactivation. Every finding is deduped by id before any action is taken. scripts/attack.sh plays both sides live: assumes the victim role, shows the stolen session working, injects a schema-accurate finding straight onto EventBridge, then shows the same stolen session denied while a freshly-minted session still works. Requires IAM_ENFORCEMENT=1. Source: 22-guardduty-autoremediation/ in the examples repo.
🎯

Surgical containment

The aws:TokenIssueTime-gated Deny cuts off only sessions already in the attacker's hands — a session minted after containment is unaffected, no blanket lockout.

🔒

Two identity types, two techniques

An assumed role gets the issue-time-gated Deny; an IAM user (no session to gate on) gets an unconditional Deny-all plus its leaked access key deactivated.

🔁

Dedup before action

The responder claims the finding id with a conditional DynamoDB write before taking any action, so a replayed or retried EventBridge delivery is a clean no-op.

Step-by-Step Walkthrough

Step 1: Start LocalEmu with IAM enforcement enabled

Terminal
$ IAM_ENFORCEMENT=1 localemu start

# The quarantine policy's whole point is to be enforced.

The quarantine policy only matters if LocalEmu actually evaluates it against every subsequent API call.

Step 2: Deploy the stack with Terraform

./scripts/deploy.sh local
$ ./scripts/deploy.sh local
$ cd terraform && terraform init -upgrade -input=false
$ terraform apply -auto-approve -input=false -var "target=local"

→ deployed to local. outputs:
alerts_topic_arn = "arn:aws:sns:us-east-1:000000000000:le-gd-alerts"
detector_id      = "<guardduty-detector-id>"
function_name    = "le-gd-responder"
incidents_table  = "le-gd-incidents"
rule_name        = "le-gd-on-guardduty-finding"
victim_role_arn  = "arn:aws:iam::000000000000:role/le-gd-victim-role"
victim_role_name = "le-gd-victim-role"

Provisions the GuardDuty detector, the victim role (standing in for a phished EC2 instance role), the DynamoDB incidents table, the SNS alerts topic, the responder Lambda, and the EventBridge rule wiring them together.

Step 3: Red team — the attacker already has a stolen session

scripts/attack.sh
# scripts/attack.sh, RED TEAM: attacker already phished this EC2
# instance role's creds (e.g. via an SSRF -> IMDS chain).
$ CREDS=$(aws sts assume-role --role-arn "$ROLE_ARN" --role-session-name hacker-session)

# attacker recon with the stolen session:
$ AWS_ACCESS_KEY_ID=$AK AWS_SECRET_ACCESS_KEY=$SK AWS_SESSION_TOKEN=$ST aws sts get-caller-identity
$ AWS_ACCESS_KEY_ID=$AK AWS_SECRET_ACCESS_KEY=$SK AWS_SESSION_TOKEN=$ST aws s3 ls

A real sts:AssumeRole mints a session for the victim role, standing in for credentials phished off an EC2 instance's IMDS. The attacker's recon calls succeed, because nothing has detected them yet.

Step 4: Detection — a schema-accurate finding hits EventBridge

scripts/attack.sh
# DETECTION: a schema-accurate finding, shaped exactly like what
# GuardDuty's real detection would emit, published straight to EventBridge.
$ aws events put-events --entries '[{
  "Source": "aws.guardduty",
  "DetailType": "GuardDuty Finding",
  "Detail": "{\"id\":\"<finding-id>\",\"type\":\"UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS\",\"severity\":8.5,\"resource\":{\"accessKeyDetails\":{\"userType\":\"AssumedRole\",\"userName\":\"le-gd-victim-role\"}}}"
}]'

GuardDuty's own CreateSampleFindings always names a generic placeholder identity, on LocalEmu and on real AWS alike — it can't demonstrate containing an identity that doesn't exist in your account. So the live demo publishes a finding shaped exactly like a real detection, naming the real victim role, straight onto the same EventBridge bus GuardDuty itself would use.

Step 5: Blue team — the stolen session is denied, a fresh one isn't

scripts/attack.sh
# BLUE TEAM: the stolen session should be denied now, but only that
# session. (sts:GetCallerIdentity is exempt from IAM evaluation by
# design, so it still succeeds -- s3 ls is the real check.)
$ AWS_ACCESS_KEY_ID=$AK AWS_SECRET_ACCESS_KEY=$SK AWS_SESSION_TOKEN=$ST aws sts get-caller-identity
$ AWS_ACCESS_KEY_ID=$AK AWS_SECRET_ACCESS_KEY=$SK AWS_SESSION_TOKEN=$ST aws s3 ls
(non-zero / AccessDenied here means containment worked)

# -> proving the surgical scope: a session minted AFTER containment works fine
$ FRESH_CREDS=$(aws sts assume-role --role-arn "$ROLE_ARN" --role-session-name legit-after-fix)
$ AWS_ACCESS_KEY_ID=$FAK AWS_SECRET_ACCESS_KEY=$FSK AWS_SESSION_TOKEN=$FST aws s3 ls
(a 200/empty-list here, not AccessDenied, is the point)

The responder Lambda already fired by now: the role's quarantine policy denies every action for sessions issued before containment. The same attacker, re-authenticating from scratch after the fix, gets a session that works fine — the role itself was never locked out, only the compromised session was.

What the run proves

Seven integration tests: six direct Lambda invokes plus one true end-to-end test that injects the finding via EventBridge and watches the whole pipeline react on its own.

Test Scenario Proves
test_assumed_role_is_quarantinedAssumedRole findingTokenIssueTime-gated Deny attached; incident row written
test_iam_user_is_quarantined_and_key_deactivatedIAMUser findingDeny-all attached + leaked access key set Inactive
test_duplicate_finding_is_dedupedsame finding id invoked twicesecond call is a no-op (already_processed)
test_non_actionable_finding_type_is_ignoredfinding type outside ACTIONABLE_TYPESignored, not silently swallowed
test_missing_principal_name_is_ignoredno principal name in the findingignored, no crash
test_missing_finding_id_is_ignoredno finding idignored, no crash
test_end_to_end_via_eventbridgefinding published straight to EventBridgerule → Lambda → IAM quarantine + key deactivation + DDB row + SNS alert, all fire on their own

Design note: two quarantine techniques, one function

AssumedRole: AWS's own surgical IR technique — a Deny with Condition: {"DateLessThan": {"aws:TokenIssueTime": "<now>"}}. Only sessions already issued are cut off; a session minted after remediation is unaffected, so the role doesn't need to stay locked out of legitimate use during the investigation.

IAMUser: there's no session or token to gate on issue time (no AssumeRole involved), so an unconditional inline Deny-all is the direct equivalent of pulling the user's access immediately — paired with deactivating the leaked access key itself.

This workshop's own testing surfaced two real LocalEmu gaps along the way — GuardDuty's finding APIs were unimplemented, and aws:TokenIssueTime wasn't populated as an IAM condition key — both fixed upstream rather than worked around here.

Full source: src/responder.py

The GuardDuty finding responder, triggered by the EventBridge rule. Dedup, two quarantine techniques, access-key deactivation, and the SNS alert, in one ~190-line Lambda.

"""GuardDuty finding responder Lambda — a minimal Cloud Detection & Response (CDR) loop.

Triggered by an EventBridge rule matching `source: aws.guardduty`. Looks at
the compromised identity named in the finding, quarantines it, deactivates
any leaked access key, logs an incident (deduped on the finding id), and
publishes an SNS alert.

Quarantine technique: a `TokenIssueTime`-gated Deny for assumed-role
sessions (AWS's own surgical IR pattern — only already-issued sessions
are cut off), or an unconditional Deny-all for IAM users (no session to
gate on). See `_quarantine_role`'s docstring.
"""
from __future__ import annotations

import json
import logging
import os
import time
from decimal import Decimal

import boto3
from botocore.exceptions import ClientError

LOG = logging.getLogger()
LOG.setLevel(logging.INFO)

INCIDENTS_TABLE = os.environ["INCIDENTS_TABLE"]
ALERTS_TOPIC_ARN = os.environ["ALERTS_TOPIC_ARN"]

# Finding types this responder knows how to act on. Anything else is logged
# as a no-op rather than silently ignored, same spirit as 06-s3-guardrail's
# "rule-pattern shape" case.
ACTIONABLE_TYPES = {
    "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS",
    "UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS",
    "Recon:IAMUser/MaliciousIPCaller",
    "UnauthorizedAccess:IAMUser/UnusualASNCaller",
}

_iam = boto3.client("iam")
_ddb = boto3.resource("dynamodb")
_sns = boto3.client("sns")
_incidents = _ddb.Table(INCIDENTS_TABLE)

QUARANTINE_POLICY_NAME = "le-gd-quarantine"


def handle(event, _ctx):
    detail = event.get("detail") or {}
    finding_id = detail.get("id") or ""
    finding_type = detail.get("type") or ""
    severity = detail.get("severity")

    if not finding_id:
        return {"contained": False, "reason": "no_finding_id"}

    if finding_type not in ACTIONABLE_TYPES:
        return {"contained": False, "reason": "finding_type_not_actionable", "finding_id": finding_id, "type": finding_type}

    access_key_details = (detail.get("resource") or {}).get("accessKeyDetails") or {}
    principal_name = access_key_details.get("userName")
    user_type = access_key_details.get("userType")  # "AssumedRole" | "IAMUser"
    access_key_id = access_key_details.get("accessKeyId")

    if not principal_name:
        return {"contained": False, "reason": "no_principal_name", "finding_id": finding_id}

    # Dedup first: claim the finding id before taking any action, so a
    # replayed event (or a retried EventBridge delivery) is a no-op.
    if not _claim_finding(finding_id, principal=principal_name, finding_type=finding_type, severity=severity):
        return {"contained": False, "reason": "already_processed", "finding_id": finding_id}

    actions_taken = []
    now = int(time.time())

    if user_type == "AssumedRole":
        try:
            _quarantine_role(principal_name, as_of_epoch=now)
            actions_taken.append(f"quarantined_role:{principal_name}")
        except ClientError as e:
            actions_taken.append(f"quarantine_failed:{e.response['Error']['Code']}")
    elif user_type == "IAMUser":
        try:
            _quarantine_role(principal_name, as_of_epoch=now, is_user=True)
            actions_taken.append(f"quarantined_user:{principal_name}")
        except ClientError as e:
            actions_taken.append(f"quarantine_failed:{e.response['Error']['Code']}")
        if access_key_id:
            try:
                _iam.update_access_key(UserName=principal_name, AccessKeyId=access_key_id, Status="Inactive")
                actions_taken.append(f"deactivated_key:{access_key_id}")
            except ClientError as e:
                actions_taken.append(f"deactivate_key_failed:{e.response['Error']['Code']}")

    _publish_alert(
        finding_id=finding_id,
        finding_type=finding_type,
        severity=severity,
        principal=principal_name,
        actions_taken=actions_taken,
    )

    return {
        "contained": True,
        "finding_id": finding_id,
        "principal": principal_name,
        "actions_taken": actions_taken,
    }


def _claim_finding(finding_id: str, *, principal: str, finding_type: str, severity) -> bool:
    try:
        _incidents.put_item(
            Item={
                "finding_id": finding_id,
                "principal": principal,
                "finding_type": finding_type,
                "severity": Decimal(str(severity)) if severity is not None else None,
                "processed_at": int(time.time()),
            },
            ConditionExpression="attribute_not_exists(finding_id)",
        )
        return True
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return False
        raise


def _quarantine_role(name: str, *, as_of_epoch: int, is_user: bool = False) -> None:
    """Quarantine the compromised identity, pending investigation.

    AssumedRole: the surgical AWS IR technique — Deny every action for any
    session token issued before containment, via
    `Condition: {"DateLessThan": {"aws:TokenIssueTime": "<now>"}}`. Only
    sessions already in the attacker's hands are cut off; a session minted
    *after* remediation (e.g. once the role's trust/perms are fixed) is
    unaffected, so the role doesn't need to stay locked out of legitimate
    use while the incident is being investigated. (LocalEmu didn't
    populate `aws:TokenIssueTime` as a condition key until this workshop's
    accompanying upstream fix — see the README.)

    IAMUser: there's no session/token to gate on issue time (no AssumeRole
    involved), so an unconditional inline Deny-all is the direct
    equivalent of pulling the user's access immediately.
    """
    if is_user:
        policy = {
            "Version": "2012-10-17",
            "Statement": [{
                "Sid": "DenyAllPendingInvestigation",
                "Effect": "Deny", "Action": "*", "Resource": "*",
            }],
        }
        _iam.put_user_policy(UserName=name, PolicyName=QUARANTINE_POLICY_NAME, PolicyDocument=json.dumps(policy))
        return

    as_of = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(as_of_epoch))
    policy = {
        "Version": "2012-10-17",
        "Statement": [{
            "Sid": "DenySessionsIssuedBeforeContainment",
            "Effect": "Deny", "Action": "*", "Resource": "*",
            "Condition": {"DateLessThan": {"aws:TokenIssueTime": as_of}},
        }],
    }
    _iam.put_role_policy(RoleName=name, PolicyName=QUARANTINE_POLICY_NAME, PolicyDocument=json.dumps(policy))


def _publish_alert(*, finding_id: str, finding_type: str, severity, principal: str, actions_taken: list[str]) -> None:
    _sns.publish(
        TopicArn=ALERTS_TOPIC_ARN,
        Subject=f"[GuardDuty] {finding_type}",
        Message=json.dumps(
            {
                "finding_id": finding_id,
                "finding_type": finding_type,
                "severity": severity,
                "principal": principal,
                "actions_taken": actions_taken,
            }
        ),
    )

Files

Repository layout.

22-guardduty-autoremediation/
├── README.md
├── src/
│   └── responder.py           (~190 lines)
├── terraform/                 (11 resources)
├── tests/
│   └── test_guardduty_response.py  (7 tests)
└── scripts/
    ├── deploy.sh
    ├── test.sh
    ├── teardown.sh
    └── attack.sh              (live red-team / blue-team demo)