SSRF Prevention

Layered SSRF defense: prefer allowlists, resolve-then-pin the connection to a validated IP, push egress through a single proxy, and harden the metadata endpoint — because URL string-matching always loses.

Why string validation fails

A validator that inspects URL text never learns where the socket actually lands. Every blocklist is bypassed by IP encodings, parser differentials, redirects and DNS rebinding (see IP Address Encoding Bypasses, URL Parser Differentials, DNS Rebinding). Even a correct blocklist checked at validation time is a TOCTOU bug: an HTTP redirect, a rebinding DNS record, or a second unchecked resolution between check and connect defeats it. BASE_URL-prefix anchoring is broken by @host (userinfo) and # (fragment); hostname blocklists are broken by localtest.me-style domains that resolve to 127.0.0.1.

Allowlist vs blocklist (OWASP two cases)

  • Case 1 — fetcher only needs identified, trusted destinations: use an allowlist. Don’t accept a whole URL; take an IP or domain, strict-compare (case-sensitive) against the allowed set, then build the request yourself with a scheme, port and path the app fixes. If the host came from a user URL, do not carry its path/query across. Validate IP literals with a parser not fooled by hex/octal/dword/mixed encodings, checking both A and AAAA.
  • Case 2 — fetcher must reach arbitrary external hosts (webhooks): allowlists don’t apply, so blocklist is the best available but not a wall. Verify the resolved address is public (reject all RFC1918, loopback, 169.254.0.0/16 link-local, IPv6 ULA/link-local, and provider metadata IPs), resolve via a resolver that won’t answer internal names, and still pin the connection.

Resolve-then-pin (the core control)

Defeat TOCTOU by collapsing check and use:

  1. Resolve the hostname once (A + AAAA).
  2. Reject any private/loopback/link-local answer.
  3. Connect to that exact validated IP, preserving the original hostname only for the Host header / TLS SNI.
  4. Do not resolve a second time. Disable redirects, or re-run the whole validation on every hop.
  5. Validate every A/AAAA record (reject if any is blocked), and pin through a custom resolver/transport — swapping the IP into the URL breaks certificate verification. curl --resolve preview.example:443:203.0.113.10 https://preview.example/ is the reference behavior.
  6. Cover retries, pools and fallback connections: each re-resolve is a second lookup (OWASP).
  7. Don’t reuse validators across contexts: an OAuth redirect-URI rule permits loopback by design (RFC 8252) (Traewelling). Validation that returns a verdict string rather than a pinned IP (mcp-atlassian) or a pinned IP callers discard (AVideo) is not pinning (xalgorix).
  8. Validate names, not just literals, and the port too. rConfig’s DeviceIpIsValid rejected loopback IPs but let unresolved hostnames through, and a user-set device_port_override of 6379 aimed the fetch at Redis for RCE (CVE-2026-135696) (rConfig).
  9. Don’t ship permissive proxy defaults or leave side channels unauthenticated. Interstellar enabled wisp-js allow_loopback_ips and allow_private_ips at startup, and its wisp WebSocket skipped the Express password middleware. That gave unauthenticated TCP streams to loopback, internal hosts and metadata (CVE-2026-135161) (Interstellar). Every transport, including WebSocket upgrades, must pass the same auth and destination policy.

Remediation checklist from a P2 bug-bounty template: strict domain allowlist; reject loopback, private, link-local and reserved ranges; validate DNS resolution and re-validate after redirects (or disable them); restrict schemes; outbound firewall plus segmentation; don’t return raw internal responses; log and monitor unusual outbound requests (P2 SSRF).

Watch IPv6 pitfalls: gethostbyname() resolves only A records — an AAAA-only host returns the hostname string and slips a naive blocklist straight to the IMDS IPv6 endpoint ([fd00:ec2::254]). Validate IPv6 and compatibility protocols (DNS64, Teredo, 6to4) explicitly.

Library guidance

  • Anti-SSRF HTTP wrappers (Include Security SafeURL, Doyensec safeurl-go) hook the low-level client (getaddrinfo/connect, urllib3/pycurl) and validate the IP just before opening the socket — correct TOCTOU handling in one import. Cons: developers must remember to use them; many HTTP libraries per language slip through; out-of-process sinks (headless Chrome/PhantomJS PDF renderers, media converters) and transitive deps bypass them entirely. Enforce via SAST on checkin.
  • Upgrade clients that leak headers across redirects (axios < 1.8.2, CVE-2025-27152) and disable redirect-following by default in fetchers.

Egress proxy (preferred for mature orgs)

Route all outbound traffic through one CONNECT proxy that applies per-client host rules (Stripe Smokescreen: default-denies internal IPs, allow/block domains per client). Then firewall direct egress so the proxy can’t be bypassed. Gives application-layer configurability with network-layer exhaustiveness, plus centralized logging and a small, allowlistable egress IP set. Needs app HTTP CONNECT support and org buy-in to maintain.

Network segmentation & zero-trust

  • Firewall is a blunt instrument alone — it can’t stop SSRF to services on the app’s own localhost (Redis, admin panels), and large apps often legitimately call some internal service. Use it as one layer, not the layer.
  • Authenticate internal services and endpoints (zero-trust): the single most durable mitigation where an IP/port can’t be filtered. GCP/Azure gated metadata from day one; AWS retrofitted with IMDSv2.
  • Egress NetworkPolicies in Kubernetes (default-deny outbound, allow only DNS + required services) scope blast radius per pod. See SSRF in Kubernetes and Containers.

Harden the metadata endpoint

  • Require IMDSv2 (HttpTokens=required), disable IMDSv1, keep hop limit 1, or HttpEndpoint=disabled where unneeded. Enforce via Org policy/SCP; a launch-template default does not retrofit running instances. Details and limits: IMDSv2, Cloud Metadata Service Exploitation.
  • Limits of the backstops: IMDSv2 rejects a token PUT carrying X-Forwarded-For and defaults to hop limit 1, but protects one endpoint on one cloud; egress controls are often relaxed for exactly the service that fetches user URLs. They are defense in depth, not the fix (xalgorix).
  • Deny 169.254.0.0/16, fd00:ec2::254, loopback, Azure WireServer 168.63.129.16, Alibaba 100.100.100.200 at the network layer, not just in app code.
  • Replace broad instance roles with narrow workload identity (IRSA, GKE Workload Identity, Azure Workload Identity) so a stolen token’s reach is minimal.
  • A WAF rule is not the fix — in Capital One the WAF was the SSRF primitive (see Capital One Breach).

AI agent fetchers

Any agent URL tool is an SSRF primitive the model (or a prompt injection) can aim. Run fetch tools in a sandbox with no metadata service and no production credentials, enforce an egress allowlist, require approval for off-list hosts, and scan tool output for credential-shaped strings before it re-enters context. See SSRF in AI Agents and LLM Tools.

Detection

Blind SSRF is confirmed out-of-band (Burp Collaborator / interactsh) — see Out-of-Band Detection. Baseline normal metadata clients (AWS SDKs, nm-cloud-setup) and alert on rare processes hitting sensitive IMDS paths; authoritative DNS logs showing a public then a link-local answer for one name signal rebinding. Monitor allowlisted domains for drift into private ranges.

Sources