download

URL check blocks "localhost". Why can SSRF still hit cloud metadata?

Security~10 minReviewed 3 Dec 2026Free · No sign-in

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.

  1. Why do string checks on the URL and hostname fail here?
  2. Write validate_target(url, resolve) with urllib.parse and ipaddress so only https URLs resolving strictly to public global IPs pass.
  3. How do you stop 302 redirects and DNS rebinding from bypassing the check?
"CODE · PYTHON"
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)
  1. "RESOLVE THEN CLASSIFY"

    Parse the URL, resolve the hostname to every IP address, and classify each IP with ipaddress.ip_address instead of matching host strings.

  2. "UNWRAP MAPPED IPV6"

    An IPv4-mapped IPv6 address like ::ffff:127.0.0.1 wraps an IPv4 address. Unwrap ip.ipv4_mapped first, then require is_global and reject multicast and reserved ranges.

  3. "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.

"SOLUTION · PYTHON"
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))
"OUTPUT"
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]/.

targetstarter check_urlvalidate_target
ok.example (93.184.216.34)True93.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 with 127.0.0.1, ::1, ::ffff:127.0.0.1, or their own DNS A record.
  • Checking not ip.is_private instead of ip.is_global. In Python 3.12, CGNAT 100.64.0.1 has is_private == False, and multicast 224.0.0.1 has is_global == True.
  • Validating DNS once and then passing the raw URL string to an HTTP client. Automatic 302 redirects 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.hostname so TLS sends the real SNI and checks the certificate against the domain name. Pass Host: <hostname> in the HTTP request too.
  • "Why does IMDSv2 help against SSRF to 169.254.169.254?" IMDSv2 requires a PUT request with a custom X-aws-ec2-metadata-token-ttl-seconds header to mint a short-lived token, and defaults to an IP hop limit of 1. Most SSRF bugs only issue GET requests 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 →

Original OfferVibe question. OWASP SSRF Prevention Cheat Sheet · OWASP API7:2023 SSRF · Python ipaddress.is_global · Python ipv4_mapped · RFC 6890.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.