← Blog
November 23, 202610 min readSecurity EngineeringCloud SecuritySSRFAppSec

Why can SSRF still reach EC2 role credentials seven years after IMDSv2?

IMDSv2 shipped on 19 November 2019, yet any instance left at HttpTokens: optional still hands role credentials to a single SSRF GET. What the session token really blocks, where it stops helping, and a five-step rollout that makes IMDSv2 mandatory across an AWS organization: inventory, callers, flip, defaults and an SCP that locks it.

By The Xalgorix Team

On 19 November 2019 AWS shipped version 2 of the EC2 Instance Metadata Service, and the launch post was blunt about why: open reverse proxies, misconfigured WAFs and server-side request forgery kept turning plain HTTP GETs into a set of IAM role credentials. Seven years later, an SSRF on an EC2 instance can still end at 169.254.169.254/latest/meta-data/iam/. The reason is mundane. IMDSv2 was added alongside the old protocol, not instead of it, and an instance whose metadata options say HttpTokens: optional answers the 2019-era request exactly as it always did.

So the useful question is not “do we use IMDSv2?” but “can anything in our estate still launch or run with IMDSv1 switched on?” This guide walks through what IMDSv2 actually blocks, the gaps it leaves, and a rollout that turns it from an option into an organisation-wide guarantee: inventory, find the callers, flip the instances, change the defaults, then lock the setting with policy so it cannot drift back.

One GET versus a session

With IMDSv1, metadata is a plain unauthenticated HTTP service on a link-local address. Any process that can make the instance send a GET can read it. One request lists the role name, and a second returns that role's temporary credentials:

# IMDSv1: one request, no token. This is all a basic SSRF needs.
GET http://169.254.169.254/latest/meta-data/iam/security-credentials/<role-name>

# IMDSv2: open a session with PUT, then send the token on every read
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/

The session design stacks three separate obstacles in front of an attacker, and it helps to know which one is doing the work in your environment:

  • The PUT. A session starts with a PUT request. Many SSRF sinks — URL previews, image fetchers, PDF renderers, webhook testers — only ever issue GETs, and AWS said the vast majority of third-party WAFs it analysed do not permit PUT requests at all.
  • The headers. The token has to be requested with one custom header and presented in another. AWS also refuses to issue a token to any request that carries an X-Forwarded-For header, which is aimed squarely at open reverse proxies that relay requests to the metadata address.
  • The hop limit. The PUT response is sent with an IP TTL of 1 by default, so the token cannot survive a routing hop. That defeats open layer-3 firewalls and NAT setups that would otherwise let an outside host talk to the instance's metadata endpoint. The token is also only usable from the instance where the session began, and a session lasts at most six hours.
PUT /latest/api/token
GET-only sinks stop here
No X-Forwarded-For
proxies refused a token
Response TTL = hop limit
token dies after N hops
Token header on reads
credentials returned
A GET-only SSRF fails at the first box. An attacker who controls method and headers gets through all three, which is why IMDSv2 is a layer, not the fix for SSRF.

Where IMDSv2 stops helping

IMDSv2 raises the bar for one specific class of request. It does nothing about several others, and a rollout plan that treats it as “SSRF solved” will leave these open:

  • Full-control SSRF. If the vulnerable feature lets the attacker choose the method and set headers — a configurable webhook, an “HTTP request” step in a workflow builder, a proxy endpoint — it can perform the PUT and replay the token like any local client. AWS's own wording is that the design protects against the vast majority of SSRF bugs, not all of them.
  • Code execution on the host. Once an attacker runs commands, they are a local client and IMDSv2 is just one extra curl.
  • A hop limit sized for containers. Containers on a bridged network sit one hop away from the instance. Raise the hop limit so they can reach IMDS and every container on that host, including a compromised one, can obtain the instance role's credentials.
  • Other credential endpoints. These settings govern the EC2 instance metadata service only. ECS task roles and EKS pod identities are delivered through their own endpoints and need their own review.
IMDSv2 is defence in depth. It makes the common GET-only SSRF worthless against instance credentials; it does not make the SSRF itself acceptable. Fix the request path too — see our piece on why SSRF filters and HTTP clients parse different URLs.

The rollout: inventory, callers, flip, defaults, lock

AWS's transition guide lays out a path that maps neatly onto five moves. The order matters: switching IMDSv1 off before you know who still calls it breaks agents and boot scripts, and locking the setting before the estate is clean just turns launches into failures.

1 · Inventory
ImdsV1Enableddescribe-instancesec2-imdsv2-check
2 · Callers
MetadataNoTokenIMDS Packet AnalyzerSDK upgrades
3 · Flip
HttpTokens=requiredMetadataNoTokenRejected
4 · Defaults
AMI imds-support v2.0Region defaultsDeclarative policy
5 · Lock
SCP condition keysIMDSv2 enforcement
Each stage has a signal that tells you when it is safe to move to the next one.

1. Inventory the instances that still allow IMDSv1

Each instance reports a CloudWatch metric, ImdsV1Enabled, that is 1 when HttpTokens is optional and 0 when it is required, so a single metric-math search across AWS/EC2 gives you a fleet count to drive towards zero. The same answer per Region from the CLI:

aws ec2 describe-instances \
  --query "Reservations[].Instances[] | [?MetadataOptions.HttpTokens=='optional'].InstanceId" \
  --output text

For continuous coverage, the AWS Config managed rule ec2-imdsv2-check and Security Hub control EC2.8 flag the same condition, as AWS notes in its September 2023 rollout post.

2. Find out who is still making IMDSv1 calls

An instance that allows IMDSv1 is not necessarily using it. The MetadataNoToken metric counts metadata calls made without a token; when it stays at zero for an instance through a full stop, start and normal working cycle, nothing on that box depends on v1. AWS points out that most IMDSv1 calls happen at launch and shutdown, so a week of steady-state traffic is not enough evidence on its own.

When the metric is non-zero, AWS's open-source IMDS Packet Analyzer logs which process made each tokenless call. The usual culprits are old agents, hand-rolled boot scripts that curl the metadata path, and outdated SDKs. Every current AWS SDK and the CLI speak IMDSv2; AWS publishes the minimum versions (for example AWS CLI 1.16.289, Boto3 1.12.6, botocore 1.13.25).

3. Flip running instances to required

The change is a single API call and, per AWS, takes effect immediately without a restart:

aws ec2 modify-instance-metadata-options \
  --instance-id i-0123456789abcdef0 \
  --http-tokens required --http-endpoint enabled

After the flip, watch MetadataNoTokenRejected. It only emits once IMDSv1 is off and counts the tokenless calls that were turned away, which makes it the fastest way to spot the cron job nobody remembered. Put the same setting in your infrastructure code so the next deploy does not quietly revert it: MetadataOptions.HttpTokens: required in a CloudFormation launch template, or metadata_options { http_tokens = "required" } in Terraform.

4. Make every new launch safe by default

Three layers decide what a new instance gets, evaluated per option in this order of precedence: values set at launch (directly or in the launch template) win, then the account's Region-level defaults, then the AMI's own setting.

  • AMI. An AMI registered or modified with --imds-support v2.0 launches instances with HttpTokens: required and a hop limit of 2. Amazon Linux 2023 ships this way. The attribute cannot be undone once set, so only apply it to images whose software you have already checked.
  • Account defaults, per Region. aws ec2 modify-instance-metadata-defaults --http-tokens required --http-put-response-hop-limit 2 sets the default for new launches in one Region of one account. It does not touch existing instances, and it has to be repeated in every Region you use.
  • Organisation-wide. The AWS Organizations declarative policy for EC2 has an Instance Metadata Defaults attribute that sets the same defaults (and enforcement) for every account it is attached to, and account administrators cannot change the value locally.

5. Lock it so it cannot drift back

Defaults are only defaults: a launch template can still ask for optional, and anyone with ec2:ModifyInstanceMetadataOptions can switch a running instance back. Two mechanisms close that. The account-level --http-tokens-enforced enabled setting (or its declarative-policy equivalent) makes any launch fail unless HttpTokens resolves to required. And service control policies built on the EC2 condition keys stop people weakening the setting in the first place.

An SCP that keeps IMDSv1 off

The statements below combine the condition keys AWS documents for this purpose: ec2:MetadataHttpTokens on RunInstances, ec2:Attribute/HttpTokens on ModifyInstanceMetadataOptions, a cap on the hop limit, a guard on the account defaults API, and ec2:RoleDelivery, which is 1.0 for credentials fetched over IMDSv1 and 2.0 for IMDSv2. Replace the break-glass role ARN with your own and test in a sandbox OU first: once attached, launches that do not request required fail with UnauthorizedOperation, so set it explicitly in launch templates and infrastructure code rather than relying on Region defaults to fill it in.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RequireImdsV2AtLaunch",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": { "StringNotEquals": { "ec2:MetadataHttpTokens": "required" } }
    },
    {
      "Sid": "DenyOptOutOnRunningInstances",
      "Effect": "Deny",
      "Action": "ec2:ModifyInstanceMetadataOptions",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": {
        "StringNotEquals": { "ec2:Attribute/HttpTokens": "required" },
        "Null": { "ec2:Attribute/HttpTokens": "false" }
      }
    },
    {
      "Sid": "CapHopLimit",
      "Effect": "Deny",
      "Action": "ec2:RunInstances",
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": { "NumericGreaterThan": { "ec2:MetadataHttpPutResponseHopLimit": "2" } }
    },
    {
      "Sid": "OnlyPlatformTeamChangesDefaults",
      "Effect": "Deny",
      "Action": "ec2:ModifyInstanceMetadataDefaults",
      "Resource": "*",
      "Condition": {
        "ArnNotLike": { "aws:PrincipalArn": "arn:aws:iam::*:role/platform-imds-admin" }
      }
    },
    {
      "Sid": "RejectCredentialsFetchedOverImdsV1",
      "Effect": "Deny",
      "Action": "*",
      "Resource": "*",
      "Condition": { "NumericLessThan": { "ec2:RoleDelivery": "2.0" } }
    }
  ]
}

The last statement is the one that pays off during the migration itself. Requests signed with anything other than EC2 role credentials carry no ec2:RoleDelivery value, so the condition never matches them; requests signed with credentials an SSRF pulled over IMDSv1 are denied even on an instance you have not flipped yet. Roll it out after step 2 shows no legitimate IMDSv1 callers, or it will break the very agents you are still upgrading.

Choosing the hop limit: 1 or 2

The hop limit is the one setting where the right answer depends on what runs on the box. It accepts 1 to 64. When neither the launch nor the account defaults set it, it is 1, or 2 if the AMI says imds-support v2.0.

Who on this instance needs instance-role credentials?
Only host processes
Hop limit 1. Bridged containers cannot complete the PUT, which is exactly the point.
Containers that use the instance role
Hop limit 2 so they get a token instead of falling back to IMDSv1. Every container on the host now shares that role.
Kubernetes nodes
Prefer hop limit 1 and give pods their own roles; a pod that reaches the node role inherits the node's permissions.
A higher hop limit is a deliberate decision to let containers reach the instance role. Make it only where that is what you want.

The Kubernetes case is where this bites most. Datadog Security Labs' write-up on EKS nodes shows a compromised pod calling the worker node's metadata service for the node role, and its remediation is IMDSv2 required plus a hop limit of 1, noting that IMDSv2 alone is not enough, with a Kubernetes NetworkPolicy blocking the metadata address as a second layer. Pods that run with hostNetwork: true share the node's network namespace and are not a hop away, so the hop limit does not stop them; keep that privilege rare.

When credentials leak anyway

Assume one day a full-control SSRF or an RCE hands someone a valid token. Two more controls limit what the stolen credentials are worth:

  • Pin credentials to where they were issued. The aws:EC2InstanceSourceVPC and aws:EC2InstanceSourcePrivateIPv4 condition keys, described in AWS's March 2023 post, let an SCP deny instance-role requests that do not come from the instance's own VPC and IP. The comparison relies on aws:SourceVpc, which is only present on calls through VPC endpoints, so plan the endpoint coverage and the exceptions the post lists before turning it on.
  • Alert on use elsewhere. GuardDuty raises InstanceCredentialExfiltration.OutsideAWS when instance-launch-role credentials are used from an external IP, and InstanceCredentialExfiltration.InsideAWS when they are used from another AWS account. Route both to someone who will act on them the same day.

Checking it from the outside

If you test applications on AWS, the metadata options change how you report an SSRF. A GET-only SSRF against an instance with IMDSv1 enabled is a credential-theft path; the same bug against an instance with HttpTokens: required and hop limit 1 is still a finding, but the impact story moves to internal services and whatever else the server can reach. Say which one you observed rather than assuming the worst, and stop at confirming that credentials were returned: listing the role name is enough evidence, and using the keys is outside almost every programme's scope.

For defenders, the end state is easy to state and easy to audit: ImdsV1Enabled sums to zero, MetadataNoTokenRejected stays quiet, the declarative policy or SCP is attached at the root, and any instance that needs a hop limit above 1 has a written reason. Seven years after IMDSv2 shipped, getting there is mostly a matter of finishing the migration rather than starting it.

Ready to see it prove a bug?

Start scanning on Cloud →