SSRF is usually explained as "the server fetches a URL the attacker chose". That description undersells it. In a cloud environment, the interesting question is not what can the attacker read from the internet, but what can the server reach that the attacker never could.
This post is about one specific target: the instance metadata service.
Context
Every major cloud exposes a link-local HTTP endpoint inside each virtual machine, usually 169.254.169.254. It tells the instance about itself, and, more importantly, it hands out temporary credentials for the role attached to the machine.
On AWS, for example, a plain GET returns the role name and then a JSON document with an access key, a secret key and a session token.
Now combine that with any feature that fetches a user-supplied URL: webhooks, "import from URL", image proxies, PDF renderers, link previews. If the application does not restrict the destination, the attacker simply asks the application to fetch the metadata endpoint and return the response.
The attacker never touches your network. The application does it on their behalf, from a network position that the metadata service trusts completely.
The 2019 Capital One incident is the example everyone cites. An SSRF in a misconfigured web application firewall was used to retrieve role credentials from the metadata service.
What IMDSv2 changes
The original service (IMDSv1) answered any simple GET. That is exactly the primitive a typical SSRF gives you.
IMDSv2 turns it into a two-step, session-oriented exchange:
- A
PUT request to /latest/api/token with a TTL header returns a session token.
- Every metadata request must then carry that token in a header.
csharp
using var http = new HttpClient { BaseAddress = new Uri("http://169.254.169.254") };
var tokenRequest = new HttpRequestMessage(HttpMethod.Put, "/latest/api/token");
tokenRequest.Headers.Add("X-aws-ec2-metadata-token-ttl-seconds", "60");
var token = await (await http.SendAsync(tokenRequest)).Content.ReadAsStringAsync();
var roleRequest = new HttpRequestMessage(HttpMethod.Get, "/latest/meta-data/iam/security-credentials/");
roleRequest.Headers.Add("X-aws-ec2-metadata-token", token);
var role = await (await http.SendAsync(roleRequest)).Content.ReadAsStringAsync();
Most SSRF bugs cannot do this. They tend to be GET-only, they cannot set arbitrary request headers, and they certainly cannot send a PUT first and carry its result into a second request.
There is one more detail that gets less attention.
The hop limit
The response to the token request is sent with an IP TTL of 1 by default. That means the packet can travel exactly one network hop and is then dropped.
For a process running directly on the instance, that is fine. The response arrives.
For a container with its own network namespace behind a bridge, there is an extra hop. The token response never reaches the container.
This is a deliberate protection. It means that a compromised or SSRF-able workload inside a container cannot obtain a token, even though it shares the host.
And this is also where well-intentioned changes cause damage. When a platform team finds that pods cannot reach the metadata service, the usual fix found in forums is to raise the hop limit to 2. It works. It also hands every pod on that node the node's IAM role.
bash
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1
--http-tokens required disables IMDSv1 entirely. Keep the hop limit at 1 and give pods their own identity (IAM roles for service accounts, or the equivalent for your platform) instead of letting them borrow the node's.
Other clouds use the same idea with different mechanics. Azure requires a Metadata: true header and rejects requests that carry X-Forwarded-For. Google requires Metadata-Flavor: Google. In all three cases, the requirement for a custom header is what defeats the simplest SSRF.
Fixing the application too
IMDSv2 raises the bar, but it is not a fix for the SSRF itself. The application should refuse to connect to internal addresses regardless of what is behind them.
The common mistake is to validate the URL string and then let the HTTP client resolve it again. Blocklisting 169.254.169.254 as text misses decimal, octal and hex notations, IPv6-mapped addresses, redirects, and DNS names that resolve to internal addresses.
The reliable approach is to validate the address that will actually be used to connect:
csharp
var handler = new SocketsHttpHandler
{
ConnectCallback = async (context, ct) =>
{
var addresses = await Dns.GetHostAddressesAsync(context.DnsEndPoint.Host, ct);
var allowed = addresses.Where(a => !IsInternal(a)).ToArray();
if (allowed.Length == 0)
throw new HttpRequestException("Destination is not allowed.");
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
await socket.ConnectAsync(allowed, context.DnsEndPoint.Port, ct);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
};
IsInternal should cover loopback, link-local, private ranges, unique-local IPv6 and the IPv4-mapped forms of all of those.
Because the check happens inside the connection callback, it runs for every new connection, including the ones triggered by redirects, and the address that was checked is the address that is used. That closes the DNS rebinding gap.
Detecting attempts
Prevention will eventually have gaps, so it is worth knowing what a successful attempt looks like from the outside.
- The credentials are used from somewhere they should not be. Temporary credentials issued to an instance role are meant to be used from that instance. A call made with them from a different network is the clearest signal there is. AWS GuardDuty has a dedicated finding for it,
InstanceCredentialExfiltration, which fires when credentials created for an EC2 instance are used from an address outside AWS or from another account.
- Your own egress logs. An application that fetches user-supplied URLs should log the resolved destination of every request. A burst of requests to
169.254.169.254, to private ranges, or to unusual ports is an attempt, whether or not it worked.
- Metadata access from processes that never needed it. On the host, a flow log or a firewall counter on the metadata address tells you who is asking.
None of this needs a new product to start with. A single log line with the resolved IP and the outcome, per outbound fetch, is already enough to build an alert.
The hop limit story changes with the platform, so check what your workloads actually use.
On ECS, tasks get their credentials from a separate local endpoint, advertised through an environment variable, and not from the instance metadata service. On EKS, IAM roles for service accounts and Pod Identity hand each pod its own short-lived credentials, which is why the node's role never has to be reachable from a pod at all.
The practical consequence: when you move a workload to per-pod identity, block the metadata address for pods as well, with a network policy or a host firewall rule. The identity mechanism removes the need for access, and the block makes sure that a forgotten fallback does not quietly restore it.
Testing your fix
A defense that has never been attacked is a theory. Before you close the ticket:
- Point the vulnerable feature at
http://169.254.169.254/ and confirm it is refused.
- Try the usual disguises:
http://2852039166/ (the address as a single decimal number), http://0xA9FEA9FE/, http://[::ffff:169.254.169.254]/, and a domain you control that resolves to 169.254.169.254.
- Try a redirect: a public URL that answers
302 with the metadata address in Location.
- Try DNS rebinding: a name that resolves to a public address on the first lookup and to an internal one on the second.
If the connection-time check described above is in place, all four fail for the same reason, and that is exactly what you want to see.
Conclusion
The easy takeaway is "enable IMDSv2". That is necessary, but it is the weakest of the three layers.
The better way to think about it is that credentials reachable from the application's network position are part of the application's attack surface. IMDSv2 and the hop limit make them harder to reach. Connect-time address validation makes the application refuse the request in the first place. And a least-privilege role makes the damage small when both of those fail.
None of them is enough on its own. Together they turn a critical finding into a boring one.
References