SSRF to Cloud Metadata: Exploiting URL Parsers and Hardening Egress
A practical look at server-side request forgery against cloud instance metadata services: parser differentials, redirect and DNS-rebinding filter bypasses, IMDSv2 token flow, and layered egress hardening.
Introduction
A server-side request forgery (SSRF) flaw lets an attacker make your server issue an HTTP request to a destination of their choosing. On a developer laptop that is a nuisance. Inside a cloud virtual machine it is frequently a credential-theft primitive, because every major provider runs an instance metadata service (IMDS) on a link-local address that hands out temporary role credentials, user data scripts, and instance identity documents to anything that can reach it. There is no password: being on the instance is the authentication.
The interesting engineering question is not “what is SSRF” but “why do our filters keep losing”. The answer is almost always a parser differential — the validator and the HTTP client disagree about what a URL means — combined with the fact that most HTTP clients happily follow redirects and re-resolve DNS. This article walks through the mechanics, demonstrates bypass classes in a reproducible local lab, and then builds a defence that does not rely on string matching.
Assumptions. Examples use AWS terminology and the 169.254.169.254 endpoint; the concepts apply to other providers with different addresses and required headers (Google Cloud requires Metadata-Flavor: Google, Azure requires Metadata: true, Alibaba Cloud uses 100.100.100.200, DigitalOcean serves /metadata/v1/). Client-library behaviour varies by version and language — always verify against your own stack rather than trusting a payload list.
Core Concepts
What the metadata service actually is
169.254.169.254 is not a magic address; it is an IPv4 link-local address from the RFC 3927 range (169.254.0.0/16), reachable over an internal path that never leaves the host or its hypervisor. That has three consequences worth internalising:
- It is reachable from the instance even when the instance has no internet egress at all, so “we have no outbound access” is not a mitigation.
- Traffic to it typically does not traverse the VPC network, so VPC Flow Logs often will not show it. Host-level telemetry matters more.
- Because it is link-local, requests to it are not subject to ordinary internet NAT or egress filtering unless you explicitly write such a rule.
IMDSv1 versus IMDSv2
IMDSv1 is a plain GET. Anything that can issue an HTTP request can read credentials:
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/my-role-name
IMDSv2 adds a session-token handshake. The client must first PUT to /latest/api/token with a TTL header, then send the returned token on subsequent GETs. The two headers are different: X-aws-ec2-metadata-token-ttl-seconds on the PUT, and X-aws-ec2-metadata-token on the GET.
# Step 1: request a session token (PUT, not GET)
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
-H 'X-aws-ec2-metadata-token-ttl-seconds: 21600')
# Step 2: use the token for every metadata read
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/iam/security-credentials/
This defeats a large class of SSRF bugs because many SSRF primitives are GET-only and cannot set custom headers. It does not defeat SSRF where the attacker controls the HTTP method, the headers, or where the vulnerable code fetches an attacker-specified URL with a generic client wrapper. Treat IMDSv2 as a strong speed bump, not a boundary.
Why URL parsing is the weak point
A typical filter looks like this: parse the URL or regex it, check the host against an allowlist or blocklist, then hand the original string to an HTTP client. The bug is that the check operates on one interpretation and the client operates on another. Common divergences:
- Alternative IP encodings.
169.254.169.254has well-known decimal (2852039166), octal (0251.0376.0251.0376) and hexadecimal (0xA9.0xFE.0xA9.0xFE) forms. Some resolvers accept them; blocklists keyed on the dotted-quad string do not. - IPv4-mapped IPv6.
http://[::ffff:169.254.169.254]/is routed to the same place but is not equal to the IPv4 literal as a string. - Userinfo confusion.
http://api.example.com@169.254.169.254/has host169.254.169.254; naive parsers that split on@or use substring checks see the allowlisted name. - Trailing dots and case.
169.254.169.254.andAPI.EXAMPLE.COMmay bypass exact-match checks. - DNS names that resolve to link-local.
169.254.169.254.nip.io(and similar wildcard-DNS services) resolve to the embedded IP while looking like a hostname. - Backslash and authority confusion. For special schemes, many clients normalise
\to/before authority parsing, sohttp://host\@evil/can be interpreted as hosthostwith path/@evil/rather than as userinfohost\atevil. Validators that split on@or\before normalisation can therefore disagree with the client.
There is no universal payload here. The productive approach is to enumerate the actual normalisation your client performs.
Redirects and DNS rebinding
Both are time-of-check/time-of-use problems. A redirect lets the first hop pass validation and the second hop go somewhere else. A rebinding attack uses an attacker-controlled authoritative DNS server with a very low TTL: the first lookup returns a harmless public IP (validation passes), and the second lookup, milliseconds later when the client actually connects, returns 169.254.169.254.
Practical Walkthrough
Lab setup
You can reproduce link-local reachability locally without a cloud account by assigning the address to loopback inside a disposable VM or container:
# Add the metadata address to loopback so a local mock can bind it
sudo ip addr add 169.254.169.254/32 dev lo
# Serve a fake metadata tree on port 80
sudo python3 -m http.server 80 --directory /tmp/fake-imds
Populate /tmp/fake-imds/latest/meta-data/iam/security-credentials/ with dummy files. This gives you a safe target that behaves like the real thing from the perspective of your application’s network stack. It models host-network reachability, not the full cloud link-local path: in particular it does not reproduce the TTL/hop-limit decrement that separates host networking from bridged or NAT’d container networking, which matters in the IMDSv2 discussion below.
The vulnerable service
from flask import Flask, request
import requests
app = Flask(__name__)
ALLOWED = ('api.example.com', 'images.example.com')
@app.route('/fetch')
def fetch():
url = request.args.get('url', '')
# Naive substring allowlist - the classic mistake
if not any(h in url for h in ALLOWED):
return 'blocked', 400
# allow_redirects=True is the default and re-resolves DNS
r = requests.get(url, timeout=5)
return r.text[:2000]
The check is a substring match against the raw string, and the client follows redirects. Both are exploitable independently.
Step 1: parser differentials
The sample app above uses a substring allowlist, not a blocklist. That matters for interpreting the payload list: among the forms below, only the userinfo payload contains an allowlisted string (api.example.com) and therefore passes this exact sample. The others are client-normalisation probes for blocklist-style filters or for a different fetcher. Run each one against the client you actually use, print the parsed host and the resolved IP, and record which forms were normalised before the filter ran and which were normalised after.
http://169.254.169.254/latest/meta-data/
http://2852039166/latest/meta-data/ # decimal form
http://0251.0376.0251.0376/latest/meta-data/ # octal form
http://0xA9.0xFE.0xA9.0xFE/latest/meta-data/ # hex form
http://[::ffff:169.254.169.254]/latest/meta-data/ # IPv4-mapped IPv6
http://169.254.169.254./latest/meta-data/ # trailing dot
http://api.example.com@169.254.169.254/latest/... # userinfo
http://169.254.169.254.nip.io/latest/meta-data/ # wildcard DNS
| Payload | What it probes | Passes the sample allowlist? |
|---|---|---|
http://169.254.169.254/... | Direct link-local literal | No |
http://2852039166/... | Decimal IPv4 | No |
http://0251.0376.0251.0376/... | Octal IPv4 | No |
http://0xA9.0xFE.0xA9.0xFE/... | Hexadecimal IPv4 | No |
http://[::ffff:169.254.169.254]/... | IPv4-mapped IPv6 | No |
http://169.254.169.254./... | Trailing-dot host | No |
http://api.example.com@169.254.169.254/... | Userinfo confusion | Yes |
http://169.254.169.254.nip.io/... | Wildcard DNS | No |
In Python, socket.gethostbyname on the host portion is informative; for a definitive answer, enable urllib3 debug logging or capture packets. Do not assume that a payload which works in one language or library version will work in another.
Step 2: redirect bypass
Stand up a redirector on any host your filter trusts (in the lab, add an /etc/hosts entry mapping api.example.com to 127.0.0.1, and run the redirector on port 80 or use http://api.example.com:5000/go in the request):
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/go')
def go():
return redirect('http://169.254.169.254/latest/meta-data/', code=302)
Now url=http://api.example.com/go passes the allowlist, and the client follows the 302 to link-local. This works because validation happened once, at the string level, and the redirect target was never validated. A robust fetcher must re-run the full validation on every Location, including protocol-relative Location values. If your HTTP stack or any front-end also follows Refresh headers or HTML meta refresh, those need the same treatment.
Step 3: IMDSv2 considerations
If the instance enforces IMDSv2, the previous payloads return 401 Unauthorized. To continue in a lab you would need a primitive that performs PUT with X-aws-ec2-metadata-token-ttl-seconds and then replays the returned token with X-aws-ec2-metadata-token. Realistically, this requires either a fully generic request proxy in the vulnerable code, or a token that was already minted and cached somewhere the attacker can influence. Note that the token endpoint returns a token bound to the TTL you request, and the default http-put-response-hop-limit on the instance is 1 — which is why containers on the same instance often need the hop limit raised, and why raising it widens the blast radius.
Step 4: DNS rebinding (concept)
Rebinding needs an authoritative DNS zone you control. The pattern is: serve an A record with TTL 0 (or 1) that alternates between a benign IP and 169.254.169.254, and have the target application resolve the name twice — once for the filter, once for the connection. Because the technique depends on resolver caching behaviour, negative caching, and the client’s connection pooling, results vary widely between environments. The correct defensive conclusion is not “rebinding always works” but “any filter that resolves and then discards the result is bypassable by design”.
Security Implications
When SSRF succeeds against IMDSv1, the typical chain is:
SSRF -> /latest/meta-data/iam/security-credentials/
-> role name
-> credential JSON (AccessKeyId, SecretAccessKey, Token, Expiration)
-> sts:GetCallerIdentity / S3 / DynamoDB / Secrets Manager as that role
Secondary targets are equally valuable: user-data frequently contains bootstrap secrets or repository tokens; instance identity documents can be used to enrol the instance elsewhere; and SSRF to internal-only HTTP services (dashboards, admin APIs, Kubernetes API servers, Elasticsearch) is often easier than reaching the internet.
Detection signals worth instrumenting:
- Egress DNS queries for wildcard-DNS domains such as
nip.io,sslip.io,xip.io, or unusually short TTLs from application workloads. - Host/agent telemetry for processes opening connections to
169.254.169.254orfd00:ec2::254that are not the instance’s own bootstrap tooling. - CloudTrail events for credential use from unexpected source IPs or ASNs shortly after a suspicious inbound request to a public-facing app.
- Managed threat-detection services that include findings for instance-credential exfiltration and metadata DNS rebinding; these are useful but should not be your only control.
Defensive Considerations
1. Enforce IMDSv2 at the instance level
Require tokens and keep the hop limit low:
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1 \
--http-endpoint enabled
Apply this through launch templates or account/region-level metadata defaults so new instances inherit it, and verify enforcement fleet-wide with a compliance check such as the AWS Config ec2-imdsv2-check managed rule (and the related Security Hub control). Existing instances and older AMIs may still have IMDSv1 available by default; do not assume that changing a launch template remediates the fleet.
Note the hop-limit trade-off precisely: host-network pods generally work with hop limit 1 because they share the host network namespace, while bridged or NAT’d pods typically need hop limit 2. Raise the limit only where genuinely needed, and document which workloads required it.
2. Fix the fetcher, not the regex
The only reliable client-side fix is to make validation and connection agree:
- Parse the URL once, reject non-
http/httpsschemes, reject any userinfo component, and reject non-default ports unless they are on an explicit allowlist. Reject non-ASCII/IDNA-confusable hostnames unless they are explicitly allowlisted. - Require an exact-match hostname allowlist — no substrings, no suffixes. Prefer an allowlist-first model: resolve the host and require every returned address to be public or on an explicit egress allowlist.
- Resolve DNS yourself, canonicalise IPv4-mapped and IPv4-compatible IPv6 forms, and reject private, loopback, link-local, reserved, multicast and unspecified addresses using a proper IP library.
- Connect to the resolved IP, not the hostname, so a second lookup cannot return something different. Preserve the original
Hostheader and SNI. - Disable automatic redirects; handle each hop manually and re-run steps 1–4 on every
Location, including protocol-relative values.
import ipaddress, socket
def _canonical_ip(value):
addr = ipaddress.ip_address(value.split('%', 1)[0])
if isinstance(addr, ipaddress.IPv6Address):
if addr.ipv4_mapped is not None:
return addr.ipv4_mapped
# IPv4-compatible ::/96 forms (excluding :: and ::1)
if addr in ipaddress.IPv6Network('::/96') and not (
addr.is_unspecified or addr.is_loopback):
return ipaddress.IPv4Address(int(addr) & 0xFFFFFFFF)
return addr
def assert_safe_host(host):
infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
for info in infos:
addr = _canonical_ip(info[4][0])
if (addr.is_private or addr.is_loopback or addr.is_link_local
or addr.is_reserved or addr.is_multicast or addr.is_unspecified):
raise ValueError(f'blocked destination {addr}')
The canonicalisation step matters: in Python, ::ffff:127.0.0.1 is not caught by is_loopback, and ::ffff:169.254.169.254 is not caught by is_link_local; whether is_private catches them depends on interpreter version. Normalise via .ipv4_mapped (and handle IPv4-compatible ::/96 forms) before classification. An allowlist-first check — every resolved address must be on an explicit public egress allowlist — is stronger than trying to enumerate every non-public range; is_global-style checks can serve as a secondary guard where your IP library exposes them.
Step 4 is the one most teams skip. requests does not expose easy IP pinning; you need a custom HTTPAdapter/urllib3 connection pool that preserves the original Host header and SNI, or an HTTP client with a fixed-resolver/IP-pinning option. curl --resolve is a CLI convenience, not a general application-stack solution.
3. Build a real egress boundary
Assume the application will be compromised and make the metadata path unreachable from workload users:
# Reject link-local metadata traffic from a dedicated service account
sudo iptables -A OUTPUT -m owner --uid-owner 1001 \
-d 169.254.169.254/32 -j REJECT
For the IPv6 metadata endpoint, add the equivalent ip6tables rule for fd00:ec2::254/128. On tighter platforms, run workloads through a forward proxy that terminates TLS, resolves DNS at the proxy, enforces an allowlist, and refuses cross-host redirects. If a forward proxy is the egress boundary, authenticate workloads to it (for example with mTLS or signed requests) and deny unauthenticated use; otherwise the proxy becomes a new SSRF pivot. Combine this with default-deny security groups, Kubernetes egress NetworkPolicy, and VPC endpoints so that legitimate cloud API calls never need general internet access.
4. Reduce the value of a successful SSRF
Least-privilege instance roles, permission boundaries, short session lifetimes, and moving secrets out of user-data all shrink the payoff. If the role can only read one bucket prefix, credential theft is an incident rather than a catastrophe.
5. Test your own filters
Maintain a regression suite of URL forms — decimal, hex, octal, IPv4-mapped, userinfo, trailing dot, wildcard DNS, redirect chains — and run it against every fetcher in your codebase on each dependency upgrade. Parser behaviour changes between library versions; the bypass that failed last quarter may succeed this quarter.
Conclusion
SSRF against cloud metadata is a parsing problem wearing a network costume. The exploitation surface is not a single magic payload but the gap between how a validator reads a URL and how an HTTP client acts on it — amplified by redirects and by DNS being resolved twice. IMDSv2 raises the cost of exploitation considerably by forcing a PUT handshake, but it is a mitigation rather than a boundary, and any fetcher that accepts arbitrary methods and headers negates it.
The durable defences are structural: pin DNS resolution to the IP you validated, forbid automatic redirects, put a default-deny egress boundary in front of workloads, and make the metadata endpoint unreachable from application users. Then shrink what a stolen credential is worth. Assume the filter will eventually be bypassed and design so that the bypass is loud and cheap to contain.