# 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) ([[raw/github.com/traewelling-ssrf-via-outgoing-webhook-url-15834|Traewelling]]). Validation that returns a verdict string rather than a pinned IP (mcp-atlassian) or a pinned IP callers discard (AVideo) is not pinning ([[raw/xalgorix.com/a-passed-check-is-not-proof-the-ssrf-filter-that-resolves-dns-twice-15832|xalgorix]]). 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 ([[raw/xalgorix.com/a-passed-check-is-not-proof-the-ssrf-filter-that-resolves-dns-twice-15832|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. ## Related - [[Server-Side Request Forgery]] - [[IMDSv2]] - [[Cloud Metadata Service Exploitation]] - [[Capital One Breach]] - [[DNS Rebinding]] - [[IP Address Encoding Bypasses]] - [[URL Parser Differentials]] - [[SSRF in Kubernetes and Containers]] - [[Webhook SSRF]] - [[SSRF in AI Agents and LLM Tools]] - [[Out-of-Band Detection]] ## Sources - [[raw/blog.includesecurity.com/mitigating-ssrf-in-2023-30|Mitigating SSRF in 2023 - Include Security]] - [[raw/cheatsheetseries.owasp.org/server-side-request-forgery-prevention-owasp-cheat-sheet-series-107|Server-Side Request Forgery Prevention Cheat Sheet]] - [[raw/agentoffense.com/ssrf-cloud-metadata-attacks-url-fetcher-to-iam-credentials-15332|SSRF Cloud Metadata Attacks: URL Fetcher to IAM Credentials]] - [[raw/archy.net/auditing-and-mitigating-axios-ssrf-in-kubernetes-cve-2025-27152-3289|CVE-2025-27152: Auditing and Mitigating Axios SSRF in Kubernetes]] - [[raw/github.com/craft-cms-cloud-metadata-ssrf-protection-bypass-via-ipv6-resolution-4786|Cloud Metadata SSRF Protection Bypass via IPv6 Resolution]] - [[raw/wiz.io/imds-abused-hunting-rare-behaviors-to-uncover-exploits-2259|IMDS Abused: Hunting Rare Behaviors to Uncover Exploits]] - [[raw/xalgorix.com/a-passed-check-is-not-proof-the-ssrf-filter-that-resolves-dns-twice-15832|A passed check is not proof: the SSRF filter that resolves DNS twice]] - [[raw/github.com/traewelling-ssrf-via-outgoing-webhook-url-15834|Traewelling SSRF via outgoing webhook URL]]