TExcelTAD
Home › Cloud & Container Security › Instance Metadata: IMDSv1, IMDSv2 and Hop Limits

Instance Metadata: IMDSv1, IMDSv2 and Hop Limits

Every cloud VM can ask a local HTTP service, at the link-local address 169.254.169.254, about itself: its ID, network, user data, and temporary credentials for its role. That service, the instance metadata service (IMDS), is how workloads get cloud credentials without storing keys (Workload Identity). It is also why server-side request forgery is so dangerous in the cloud: a web application that can be tricked into fetching a URL can be tricked into fetching its own credentials and returning them. SSRF: Allow-Lists and Cloud Metadata showed the application side with a fake metadata service; this lesson is the platform side: how IMDS was hardened, what each protection stops, and how to check that it is on.

IMDSv1: one GET away

The original AWS design answers any HTTP GET from the instance:

text
GET http://169.254.169.254/latest/meta-data/iam/security-credentials/            -> app-role
GET http://169.254.169.254/latest/meta-data/iam/security-credentials/app-role    -> {"AccessKeyId": "ASIA…", "SecretAccessKey": …, "Token": …}

No header, no method other than GET, no secret. Anything that makes the server fetch an attacker-chosen URL (a link preview, a PDF renderer, an XML parser resolving external entities, a misconfigured proxy) can read it. Well-known breaches followed exactly this path: SSRF on a web tier, role credentials from IMDSv1, then the role's over-broad S3 permissions.

IMDSv2: session tokens and a hop limit

IMDSv2 adds three hurdles, each aimed at a property of typical SSRF:

process onthe instance no X-Forwarded-For allowedon the PUT IMDS169.254.169.254 1. PUT /latest/api/tokenX-aws-ec2-metadata-token-ttl-seconds: 21600 2. token (IP TTL = hop limit, e.g. 1) 3. GET .../security-credentials/app-roleX-aws-ec2-metadata-token: token
  1. A PUT to get a session token: most SSRF primitives can only cause GET requests.
  2. Custom headers: the token request needs X-aws-ec2-metadata-token-ttl-seconds and every later request X-aws-ec2-metadata-token; most SSRF primitives can't set headers. Token requests carrying X-Forwarded-For are refused, which stops open reverse proxies and WAFs that forward requests on.
  3. Hop limit: the token response is sent with an IP time-to-live equal to the configured hop limit (http-put-response-hop-limit: 1 unless something sets it, but 2 for instances launched from AMIs registered with ImdsSupport: v2.0, such as Amazon Linux 2023, because AWS expects containers there). Every router or virtual bridge decrements it, so with a limit of 1 the response can't reach a container behind a bridge or a host one hop away.

The instance setting HttpTokens decides whether v1 still works: optional (both versions) or required (v2 only). Azure and Google Cloud chose a simpler hurdle from the start: their metadata services require a header (Metadata: true, Metadata-Flavor: Google) on every request and reject requests carrying X-Forwarded-For.

Which SSRF gets credentials? A model

The program models the IMDS decisions above and five kinds of request-forging capability an attacker might find. It doesn't send any packets: each "client" is a description of what it can control.

python · try it yourself
def imds(req, tokens_required, hop_limit):
    """Return credentials or the reason the request fails, following the IMDSv1/v2 rules."""
    token = None
    if req["can_put"] and req["can_set_headers"]:
        if "X-Forwarded-For" in req["adds_headers"]:
            token_err = "token PUT refused (X-Forwarded-For)"
        elif req["hops"] > hop_limit:
            token_err = f"token response dropped (TTL {hop_limit} < {req['hops']} hops)"
        else:
            token, token_err = "tok", None
    else:
        token_err = "cannot send PUT with headers"
    if token:
        return "CREDENTIALS (v2 session)"
    if not tokens_required:
        return "CREDENTIALS (v1, plain GET)"
    return f"blocked: {token_err}"

clients = {
    "URL-only SSRF (link preview)": dict(can_put=False, can_set_headers=False, adds_headers=[], hops=1),
    "SSRF with header injection, GET only": dict(can_put=False, can_set_headers=True, adds_headers=[], hops=1),
    "open reverse proxy on the instance": dict(can_put=True, can_set_headers=True, adds_headers=["X-Forwarded-For"], hops=1),
    "code execution in a bridged container": dict(can_put=True, can_set_headers=True, adds_headers=[], hops=2),
    "code execution on the instance": dict(can_put=True, can_set_headers=True, adds_headers=[], hops=1),
}
settings = [("v1 allowed, hop 1", False, 1), ("v2 required, hop 2", True, 2), ("v2 required, hop 1", True, 1)]
for name, req in clients.items():
    print(name)
    for label, req_tokens, hop in settings:
        print(f"   {label:20} {imds(req, req_tokens, hop)}")
URL-only SSRF (link preview)
   v1 allowed, hop 1    CREDENTIALS (v1, plain GET)
   v2 required, hop 2   blocked: cannot send PUT with headers
   v2 required, hop 1   blocked: cannot send PUT with headers
SSRF with header injection, GET only
   v1 allowed, hop 1    CREDENTIALS (v1, plain GET)
   v2 required, hop 2   blocked: cannot send PUT with headers
   v2 required, hop 1   blocked: cannot send PUT with headers
open reverse proxy on the instance
   v1 allowed, hop 1    CREDENTIALS (v1, plain GET)
   v2 required, hop 2   blocked: token PUT refused (X-Forwarded-For)
   v2 required, hop 1   blocked: token PUT refused (X-Forwarded-For)
code execution in a bridged container
   v1 allowed, hop 1    CREDENTIALS (v1, plain GET)
   v2 required, hop 2   CREDENTIALS (v2 session)
   v2 required, hop 1   blocked: token response dropped (TTL 1 < 2 hops)
code execution on the instance
   v1 allowed, hop 1    CREDENTIALS (v2 session)
   v2 required, hop 2   CREDENTIALS (v2 session)
   v2 required, hop 1   CREDENTIALS (v2 session)

The table is the argument for HttpTokens=required:

  • With v1 allowed, every client gets credentials, including the plain URL-only SSRF that is by far the most common kind.
  • Requiring v2 stops the URL-only and GET-only SSRF and the forwarding proxy, whatever the hop limit.
  • The hop limit matters for containers: at 2 (needed when containers in bridge networks must use the instance role), any container on the host can fetch the instance's credentials; at 1 they can't.
  • Code execution on the instance itself gets credentials in every configuration. IMDSv2 is a defence against request forgery, not against a compromised host; least privilege on the role is what limits that case (Least Privilege).

How to check and enforce it

console
# lab session (illustrative, lab account 123456789012; not run here)
$ aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId,MetadataOptions.HttpTokens,MetadataOptions.HttpPutResponseHopLimit]" --output text
i-0a1b2c3d4e5f60001    optional    1
i-0a1b2c3d4e5f60002    required    1
i-0a1b2c3d4e5f60003    required    2
$ aws ec2 modify-instance-metadata-options --instance-id i-0a1b2c3d4e5f60001 --http-tokens required --http-put-response-hop-limit 1
  • Inventory: list MetadataOptions for every instance and launch template; HttpTokens=optional is a finding, HttpPutResponseHopLimit > 1 needs a reason.
  • Prevent drift: set the account-level default for new instances to v2-only and turn on account-level IMDSv2 enforcement (HttpTokensEnforced, which makes launches without required fail), or set both for many accounts and regions at once with an AWS Organizations declarative policy; use AMIs that default to v2 (and set the hop limit explicitly, because v2.0 AMIs bring a default of 2); deny ec2:RunInstances without ec2:MetadataHttpTokens = required in an SCP; and catch it before deployment with IaC scanning (Trivy's AWS-0028 in the intro).
  • Measure v1 use before switching: the CloudWatch metric MetadataNoToken counts v1 requests per instance, so you can find old SDKs and agents that would break.
  • Turn it off where unused: HttpEndpoint=disabled for instances that need no metadata at all.

Pitfalls

  • Requiring v2 on instances but not in launch templates: the next auto-scaling event brings v1 back.
  • Raising the hop limit to 2 cluster-wide "because a pod needed it", which gives every pod the node role. Use workload identity for pods instead.
  • Assuming header requirements make GCP or Azure immune: SSRF that can set headers, or code execution, still reaches their metadata services. Allow-lists and egress control in the application remain necessary (SSRF fixes).

Practice

1. Add a client "SSRF through a PDF renderer that follows redirects" with can_put=False. What does each setting give?

Same as the URL-only SSRF: credentials with v1 allowed, blocked with v2 required. Redirect following changes where the GET goes, not its method or headers.

2. Why is the X-Forwarded-For check on the token request useful even though the proxy can send PUT with headers?

Reverse proxies and load balancers add X-Forwarded-For to forwarded requests; refusing token requests that carry it blocks the case where a misconfigured proxy on the instance forwards an outside request to IMDS.

3. Your EKS nodes have hop limit 2 because the CNI plugin "needs it". What do you check, and what is the alternative?

Check whether the component runs with hostNetwork: true (then hop limit 1 suffices, as in Workload Identity); give pods that need AWS access their own identities (IRSA or EKS Pod Identity) and set the hop limit to 1 so pods can't use the node role.

Test yourself

Which kind of SSRF does IMDSv2 stop that IMDSv1 doesn't?

  1. Code execution on the instance
  2. A URL-only SSRF that can make the server send GET requests
  3. Nothing
  4. Attacks on S3

What does a hop limit of 1 prevent?

  1. Any use of IMDS
  2. The token response reaching a container behind a network bridge (one more hop)
  3. Use of IMDSv1
  4. DNS lookups

In the model, which client gets credentials in all three settings?

  1. URL-only SSRF
  2. Open reverse proxy
  3. Code execution on the instance
  4. Bridged container

Which CloudWatch metric helps find instances still using IMDSv1 before you require v2?

  1. CPUUtilization
  2. MetadataNoToken
  3. StatusCheckFailed
  4. NetworkIn