
Hands-on AWS Security: Simulating EC2 Attack Chains, IMDS Credential Theft, and GuardDuty Detections
Hands-on lab simulating EC2 IMDS credential theft, triggering GuardDuty OutsideAWS detection, and automating response with IMDSv2 and EventBridge.
Builder TL;DR: A hands-on security lab simulating how an initial RCE on an EC2 instance leads to IMDS temporary credential theft, S3 exfiltration, and privilege escalation. We analyze the exact conditions required to trigger GuardDuty'sInstanceCredentialExfiltration.OutsideAWSfinding and look at five practical hardening steps, including IMDSv2 enforcement and EventBridge automated remediation.
The Threat Model & Architecture
When deploying applications on EC2, engineers often focus heavily on inbound security group rules and web app firewalls. But what happens once an attacker actually gets a shell on the underlying host?
In AWS, an EC2 instance with an attached IAM role has direct access to the Instance Metadata Service (IMDS) at
169.254.169.254 . If the instance profile is overprivileged and IMDSv1 is enabled, an attacker who obtains remote code execution (RCE) can pull temporary STS credentials and pivot into the wider cloud environment.Attacker Workstation / Test Box │ │ Step 1: Exploit vulnerable web app (RCE) ▼Victim EC2 Instance (Attached IAM Instance Profile) │ │ Step 2: Reverse shell connection │ Step 3: Query IMDSv1 -> Steal temporary STS credentials ▼Attacker uses stolen credentials externally │ │ Step 4: Enumerate S3 buckets and exfiltrate data │ Step 5: Abuse overprivileged IAM role ▼Full Account Exposure (Detected by Amazon GuardDuty)In this lab, we build this scenario in an isolated test account, observe the exact detections generated by Amazon GuardDuty, and implement remediation.
Note: Run this exclusively in a personal sandbox or dedicated test account.
1. Environment Setup
1.1 Enable GuardDuty First
Ensure GuardDuty is actively monitoring API calls before beginning so you capture the baseline events:
aws guardduty create-detector \ --enable \ --finding-publishing-frequency FIFTEEN_MINUTES \ --region us-east-11.2 Simulate an Overprivileged Role
In real production incidents, the core issue is usually an overly broad instance profile. We attach a role with
AmazonS3FullAccess and IAMReadOnlyAccess :# Trust policy allowing EC2 to assume the rolecat > trust-policy.json << 'EOF'{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole" }]}EOF
# Create the role and instance profileaws iam create-role \ --role-name app-workload-ec2-role \ --assume-role-policy-document file://trust-policy.json
aws iam attach-role-policy \ --role-name app-workload-ec2-role \ --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
aws iam attach-role-policy \ --role-name app-workload-ec2-role \ --policy-arn arn:aws:iam::aws:policy/IAMReadOnlyAccess
aws iam create-instance-profile \ --instance-profile-name app-workload-ec2-profile
aws iam add-role-to-instance-profile \ --instance-profile-name app-workload-ec2-profile \ --role-name app-workload-ec2-role
2. The Attack Simulation
2.1 Credential Harvesting via IMDSv1
Once an interactive shell is gained on the victim instance, the first target is the metadata endpoint:
# Check the attached role namecurl http://169.254.169.254/latest/meta-data/iam/security-credentials/# Returns: app-workload-ec2-role
# Extract the temporary STS security credentialscurl http://169.254.169.254/latest/meta-data/iam/security-credentials/app-workload-ec2-roleThis returns raw JSON containing:
-
AccessKeyId(starts withASIA...)
-
SecretAccessKey
-
Token
-
Expiration
2.2 Where You Run Stolen Credentials Matters
This is where many lab write-ups miss a critical detail. GuardDuty has two distinct findings for instance credential exfiltration, each with narrow trigger criteria:
GuardDuty Finding | Trigger Condition |
|---|---|
InstanceCredentialExfiltration.OutsideAWS | Temporary instance credentials used from an IP outside of AWS entirely. |
InstanceCredentialExfiltration.InsideAWS | Credentials used from an IP or VPC endpoint belonging to a different AWS account. |
If you test using credentials from another EC2 instance inside the same AWS account, neither finding fires.
To observe
InstanceCredentialExfiltration.OutsideAWS , configure the stolen credentials on your external local development machine:export AWS_ACCESS_KEY_ID="ASIAIOSFODNN7EXAMPLE"export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"export AWS_SESSION_TOKEN="AQoDYXdzEJr..."
# Verify the caller identityaws sts get-caller-identityWithin 15 to 30 minutes, GuardDuty generates a High Severity finding:
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWSLegitimate EC2 workloads rarely export their own STS session keys to an external IP. This makes it one of GuardDuty's highest-fidelity signals.
3. Defense and Remediation
Fix 1: Enforce IMDSv2
IMDSv2 uses session-oriented requests, requiring a
PUT request with a secret token before querying metadata. Crucially, setting the hop limit to 1 prevents tokens from traversing network boundaries or SSRF proxies:aws ec2 modify-instance-metadata-options \ --instance-id i-0123456789abcdef0 \ --http-tokens required \ --http-put-response-hop-limit 1For new deployments, enforce this at the Launch Template level and back it up with an AWS Organizations Service Control Policy (SCP) or AWS Config rule (
ec2-imdsv2-check ).Fix 2: Least Privilege Resource Scoping
Remove generic managed policies like
AmazonS3FullAccess . Scope the policy down to the exact bucket and path the application requires:{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::app-workload-data-prod/uploads/*" }]}Fix 3: Outbound Egress Filtering
Most engineers tightly restrict inbound security groups but leave outbound set to
0.0.0.0/0 . Restricting egress traffic to HTTPS (443) and internal database subnets prevents standard reverse shell payloads from phoning home to attacker listeners.Fix 4: Automated Remediation with EventBridge & Lambda
Rather than waiting for manual triage when an exfiltration alert fires, wire GuardDuty findings to Amazon EventBridge:
{ "source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"], "detail": { "type": ["UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS"] }}The downstream Lambda function can:
- Attach an explicit inline
DenyAllpolicy to the compromised IAM role to immediately invalidate all active STS sessions.
- Tag the EC2 instance with
Quarantine: True.
- Dispatch an alert via SNS to the on-call security engineer with the compromised caller IP and role details.
4. Teardown & Resource Cleanup
To avoid running up costs after testing:
# Terminate EC2 instancesaws ec2 terminate-instances --instance-ids <YOUR_INSTANCE_IDS>
# Clean up IAM role and instance profileaws iam remove-role-from-instance-profile \ --instance-profile-name app-workload-ec2-profile \ --role-name app-workload-ec2-role
aws iam delete-instance-profile --instance-profile-name app-workload-ec2-profileaws iam detach-role-policy --role-name app-workload-ec2-role --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccessaws iam detach-role-policy --role-name app-workload-ec2-role --policy-arn arn:aws:iam::aws:policy/IAMReadOnlyAccessaws iam delete-role --role-name app-workload-ec2-role
💬 Let's Discuss
- How is your team currently handling the transition to IMDSv2 across legacy EC2 fleets without breaking application SDK calls?
- Do you automate credential revocation on
InstanceCredentialExfiltration.OutsideAWSalerts, or keep it as a human-in-the-loop review?
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article