AWS Builder Center

Your AWS IAM Role Is Compromised: How to Detect and Stop an Attacker

Building an automated threat detection and response system using Amazon GuardDuty, Amazon EventBridge, AWS Lambda, and IAM.

1. Introduction: What If Your Cloud Identity Becomes the Attacker's Identity?

Imagine this scenario.
A developer assumes an IAM role to deploy an application. The role has permissions to access S3 buckets, read application secrets, and manage certain EC2 resources.
An attacker somehow obtains the temporary credentials associated with that role.
Instead of exploiting a server or installing malware, the attacker simply starts making legitimate AWS API requests using those stolen credentials.
From AWS's perspective, these requests are authenticated.
The attacker may now attempt to:
  • Access sensitive S3 objects.
  • Discover additional IAM permissions.
  • Create unauthorized infrastructure.
  • Modify security configurations.
  • Access resources across the AWS environment.
This creates a serious security challenge.
What happens when the identity trusted by your infrastructure becomes the source of the attack?
In cloud environments, identity is a critical security boundary. Protecting IAM roles is therefore just as important as protecting the infrastructure itself.
Let's explore how to detect suspicious IAM activity and build an automated security response architecture.

2. Understanding the Attack: How Can an IAM Role Be Abused?

Before building a defense, we need to understand the attack path.
Consider an application running on an EC2 instance with an attached IAM role.
The application uses temporary credentials to communicate with AWS services.
An attacker who obtains those credentials may attempt to reuse them from another environment.
A simplified attack scenario looks like this:
EC2 Application
|
v
IAM Role Assigned
|
v
Temporary Credentials
|
v
Credentials Compromised
|
v
Attacker Reuses Them
|
+------+------+
| |
v v
S3 Access IAM Discovery
| |
v v
Data Access Privilege Abuse
The important observation is that the attacker does not necessarily need to compromise the AWS account's root credentials.
Abusing an existing identity with excessive permissions may be sufficient.

3. The Security Challenge

Traditional security monitoring often focuses on network traffic, server logs, and application vulnerabilities.
However, cloud attacks can happen entirely through legitimate APIs.
For example:
  • An IAM role accesses resources it has never accessed before.
  • A workload suddenly performs unusual API operations.
  • Credentials are used in an unexpected context.
  • An identity attempts to enumerate IAM users and policies.
  • Suspicious activity occurs after a credential exposure.
These behaviors do not automatically prove compromise. Legitimate deployments and application changes can also generate unusual activity.
The challenge is identifying suspicious behavior and investigating it before it becomes a larger incident.

4. Our Solution: Automated IAM Threat Detection

We can build a security monitoring architecture using native AWS services.
The proposed solution combines threat detection, event processing, notifications, and controlled incident response.

Architecture

AWS Environment
|
v
AWS CloudTrail
API Activity Logs
|
v
Amazon GuardDuty
Threat Detection
|
v
Amazon EventBridge
Finding Rule
|
v
AWS Lambda
Incident Handler
|
+------+------+
| |
v v
Amazon SNS CloudWatch
Notifications Logs
|
v
Security Administrator
|
v
Investigate & Respond

AWS Services Used

1. AWS CloudTrail
Records AWS API activity and provides an audit trail of actions performed by identities.
2. Amazon GuardDuty
Analyzes supported data sources and identifies potentially malicious activity using threat intelligence and machine learning.
3. Amazon EventBridge
Receives GuardDuty findings and routes relevant events to configured targets.
4. AWS Lambda
Processes security findings and generates structured incident notifications.
5. Amazon SNS
Delivers security alerts to administrators through email or other supported subscriptions.
6. Amazon CloudWatch
Provides execution logs and monitoring information for the response function.

5. Implementation: Build the Detection Workflow

Let's implement a basic version of this architecture.

Step 1: Enable Amazon GuardDuty

Open the Amazon GuardDuty console.
  1. Select the AWS Region you want to monitor.
  1. Enable GuardDuty.
  1. Review the supported data sources and protection plans.
  1. Verify that GuardDuty is generating findings.
GuardDuty can identify suspicious AWS activity, including certain credential misuse and unauthorized access patterns.
For this demonstration, we will use GuardDuty findings as the trigger for our response workflow.

Step 2: Configure Amazon EventBridge

Create an EventBridge rule that receives GuardDuty findings.
Use the following event pattern:
{
"source": [
"aws.guardduty"
],
"detail-type": [
"GuardDuty Finding"
]
}
This rule matches GuardDuty finding events.
For a production environment, you can further filter findings by severity, finding type, account, or affected resource.

Step 3: Create an SNS Notification Topic

Create an SNS topic:
 IAMThreatAlerts 
Subscribe your security team's email address.
Confirm the subscription so that the system can deliver alerts.

Step 4: Create the Lambda Incident Handler

Now we need a Lambda function to process the incoming security finding.
The following Python example extracts important information and sends an alert.
import json
import os
import boto3

sns = boto3.client("sns")

TOPIC_ARN = os.environ["SNS_TOPIC_ARN"]

def lambda_handler(event, context):

finding = event.get("detail", {})

alert = {
"finding_id": finding.get("id"),
"finding_type": finding.get("type"),
"severity": finding.get("severity"),
"account": finding.get("accountId"),
"region": event.get("region"),
"resource": finding.get("resource")
}

sns.publish(
TopicArn=TOPIC_ARN,
Subject="AWS IAM Security Alert",
Message=json.dumps(alert, indent=2, default=str)
)

return {
"statusCode": 200,
"body": "Security alert delivered"
}
Configure the  SNS_TOPIC_ARN  environment variable with your SNS topic ARN.
The Lambda execution role must have permission to publish to the SNS topic.
EventBridge must also have permission to invoke the Lambda function.
This example forwards GuardDuty findings. It does not independently establish that an IAM role is compromised. The security team must inspect the finding type, affected identity, activity, and surrounding evidence.

Step 5: Test the Detection Pipeline

Use a dedicated test account or an isolated environment.
  1. Enable GuardDuty.
  1. Configure the EventBridge rule.
  1. Deploy the Lambda function.
  1. Configure the SNS subscription.
  1. Generate a supported GuardDuty sample finding using the GuardDuty console.
  1. Verify that EventBridge invokes Lambda.
  1. Check the Lambda logs in CloudWatch.
  1. Confirm that the SNS notification arrives.
A sample finding allows you to validate the integration without attempting to steal or misuse actual credentials.

6. Incident Response: What Should We Do After Detecting a Threat?

Detection alone does not stop an attacker.
Once a potentially compromised role is identified, the security team needs an appropriate containment strategy.
A response process could look like this:
Phase 1 — Identify
Determine the affected AWS account, IAM role, session, finding type, and associated API activity.
Phase 2 — Investigate
Review CloudTrail events to understand which actions were performed, when they occurred, and which resources were accessed.
Phase 3 — Contain
If compromise is confirmed, revoke the affected role's active sessions or apply a more narrowly scoped denial where appropriate.
AWS IAM provides a mechanism to revoke temporary role session permissions using the  AWSRevokeOlderSessions  policy.
An important consideration: revoking sessions for a role can disrupt every user and workload currently using that role, not just the attacker.
Phase 4 — Recover
Review the role's trust policy, permissions, workload configuration, and credential exposure. Restore legitimate access using verified credentials.
Phase 5 — Learn
Investigate the root cause and improve monitoring, permissions, and credential protection.

7. Going Beyond Detection: Can We Build an Autonomous Security Response?

Here is where the architecture becomes more interesting.
Instead of simply sending alerts, we can extend the system into a controlled security response platform.
Imagine adding a response engine that evaluates:
  • Which IAM role is involved?
  • What permissions does the role have?
  • What suspicious activity was detected?
  • Which resources could be affected?
  • Is automatic containment safe?
  • Does the action require human approval?
The response engine can classify incidents into different risk levels.
Risk level
Suggested response
Low
Log and monitor
Medium
Notify security team
High
Investigate and request approval
Critical
Initiate an approved containment workflow
This introduces an important principle:
Security automation should make decisions based on risk and context, not just the presence of an alert.
For sensitive environments, automated containment should have safeguards, audit trails, and a recovery procedure.

8. Security Best Practices for IAM Roles

A detection system is only one part of cloud security.
We should also reduce the likelihood and impact of credential compromise.

Apply Least Privilege

Give each IAM role only the permissions required for its workload.
Avoid using broad managed policies without reviewing their permissions.

Prefer Temporary Credentials

Use IAM roles and temporary credentials instead of embedding long-term access keys inside applications.

Secure Trust Policies

Restrict which identities and services can assume a role. Use appropriate conditions, including MFA requirements where applicable.

Monitor IAM Activity

Use CloudTrail and GuardDuty to identify suspicious activity and maintain an investigation trail.

Review Unused Permissions

Regularly inspect role permissions and remove unnecessary actions and resources.

Protect the Security Controls

Restrict access to IAM policies, GuardDuty settings, EventBridge rules, and Lambda response functions.
An attacker who can modify your security monitoring system may be able to interfere with detection.

9. Future Scope: From Cloud Security to Identity Governance

The architecture described here provides a foundation for a more advanced security system.
Future improvements could include:
  • Centralized monitoring across multiple AWS accounts.
  • Automated incident ticket creation.
  • Risk-based IAM permission analysis.
  • Integration with AWS Security Hub.
  • Policy-based response authorization.
  • Human approval workflows for sensitive operations.
  • AI-assisted investigation of security findings.
A particularly interesting direction is applying identity governance to autonomous AI agents.
As AI agents begin interacting with cloud resources, they also need controlled identities, permissions, and accountability.
An AI agent should not receive unrestricted AWS access simply because it is capable of performing a task.
Its identity, requested action, and permissions should be validated before execution.

10. Conclusion

Cloud security is evolving.
Attackers do not always need to break through traditional infrastructure defenses. Sometimes, they only need access to an identity that already has permission to operate inside the environment.
That is why IAM security must be treated as a continuous process rather than a one-time configuration.
By combining Amazon GuardDuty, EventBridge, Lambda, SNS, and CloudTrail, we can establish a foundation for detecting suspicious identity activity and responding in a controlled manner.
The ultimate objective is not simply to detect compromised credentials.
It is to minimize the damage they can cause.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article