URL check blocks "localhost". Why can SSRF still hit cloud metadata?
Question
A link-preview endpoint fetches user-supplied webhook URLs. Its starter guard only checks url.startswith("https://") and host != "localhost". During testing, requests still reach 169.254.169.254 (cloud metadata), ::ffff:127.0.0.1 (IPv4-mapped IPv6), an HTTP 302 redirect to 10.0.0.5, and a DNS rebinding host.
- Why do string checks on the URL and hostname fail here?
- Write
validate_target(url, resolve)withurllib.parseandipaddressso onlyhttpsURLs resolving strictly to public global IPs pass. - How do you stop
302redirects and DNS rebinding from bypassing the check?
from urllib.parse import urlparse def check_url(url): if not url.startswith("https://"): return False host = (urlparse(url).hostname or "").lower() return host != "" and host != "localhost"
Show hints (3)
- "RESOLVE THEN CLASSIFY"
Parse the URL, resolve the hostname to every IP address, and classify each IP with
ipaddress.ip_addressinstead of matching host strings. - "UNWRAP MAPPED IPV6"
An IPv4-mapped IPv6 address like
::ffff:127.0.0.1wraps an IPv4 address. Unwrapip.ipv4_mappedfirst, then requireis_globaland reject multicast and reserved ranges. - "REDIRECTS AND REBINDING"
Connect straight to the checked IP so DNS cannot change between check and connect. Disable automatic redirects or re-run the same check on every hop.
Show checked explanation
String checks miss IP literals (169.254.169.254, 127.0.0.1), IPv4-mapped IPv6 (::ffff:127.0.0.1), and attacker domains that resolve to internal IPs. Parse with urllib.parse, resolve every IP, unwrap ipv4_mapped, and allow only global non-multicast, non-reserved IPs. Connect to the checked IP, disable automatic redirects, and enforce IMDSv2 plus egress firewalls.
import ipaddress from urllib.parse import urlparse def validate_target(url, resolve): u = urlparse(url) if u.scheme != "https" or not u.hostname or u.username or u.password: return None ips = resolve(u.hostname) or [] for raw in ips: ip = ipaddress.ip_address(raw) ip = getattr(ip, "ipv4_mapped", None) or ip if not ip.is_global or ip.is_multicast or ip.is_reserved: return None return ips[0] if ips else None dns = {"ok.example": ["93.184.216.34"], "meta.example": ["169.254.169.254"], "v6.example": ["::ffff:127.0.0.1"], "lan.example": ["10.0.0.5"]} for host in dns: print(host, "->", validate_target(f"https://{host}/hook", dns.get))
ok.example -> 93.184.216.34 meta.example -> None v6.example -> None lan.example -> None
Author-checked on CPython 3.12.10 against synthetic DNS tables, edge-case IPv4/IPv6 ranges, DNS-rebinding mocks, and a loopback 127.0.0.1 HTTP 302 test server; official OWASP, Python ipaddress, and RFC links checked. Checked by an editor other than the author.
Walkthrough
Hostname string checks fail because many different URLs and DNS records point to internal addresses. check_url accepts https://169.254.169.254/, https://127.0.0.1/, https://[::ffff:127.0.0.1]/, and any domain whose A record points to 10.0.0.5. Rejecting u.username and u.password also stops parser-confusion URLs like https://[email protected]/.
| target | starter check_url | validate_target |
|---|---|---|
ok.example (93.184.216.34) | True | 93.184.216.34 |
meta.example (169.254.169.254) | True (SSRF leak) | None |
v6.example (::ffff:127.0.0.1) | True (SSRF leak) | None |
lan.example (10.0.0.5) | True (SSRF leak) | None |
Classify every resolved IP, not the hostname string. Unwrap ip.ipv4_mapped first so ::ffff:127.0.0.1 and ::ffff:169.254.169.254 are evaluated as IPv4. In Python 3.12, ip.is_global rejects loopback, private RFC 1918, link-local (169.254.169.254), CGNAT (100.64.0.0/10), and unspecified (0.0.0.0, ::) addresses. Two ranges still report is_global == True: multicast (224.0.0.1, ff02::1) and NAT64 (64:ff9b::/96), which is why we also reject ip.is_multicast and ip.is_reserved. Reject the whole request if any returned A or AAAA record fails.
Close the redirect and DNS rebinding gaps. If your HTTP client automatically follows 302 Location: http://169.254.169.254/, the first check passes on ok.example while the second hop hits metadata. Disable auto-redirects or re-run validate_target on every hop. For DNS rebinding, an attacker's resolver returns 93.184.216.34 on the check lookup and 169.254.169.254 milliseconds later when the HTTP client resolves again. Pin the connection to the checked IP returned by validate_target while sending the original hostname in the Host header and TLS SNI.
Layer infrastructure controls. Require IMDSv2 on cloud instances so simple GET requests without a session token fail. Route outbound webhook fetches through a dedicated egress proxy or firewall that blocks RFC 1918, loopback, and 169.254.169.254 at the network layer.
Common mistakes
- Using a string denylist like
host != "localhost". Attackers bypass it with127.0.0.1,::1,::ffff:127.0.0.1, or their own DNSArecord. - Checking
not ip.is_privateinstead ofip.is_global. In Python 3.12, CGNAT100.64.0.1hasis_private == False, and multicast224.0.0.1hasis_global == True. - Validating DNS once and then passing the raw URL string to an HTTP client. Automatic
302redirects and DNS rebinding still hit internal IPs. - Checking only the first resolved IP when DNS returns both a public address and an internal address like
10.0.0.5.
Follow-up questions
- "If you pin the socket connection to the checked IP, how does TLS certificate matching still work?" Open the TCP socket to the validated IP, then wrap it with
server_hostname=u.hostnameso TLS sends the real SNI and checks the certificate against the domain name. PassHost: <hostname>in the HTTP request too. - "Why does IMDSv2 help against SSRF to 169.254.169.254?" IMDSv2 requires a
PUTrequest with a customX-aws-ec2-metadata-token-ttl-secondsheader to mint a short-lived token, and defaults to an IP hop limit of 1. Most SSRF bugs only issueGETrequests without custom headers. - "What if your webhook feature only talks to three known partners?" Skip open URL fetching altogether. Maintain a strict allowlist of partner origins or fixed base URLs and allow user input only for validated path parameters.
What a strong answer covers
Replaces URL string denylists with parsed scheme checks, full DNS resolution, IPv4-mapped IPv6 unwrapping, and strict is_global plus non-multicast/non-reserved filtering. Connects to the checked IP, blocks unvalidated redirects, and layers IMDSv2 and egress firewalls.
Open in interactive practice deck →