How-To Guide

How to Prevent SSRF in Server-Side Requests

Validate schemes, resolve DNS and check the IP against private ranges, control redirects hop by hop, and pin the connection to the validated address.

On this page

  1. Introduction
  2. The surfaces and the interior
  3. Validate scheme and address
  4. Redirects re-open the door
  5. DNS rebinding and connection pinning
  6. Egress control as the backstop
  7. Test the guard end to end
  8. Common pitfalls
  9. Conclusion

Introduction

Server-side request forgery turns the application’s own network privileges against it. The surfaces are ordinary features: webhook callbacks at user-supplied URLs, avatar imports by link, feed readers, PDF generators, payment integrations that call back wherever they are told. Each hands the server a URL to fetch, and if the server fetches without validation, the attacker supplies http://169.254.169.254/latest/meta-data/, the cloud metadata service that mints credentials, or http://internal-admin:8080/, a panel no external scanner could ever reach, and the server, holding the privileged position, obligingly fetches the interior and returns the response to the attacker. The defense is layered validation at the boundary where the URL becomes a connection: scheme and syntax, then the resolved IP against private and metadata ranges, then redirect handling that re-validates each hop, then connection pinning so the validation and the connection cannot diverge. This tutorial implements each layer, treats DNS rebinding as the attack that punishes sloppy layering, and closes with network-level egress control, the backstop that makes application bugs survivable.

The surfaces and the interior

The attack surface inventory comes first because defenses attach to surfaces. User-supplied destination URLs: webhooks, import-by-URL, avatar and image fetching, feed subscription. Partially user-controlled URLs: template URLs with an interpolated host, redirect targets the server follows, URLs from parsed user content, markdown link prefetching. Indirect control: a user-controlled DNS name that resolves wherever the attacker’s nameserver says. What the interior holds explains the severity: cloud metadata endpoints on 169.254.169.254 that hand out instance credentials and sometimes deployment secrets; internal services on private ranges that trust the network and skip authentication precisely because they are interior; administrative panels and databases with no external exposure at all. The attacker’s goal is usually credential theft or internal mapping, and the response body of the forged request, rendered back through the original feature, is the exfiltration channel, which is why defenses include response handling, not just connection filtering.

Validate scheme and address

The first validation layer runs before any network activity: parse the URL, reject anything that is not http or https, and reject credentials embedded in the URL, which have no legitimate use in a fetch surface and exfiltrate into logs. The second layer is the decisive one: resolve the hostname and validate the resulting IP, because the hostname is a claim and the IP is the fact.

import { isIP } from 'node:net';
import { lookup } from 'node:dns/promises';

export async function assertPublicHost(hostname: string): Promise<string> {
 const results = await lookup(hostname, { all: true });
 for (const { address, family } of results) {
  if (isPrivateAddress(address, family)) {
   throw new SSRFError(`refusing private address: ${address}`);
  }
 }
 return results[0].address;
}

function isPrivateAddress(addr: string, family: number): boolean {
 const ip = isIP(addr) === 6 ? normalizeV6(addr) : addr;
 return BLOCKED_RANGES.some(range => cidrContains(range, ip));
}

The blocked set must be complete, not aspirational: the RFC 1918 private ranges, loopback on both families, link-local 169.254.0.0/16 including the metadata address, unique-local IPv6 fc00::/7, IPv4-mapped IPv6 forms that smuggle v4 inside v6 strings, and the zero network. Half the blocklists in production miss exactly one of these, and the missed range is the attack.

Redirects re-open the door

The validation above approves a destination, and then the HTTP library, helpfully following redirects, fetches somewhere entirely different: the public URL answers 302 http://169.254.169.254/, and the chain silently reaches the interior. Automatic redirect following must be disabled at the fetch layer, and each hop re-validated with the same scheme-and-address pipeline, with a hop limit because redirect chains are also a cheap loop.

export async function safeFetch(rawUrl: string, maxHops = 3): Promise<Response> {
 let url = new URL(rawUrl);
 for (let hop = 0; hop <= maxHops; hop++) {
  assertScheme(url);
  const pinnedIp = await assertPublicHost(url.hostname);
  const res = await fetch(url, {
   redirect: 'manual',
   headers: { host: url.hostname },
  });
  if (res.status < 300 || res.status >= 400) return res;
  url = new URL(res.headers.get('location')!, url);
 }
 throw new SSRFError('too many redirects');
}

The same discipline applies to every indirection the fetch layer offers: HTTP auth challenges, connection upgrades, and any plugin or middleware that follows links. The mental model that keeps this layer honest is that validation is per connection, not per feature: every new TCP connection the request causes must pass the full pipeline, because attackers choose the hop that skips it.

DNS rebinding and connection pinning

DNS rebinding is the attack that punishes validate-then-fetch implemented naively. The attacker’s nameserver answers the first resolution with a public IP, validation passes, and by the moment the fetch connects, a second resolution returns 127.0.0.1 or a private address, and the connection uses it, because the fetch re-resolves the hostname. The defenses, in increasing strength. Short TTL hygiene does nothing, attacker-controlled DNS ignores courtesy. Re-validation after connect: compare the connected peer address against the validated one and abort on mismatch, which catches most rebinding. Connection pinning: resolve once, validate the address, and connect to that address explicitly, passing the hostname as Host and TLS SNI separately, so there is no second resolution to rebind.

const pinned = await assertPublicHost(url.hostname);
const agent = new http.Agent({ lookup: (_h, opts, cb) => cb(null, pinned, 4) });
await fetch(url, { agent });

The agent-level lookup override pins every connection the request makes to the validated address, including redirects followed on the same agent, closing the gap between validation and connection structurally rather than by vigilance.

Egress control as the backstop

Application validation fails eventually, a new fetch surface ships without the pipeline, a dependency follows redirects despite the setting, and the network layer is the backstop that makes those bugs survivable. The shape is deny-by-default egress: the application runtime egresses only through a proxy, and the proxy allows only the destinations the application legitimately needs, external APIs on named hosts, and blocks everything private, link-local, and metadata by construction. Cloud metadata defenses deserve their own line because they carry credentials: IMDSv2 on AWS requires a session token that a simple SSRF cannot mint, and equivalent hardened metadata modes exist elsewhere, which converts the most valuable SSRF target from a one-line fetch into a dead end. The egress layer also provides the detection signal: proxy logs show the application’s destination set, and an unexpected private-range attempt, blocked or not, is a page-worthy anomaly, because it means either an attack in progress or a bug that will become one.

Test the guard end to end

SSRF guards are only as good as their test suite, because the attack iterates around partial defenses. The canonical payload set: direct private addresses on every blocked range, IPv6 equivalents, IPv4-mapped IPv6, decimal and octal IP encodings that parsers accept, and the metadata address itself. The redirect payload: a public URL that 302s to each blocked target, with automatic redirects disabled and each hop asserted to reject. The rebinding payload: a DNS name backed by a test nameserver that alternates answers, asserting the connection either pins or aborts rather than reaching the private address. The scheme payload: file://, gopher://, credentials-in-URL, and malformed URLs, all rejected at parse. The response-handling payload: a forged fetch whose response body must not render back to the attacker when the destination is blocked. Integration shape matters: run these against a real network namespace or a local metadata mock, not against mocked DNS, because the entire vulnerability lives in the gap between what the code says and what the network does.

const TARGETS = [
 'http://169.254.169.254/latest/meta-data/',
 'http://127.0.0.1:8080/admin',
 'http://10.0.0.5/internal',
 'http://[::ffff:127.0.0.1]/',
];
for (const url of TARGETS) {
 await expect(safeFetch(url)).rejects.toBeInstanceOf(SSRFError);
}

Common pitfalls

  • **Validating the hostname, not the address. ** The name is a claim; only the resolved IP is a fact, and only at connect time.
  • **Automatic redirects left on. ** The first hop passes validation and the 302 walks the connection into the interior.
  • **Incomplete blocklists. ** Missing IPv6, mapped addresses, or the zero network; the missed range is the attack.
  • **Validate-then-fetch without pinning. ** DNS rebinding changes the answer between validation and connection.
  • **Response bodies rendered back. ** Blocked destinations must not become an exfiltration channel through the feature’s own output.
  • **No egress backstop. ** Application-only defenses fail eventually; deny-by-default egress makes the failure survivable.

Conclusion

SSRF is the application lending its network privileges to whoever supplies a URL, and the defense is a validation pipeline attached to every connection those URLs cause. Inventory the fetch surfaces, validate scheme and syntax before any network activity, resolve and check the address against the complete blocked set, private, loopback, link-local, metadata, IPv6 and mapped forms, and handle redirects as fresh destinations with the full pipeline each hop. Pin connections to the validated address so DNS rebinding cannot split validation from connection, keep blocked responses out of the feature’s output so the guard does not become the exfiltration channel, and back the whole application layer with deny-by-default egress and hardened metadata services, because the network layer is what turns an eventual bug into a logged anomaly instead of an incident. Test with the canonical payload set against real resolution behavior, since the vulnerability lives exactly where mocks stop being honest.

Sources: OWASP: SSRF prevention cheat sheet, RFC 1918: private address ranges, MDN: same-origin policy.

FAQ

What makes SSRF different from a normal request bug?
The server’s network position is the vulnerability: it can reach cloud metadata endpoints, internal admin panels, and databases that no external attacker could touch. The attack borrows the server’s privileges to map and hit the interior.
Why is validating the hostname not enough?
The hostname is a claim; the IP is the fact. DNS can return a private address directly, or return a public one first and a private one later, the rebinding attack. Validation must happen on the resolved address, and the connection must use that same address.
Do allowlists beat blocklists?
Allowlists are stronger: enumerate the destinations the feature legitimately needs and block everything else. Blocklists are the fallback when the destination set is genuinely open, and then they must cover the full private, loopback, link-local, and metadata ranges, including IPv6.

Related Examples