One GET Request, Full AWS Access: How Attackers Steal EC2 Credentials (and How IMDSv2 Stops Them)
SSRF, the EC2 metadata service and stolen IAM role credentials: an AWS incident response playbook for revoking sessions, isolating the instance and hardening security groups, so the next request gets a polite no. Every
SSRF, the EC2 metadata service and stolen IAM role credentials: an AWS incident response playbook for revoking sessions, isolating the instance and hardening security groups, so the next request gets a polite no.
Every EC2 instance with an IAM role has a little service sitting at 169.254.169.254. Ask it for credentials and it gives you some. That's its job. It's the reason your app doesn't need access keys in a config file.
The catch is who's allowed to ask. On an instance still running IMDSv1, the answer is anyone who can get the box to make an HTTP GET. It's the colleague who reads out the office door code to anyone who rings and says "it's me".
How the attacker got the keys
The instance ran a web app with a "fetch this URL for me" feature. Link previews, import from URL, that sort of thing. Nobody had thought much about which URLs it would fetch.
Photo by Jefferson Santos on Unsplash
That's SSRF, server-side request forgery. The attacker can't run commands on the server, but they can get the server to make requests on their behalf. So they give it this:
https://app.example.com/preview?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/
That returns the role name. Add it to the end of the URL and you get this back:
{
"Code": "Success",
"Type": "AWS-HMAC",
"AccessKeyId": "ASIA...",
"SecretAccessKey": "...",
"Token": "...",
"Expiration": "..."
}
Copy those into three environment variables on any laptop in the world and you are now the instance role. Nothing in IAM was broken. The attacker just borrowed it.
Why IMDSv2 would have said no
All of that only works on IMDSv1, where a plain GET gets you the credentials and nobody asks anything.
IMDSv2 wants a token first. You send a PUT to get one, then send the GET with the token in a header:
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/iam/security-credentials/
Most SSRF bugs can only make the server send a plain GET. They can't switch to PUT and they can't add headers, so there's no token, and without a token there are no credentials. The attacker gets a 401 and has to go and rethink their afternoon.
It does a couple of other useful things too. The token response goes out with a hop limit, so with the limit set to 1 it can't get past the instance itself (a container on a bridged network can't reach it, for example). And the token endpoint refuses any PUT that has an X-Forwarded-For header, which rules out a lot of open-proxy tricks.
I want to be clear about the limits, though, because this gets oversold a lot. IMDSv2 stops SSRF. It doesn't stop someone who already has a shell on the box. Anything that can run curl on the instance can do the PUT and the GET just like your app does. IMDSv2 would have closed the door used here, but if the attacker is already inside, you're into containment.
Spotting it
Instance credentials leave a fingerprint in CloudTrail. The session name is the instance ID:
arn:aws:sts::111122223333:assumed-role/app-instance-role/i-0abc123def4567890
So if you see that session making calls from an IP that isn't that instance, something has gone wrong. GuardDuty checks for exactly this and raises UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS when the credentials show up outside AWS. There's an .InsideAWS version too, for when they're used from someone else's AWS account. Attackers rent EC2 as well.
Containment, step one: kill the stolen credentials
Instance credentials expire after a few hours, so it's tempting to just wait. Please don't. If the role can call iam:CreateUser or iam:CreateAccessKey, the attacker only needs a minute to make themselves a set of keys that never expire.
You can't delete an STS session, but you can tell IAM to refuse anything signed by a session issued before a certain time. On the role's page in the console there's a button called Revoke active sessions. It adds an inline policy that looks like this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": "*",
"Resource": "*",
"Condition": {
"DateLessThan": { "aws:TokenIssueTime": "2026-12-02T14:05:00Z" }
}
}
]
}
You can do the same from the CLI:
aws iam put-role-policy \
--role-name app-instance-role \
--policy-name AWSRevokeOlderSessions \
--policy-document file://revoke-older-sessions.json
It's a blunt tool. It catches every session for that role, so your healthy instances on the same role will get AccessDenied until they pick up fresh credentials. I'd take a short outage I chose over an attacker I didn't, but warn people before you press it.
It also doesn't stop the compromised instance asking for new credentials, which will be issued after your cutoff and work fine. So take the role off the instance as well:
aws ec2 describe-iam-instance-profile-associations \
--filters Name=instance-id,Values=i-0abc123def4567890
aws ec2 disassociate-iam-instance-profile \
--association-id iip-assoc-0123456789abcdef0
Then go through CloudTrail for everything that session did while it was out. The calls I'd look for first are CreateUser, CreateAccessKey, CreateLoginProfile, AttachRolePolicy, PutRolePolicy, UpdateAssumeRolePolicy and RunInstances, plus any burst of GetObject. Revoking the session does nothing about an access key they created with it.
Containment, step two: isolate the instance
Don't terminate it. It's evidence now, and at some point someone will ask how they got in.
Photo by Paul Hanaoka on Unsplash
The standard move is to put it in a security group with no rules at all. There's a trap here that catches people in the middle of an incident: security groups are stateful, and taking a rule away doesn't drop a connection that's already being tracked. If the attacker has a session open, swapping the group may not kick them off.
AWS's incident response guidance gets round this in two moves. First, put the instance in a group that allows all traffic in and out from 0.0.0.0/0. I know. But it turns the existing connections into untracked ones. Then, straight away, move it into the empty isolation group, and the untracked connections get cut.
# 1. allow-all group, only for a few seconds (makes existing flows untracked)
aws ec2 modify-instance-attribute --instance-id i-0abc123def4567890 \
--groups sg-0allowalltemp000000
# 2. isolation group, no inbound or outbound rules
aws ec2 modify-instance-attribute --instance-id i-0abc123def4567890 \
--groups sg-0isolation00000000
If opening it up for even a few seconds makes you uneasy, a deny rule in the subnet's network ACL cuts traffic straight away, since NACLs don't track connections. The downside is that it hits everything else in that subnet too.
After that, turn on termination protection so nobody tidies it away, snapshot the EBS volumes, tag it clearly, and grab memory if you have the tooling for it. The empty security group also blocks the SSM agent, so Session Manager won't work. Do the forensics on the snapshot from a separate instance.
Making sure it doesn't happen again
Start with IMDSv2. On the instance:
aws ec2 modify-instance-metadata-options \
--instance-id i-0abc123def4567890 \
--http-tokens required \
--http-put-response-hop-limit 1 \
--http-endpoint enabled
And as the default for new instances in the region:
aws ec2 modify-instance-metadata-defaults \
--http-tokens required \
--http-put-response-hop-limit 1
If containers on the host genuinely need the metadata service, set the hop limit to 2, knowing that's what you've chosen.
Before switching older instances over, look at the MetadataNoToken metric in CloudWatch. It counts IMDSv1 calls per instance. Old SDKs and some agents still use v1, and it's better to find them on a graph than in an outage.
Then lock it in at the organisation level so a tutorial from 2019 can't undo it next month. This SCP blocks launching instances without IMDSv2:
{
"Sid": "RequireImdsV2OnLaunch",
"Effect": "Deny",
"Action": "ec2:RunInstances",
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": {
"StringNotEquals": { "ec2:MetadataHttpTokens": "required" }
}
}
And this one denies any call made with credentials that came from IMDSv1, in case something slips through:
{
"Sid": "DenyImdsV1Credentials",
"Effect": "Deny",
"Action": "*",
"Resource": "*",
"Condition": {
"NumericLessThan": { "ec2:RoleDelivery": "2.0" }
}
}
Next, the role. The SSRF bug got the attacker in, but the role's permissions decided how much damage they could do. Cut it down to what the app actually calls. IAM Access Analyzer can generate a policy from CloudTrail activity, which is a decent place to start. An app that reads one bucket has no business with s3:*, and certainly not with anything that starts with iam:. If you want to go further, the aws:EC2InstanceSourceVPC and aws:EC2InstanceSourcePrivateIPv4 condition keys let you deny instance credentials used from outside the instance's own network. They work best with VPC endpoints, so read up before rolling them out.
Then the security groups, the everyday ones rather than the isolation group. Close SSH and RDP to the internet and use Session Manager instead, so there are no keys to lose and no bastion to babysit. Let the app instances accept traffic only from the load balancer's security group, not from an IP range. Take public IPs off anything that sits behind a load balancer. And look at egress, which almost nobody does. Most groups still allow all outbound traffic, and an app server that talks to one database and a couple of AWS services doesn't need the whole internet. Tighter egress makes it a lot harder to download tools or send data out. An AWS Config rule like restricted-ssh will tell you when someone opens port 22 "just for the demo" and forgets.
Last, and easy to skip once everything else is done: fix the SSRF bug. Check URLs against an allow-list, resolve the hostname and reject private, loopback and link-local addresses (169.254.0.0/16), and don't follow redirects blindly. Otherwise the attacker just moves on to the next internal thing that answers a GET.
What I'd have ready before it happens
Most of the time in an incident like this isn't spent fixing anything. It's spent working out what you're allowed to touch. Who else uses this role? Will revoking sessions take down the payment service at 3pm on a Friday? Is that allow-all security group a containment step or a career-limiting move? Those are bad questions to be answering for the first time while GuardDuty is shouting at you.
So the things I'd have sorted in advance are boring ones. One role per workload, so "revoke active sessions" only hits the thing that's on fire. The isolation and allow-all security groups already created in every VPC, so step one isn't writing Terraform under pressure. A short runbook with the actual commands, tried once in a sandbox. And IMDSv2 enforced by SCP long before anyone needs this post.
The metadata service isn't really the villain here. It did exactly what it was built to do. The fix comes down to three things: make it ask for a token, give the role less to hand over, and have the runbook written before the GuardDuty alert, not after.
Originally published on Medium.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.