// Why this matters
The fastest way to learn that an IAM access key has leaked is rarely a polite alert. It is a burst of AccessDenied errors as someone with a stolen key probes what it can do. Auto-remediating compromised IAM credentials with CloudTrail turns that burst into a trigger: within seconds of the first denied calls the identity is neutralised and a human is told.
Manual response does not scale to nights and weekends. A leaked key found in a public repository will be used by automated scanners in minutes, and the damage (crypto-mining instances, data exfiltration, new backdoor users) happens before anyone reads the email.
This is a small, serverless pattern, one template and one function, and it makes a good first step before investing in a full detection platform. It also teaches the CloudWatch Logs subscription mechanism that many other security automations use. For the heavier identity-side equivalent see Watching the Watchers: Identity-Tampering Detection with ChatOps Triage.
// The problem
Reconnaissance with stolen credentials has a recognisable shape: many API calls across services the real owner never touches, most of them denied. Each denial is recorded in CloudTrail with an errorCode of AccessDenied or UnauthorizedOperation. Alone, one denial is noise; a burst from one principal is a signal.
The difficulty is acting on it safely. Aggressive containment risks locking out a legitimate engineer or breaking a production integration that happens to hold the key; timid containment leaves the attacker free to find the one service the key can use. And the automation itself is a privileged component: a Lambda that can edit IAM is a juicy target and a potential outage-maker if it misfires.
So the requirements were: react in seconds, tell humans immediately, contain with the least destructive action that actually stops the abuse, never act on the wrong principal, and leave an audit trail.
// The solution
CloudTrail delivers management events to S3 for the durable record and to a CloudWatch Logs group for near-real-time processing. A subscription filter on that log group matches only events whose errorCode ends in UnauthorizedOperation or starts with AccessDenied, and invokes a Lambda with the matching batch. Lambda receives the batch as a base64 encoded, gzip compressed payload.
The function decodes each event, extracts the identity, and branches. For an IAM user it notifies via SNS first (the human is informed even if remediation later errors), then disables the access key used in the event and removes the console login profile. For an assumed role or federated identity it only notifies, because deleting a role session is not something IAM lets you do and the right control there is a session-revocation policy.
The original design deleted the access key. We recommend the safer variant shown in this article: set the key to Inactive and attach an inline deny-all policy to the user. Both are instantly effective and fully reversible by the owner after investigation; deletion destroys the evidence of which key was used and cannot be undone. Add a threshold (N denials from one principal in a window) before acting if your estate has noisy legitimate failures.
Finally, the function role is scoped. It needs only to read the user, list and update access keys, put a user policy, delete a login profile and publish to one topic. The sample template that this pattern grew from used broad wildcard permissions to get going, and tightening them was the first follow-up.
- CloudTrailtrail logging to S3 and CloudWatch Logs
- Log filterpattern on AccessDenied and UnauthorizedOperation
- Lambda triggersubscription event on the function
- Decodebase64 and gzip decode, parse the identity
- NotifySNS email naming the suspected principal
- Revoke keys gatedelete the access key used in the event
- Revoke consoledelete the login profile
- Observabilitylog retention and Contributor Insights rule
- Decodebase64 then gunzip the batch
- Parseread userIdentity from each log event
- ClassifyIAM user, role session or root
- Allow-list gateskip break-glass and service identities
- NotifySNS message first
- Containdeactivate key, attach deny-all
- Recordstructured log line for audit
// Before you start
- AWS CLI and AWS SAM CLI installed; permission to create trails, log groups, IAM roles, Lambda functions and SNS topics.
- An email address for SNS subscription; you must click the confirmation link.
- A non-production IAM user with a throwaway access key for testing. Never test with a real engineer account.
- Python 3.9+ locally to unit test the handler.
- An understanding that this triggers on a single account; an organisation trail needs a central log group and cross-account design.
// Step-by-step implementation
01 Create the trail and log delivery
The trail needs three things: an S3 bucket with the CloudTrail bucket policy, a log group, and a role CloudTrail can assume to write to that group. The bucket policy is the usual stumbling block: CloudTrail checks the ACL and writes under an account-prefixed path, and the trail creation fails if either statement is missing.
02 Create the alert topic and a least-privilege function role
Subscribe a human before anything else. The function role is scoped to exactly the IAM actions it uses. IAM resource-level scoping for users works by ARN pattern, so you can even restrict it to a naming convention or a path and keep break-glass users structurally out of reach.
03 Write the handler: decode, classify, notify
Log subscriptions deliver a base64 string that decodes to gzip that decodes to JSON with a logEvents list; each logEvent message is itself a JSON CloudTrail record. Skip anything that is not an IAM user (role sessions have an ARN containing assumed-role), and de-duplicate principals within the batch so a hundred denied calls produce one alert and one containment.
04 Contain reversibly: deactivate, deny, remove console access
Deactivating the key stops it working immediately but keeps it for forensics. The deny-all inline policy catches any other credentials the user holds (a second key, an existing console session). Deleting the login profile removes password sign-in. Each call is wrapped so one failure (for example the user never had a console password) does not prevent the rest.
05 Attach the subscription filter and add log retention
The filter pattern uses CloudWatch Logs JSON syntax. The first term matches errors ending in UnauthorizedOperation (EC2 style), the second matches errors starting with AccessDenied (S3, IAM style). Add the Lambda permission for the logs service, then give the function its own log group with retention so its output does not live forever.
06 Add Contributor Insights to tune the trigger
A Contributor Insights rule on the trail log group groups events by principal and event name and shows the top contributors. After a week you will know which legitimate identities generate denials (misconfigured jobs, health checkers) and can add exemptions or a minimum-count threshold rather than guessing.
07 Build, deploy and test with a throwaway user
Deploy with SAM, confirm the SNS subscription from your inbox, then create a disposable user with a key and no permissions. Calling any API with it generates AccessDenied events. Watch the alert arrive, then confirm the key is Inactive and the policy is attached. Delete the test user afterwards.
// How to verify it works
- After the throwaway user triggers denials, an email arrives within a few minutes naming the user and the first denied call.
aws iam list-access-keys --user-name zz-compromise-testshows the key with Status Inactive.aws iam list-user-policies --user-name zz-compromise-testlists the quarantine policy.- Tag another test user
containment=exempt, generate denials, and confirm the function logs a keys-error AccessDenied for that user and leaves its credentials untouched. - The Contributor Insights rule shows the throwaway principal at the top of the contributor list.
// Design decisions and trade-offs
- Fully event-driven and serverless.
- Containment first, humans notified immediately after.
- A production version should scope the function role and the trigger threshold; both are called out as follow-ups.
// Pitfalls and lessons learned
- Broad wildcard IAM permissions on the function role turn the remediator into the most dangerous identity in the account. Scope actions and resources.
- Deleting an access key destroys forensic evidence and cannot be undone; prefer Inactive plus a deny policy.
- A single denied call is not an attack. Without a threshold or exemptions, health checkers and mis-scoped jobs will get quarantined.
- CloudTrail to CloudWatch Logs delivery has a delay of minutes, so this is fast but not instant; keep expectations honest.
- Role sessions and federated users cannot be contained by deleting keys. Alert on them and use session revocation instead.
- Forgetting the bucket-owner-full-control condition or the AclCheck statement makes trail creation fail with an unhelpful error.
- A remediation function that errors before notifying leaves humans blind. Notify first, contain second.
// Frequently asked questions
How do I automatically revoke compromised IAM credentials?
Stream CloudTrail to CloudWatch Logs, subscribe a Lambda to AccessDenied and UnauthorizedOperation events, then disable the key, attach a deny-all policy and notify. This article gives the full SAM template.
Should the Lambda delete the access key or deactivate it?
Deactivate. It stops the key immediately, is reversible, and preserves the key id for the investigation.
Can this contain a compromised IAM role?
Not by deleting keys. For roles, alert, then add a deny policy conditioned on token issue time to invalidate existing sessions.
How fast is it?
Log delivery and subscription add minutes at worst and often much less. It is near-real-time, not synchronous with the API call.
How do I stop false positives?
Use Contributor Insights to find noisy identities, tag exemptions, and require a minimum number of denials in a window. For continuous policy scanning see Cloud Governance as Code with Cloud Custodian.
// The outcome
Seconds from anomalous activity to revoked credentials and an alert.
// Where to take it next
- Add a count-in-window threshold using a metric filter and alarm before containment.
- Extend to an organisation trail with a central log account and cross-account remediation roles.
- Send a structured event to a ticketing or chat channel as well as email.
- Look at Watching the Watchers: Identity-Tampering Detection with ChatOps Triage for the equivalent on the identity provider side and Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys for preventive guardrails.