Preventing SSRF: Validating Resolved IPs, Pinning Connections, and Locking Down Cloud Metadata
Server-side request forgery turns your URL fetcher into an attacker's proxy. Learn why string filters fail and how to layer resolved-IP checks, connection pinning, IMDSv2 and egress rules.
Many applications fetch URLs on behalf of their users: link previews, webhook deliveries, "import from URL" buttons, PDF renderers, avatar uploads by address. Each of these features turns your server into a proxy that someone else gets to aim. Server-side request forgery (SSRF) is what happens when that aim lands somewhere you never meant to expose, such as an admin panel bound to localhost, an internal database dashboard, or the cloud metadata service that hands out credentials.
This guide explains why SSRF keeps slipping past input filters, then walks through a layered defense: decide which kind of fetch you are building, validate the resolved address instead of the string, pin the connection, turn off redirects, harden the metadata endpoint, and restrict egress at the network layer. It ends with a runnable Python validator and a checklist you can use in code review.
Why the server is a better attacker than the attacker
An outside user cannot reach 10.0.0.5 or 127.0.0.1 on your infrastructure. Your application server can. Internal services often trust traffic simply because it comes from inside the network, so they skip authentication or expose management functions that were never designed to face the internet. When the server makes a request to an address the user chose, the user borrows the server's network position and its implied trust.
There are two flavors to keep in mind. In regular SSRF the response comes back to the attacker, for example as the body of a link preview. In blind SSRF the server makes the request but returns nothing useful. Blind SSRF is harder to exploit, yet it can still trigger state changes on internal endpoints, so "we never show the response" is not a defense.
The most valuable target: cloud metadata
On AWS, GCP and Azure, a link-local address, 169.254.169.254, serves instance metadata. On AWS that includes temporary credentials for the IAM role attached to the instance. If an attacker can make your server issue a plain GET to that address and read the reply, they may walk away with keys that act as your workload. Container platforms add more endpoints in the same link-local block, such as the ECS task credential address 169.254.170.2.
Why string filters fail
The first instinct is to block the word localhost and the string 169.254.169.254. Attackers have many ways around that, and they all exploit the gap between the text you inspect and the address the HTTP client eventually connects to.
- Alternate IP notations: 2130706433 is the decimal form of 127.0.0.1, and octal or shortened forms are accepted by many resolvers.
- IPv6 wrappers: ::ffff:127.0.0.1 is an IPv4-mapped address, and 64:ff9b::a9fe:a9fe is the NAT64 encoding of the metadata IP.
- Attacker-owned DNS: a harmless-looking hostname that simply resolves to 127.0.0.1 or a private range.
- Parser confusion: userinfo before an @ sign, fragments after #, and backslashes are read differently by different URL libraries, so the validator and the client may disagree about the host.
- Redirects: the URL you approved returns a 302 pointing at an internal address, and the client follows it.
- DNS rebinding: the name resolves to a public IP when you check it and to an internal IP when the client connects a moment later.
The common thread is time and interpretation. Any check performed on a different representation, or at a different moment, than the actual connection can be bypassed. A sound defense makes the checked value and the connected value the same thing.
Step 1: decide which kind of fetch you are building
The OWASP SSRF Prevention Cheat Sheet splits the problem into two cases, and the right controls differ sharply between them.
- Known destinations: your app talks to a fixed set of partner APIs or internal services. Use a strict allowlist of hostnames or IPs, and do not accept full URLs from users at all. Let them pick an identifier, and build the URL yourself with a fixed scheme, port and path.
- Arbitrary destinations: webhooks, link previews and feed readers must reach any public host. An allowlist is impossible, so you rely on a blocklist of non-public address space enforced on resolved IPs, plus connection pinning, disabled redirects and network egress controls.
If you can redesign the feature into the first case, do it. An allowlist with no user-controlled path is far easier to reason about than any blocklist.
Step 2: validate the resolved address, not the hostname
For arbitrary destinations, the decision must be based on the IP addresses the hostname actually resolves to. Resolve the name, inspect every A and AAAA record, unwrap IPv4-mapped and NAT64 forms back to IPv4, and reject the request if any address is loopback, private, link-local, multicast or otherwise not globally routable. Checking every record matters because an attacker can publish one public and one private address and hope your client picks the second.
The function below does exactly that with Python's standard library. It is written for this article and tested on CPython 3; it is a starting point, not a drop-in library.
import ipaddress
import socket
from urllib.parse import urlsplit
ALLOWED_SCHEMES = {"http", "https"}
NAT64 = ipaddress.ip_network("64:ff9b::/96")
def normalize(ip):
"""Unwrap IPv6 forms that smuggle an IPv4 address."""
if ip.version == 6:
if ip.ipv4_mapped is not None:
return ip.ipv4_mapped
if ip in NAT64:
return ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
return ip
def check_outbound_url(url):
"""Return (host, port, pinned_ip) or raise ValueError."""
parts = urlsplit(url)
if parts.scheme not in ALLOWED_SCHEMES:
raise ValueError(f"scheme not allowed: {parts.scheme!r}")
if parts.username or parts.password:
raise ValueError("credentials in URL are not allowed")
host = parts.hostname
if not host:
raise ValueError("missing host")
port = parts.port or (443 if parts.scheme == "https" else 80)
infos = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)
addresses = {normalize(ipaddress.ip_address(info[4][0])) for info in infos}
for ip in addresses:
if not ip.is_global:
raise ValueError(f"{host} resolves to non-public address {ip}")
pinned = sorted(addresses, key=str)[0]
return host, port, str(pinned)
Worked example: how the validator treats common payloads
Running the function against typical bypass attempts shows why resolving first is effective. The string checks never see the internal address; the resolved check always does.
- http://169.254.169.254/latest/meta-data/ is blocked because the address is link-local.
- http://2130706433/admin is blocked because getaddrinfo turns the decimal form into 127.0.0.1, which is loopback.
- http://[::ffff:127.0.0.1]/ is blocked after the IPv4-mapped address is unwrapped to 127.0.0.1.
- http://[64:ff9b::a9fe:a9fe]/ is blocked after the NAT64 address is unwrapped to 169.254.169.254.
- http://user@internal. example/ is blocked because embedded credentials are refused outright.
- file:///etc/passwd is blocked by the scheme allowlist before any lookup happens.
- https://example. com/hook is allowed, and the function returns the public IP it decided to trust.
Step 3: pin the connection to the address you checked
Validation alone still leaves a gap. If the HTTP client performs its own DNS lookup after your check, a rebinding attacker can answer the second query with an internal IP. The fix is to connect to the exact IP your validator approved while keeping the original hostname for the Host header, TLS SNI and certificate verification. The validator above returns that pinned IP for this reason.
With curl, the --resolve option supplies the address for a host and port pair, so no second lookup occurs. Redirects are not followed unless you pass -L, and the --proto option restricts which schemes curl will use:
curl --proto '=https' --resolve hooks.example.com:443:203.0.113.10 \
https://hooks.example.com/deliverIn application code, look for the equivalent hook in your HTTP library: a custom resolver, a connect callback, or a transport that dials a fixed IP. Apply the same policy to retries and fallback connections, because a retry that re-resolves the name reopens the hole.
Step 4: disable redirects and restrict schemes
Most HTTP clients follow redirects by default. Turn that off for user-directed fetches. If the product genuinely needs redirects, follow them manually, one hop at a time, and run the full validate-and-pin routine on every new location. Also limit the scheme to http and https. Schemes such as file, gopher and dict have historically turned SSRF into local file reads or raw protocol injection against internal services. If the feature parses XML, disable external entities too, since XXE is another path to the same server-side requests.
Step 5: harden the metadata service
On AWS, require Instance Metadata Service version 2. IMDSv2 is session-oriented: a client must first send a PUT to /latest/api/token with an X-aws-ec2-metadata-token-ttl-seconds header (up to 21,600 seconds), then present the returned token in an X-aws-ec2-metadata-token header on each GET. When tokens are required, requests without a valid token receive a 401.
This helps against SSRF because most vulnerable features can only make simple GET requests and cannot set custom headers or choose the method. AWS also rejects token PUTs that carry an X-Forwarded-For header, which defeats many open reverse proxies, and the token response has an IP hop limit of 1 by default so it does not travel beyond the instance. Treat this as defense in depth: a bug that lets an attacker control the method and headers can still complete the handshake. Raise the hop limit only if containers on the host genuinely need it.
Step 6: restrict egress at the network layer
Application checks can have bugs; network policy is a second, independent wall. Run URL-fetching workers in their own subnet or container with egress rules that allow only the destinations they need. For arbitrary-destination features, send traffic through an egress proxy that refuses private and link-local ranges on its own. Block 169.254.169.254 (and fd00:ec2::254 for IPv6 on AWS) from any workload that does not need instance metadata.
Ranges to deny when you cannot allowlist
If you write your own deny-list instead of relying on a built-in check like is_global, normalize addresses first and cover at least these blocks:
- Loopback: 127.0.0.0/8 and ::1/128, plus the "this network" block 0.0.0.0/8
- Private IPv4: 192.168.0.0/16, then 172.16.0.0/12, then 10.0.0.0/8
- Link-local: 169.254.0.0/16 and fe80::/10
- IPv6 unique local: fc00::/7
- Multicast: 224.0.0.0/4 and ff00::/8
- Wrappers to unwrap before checking: ::ffff:0:0/96 (IPv4-mapped) and 64:ff9b::/96 (NAT64)
Common mistakes
- Validating with one URL parser and fetching with another, so they disagree about the host.
- Checking only the first DNS answer instead of every A and AAAA record.
- Resolving once for validation and letting the client resolve again for the connection.
- Leaving redirect following on, or re-validating only the first URL in a redirect chain.
- Assuming blind SSRF is harmless because responses are never shown to the user.
- Treating IMDSv2 as the whole fix instead of one layer among several.
Code review checklist
- Can this feature use a fixed allowlist instead of user-supplied URLs?
- Is the scheme limited to http or https, and are URL credentials rejected?
- Are all resolved addresses normalized and checked, not the hostname string?
- Does the client connect to the validated IP, with the hostname preserved for TLS?
- Are redirects disabled or re-validated hop by hop?
- Is IMDSv2 required and IMDSv1 disabled on every instance that runs this code?
- Does network egress policy block private and link-local ranges independently of the code?
No single control here is sufficient on its own. SSRF defense works when the checked address and the connected address are provably the same, and when the network would still refuse the request if the application logic slipped.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter