December 3, 2026
SSRF protection for server-side fetch in Node.js:
How to fetch user-supplied URLs from Node.js without letting them reach localhost, cloud metadata or your internal network: parse firstβ¦
By Ali Ahmed
4 min read
SSRF protection for server-side fetch in Node.js: block private addresses at connect time, on every redirect
How to fetch user-supplied URLs from Node.js without letting them reach localhost, cloud metadata or your internal network: parse first, block private and IPv4-mapped addresses, check DNS results at connect time to stop rebinding, and follow redirects manually so every hop is checked. Tested with undici, including five spellings of 127.0.0.1 and the BlockList rule that blocks every public IPv4 address.
This story was written with the assistance of an AI writing program.
Video: Three ways a URL reaches your internal network, and the guard that stops each
Server-side request forgery (SSRF) happens when your server fetches a URL someone else chose, and that URL points somewhere only your server can reach: localhost, a database, the cloud metadata service at 169.254.169.254, or another machine on the internal network. Checking the URL string isn't enough, because 2130706433, 0x7f.0.0.1, 127.1 and 0177.0.0.1 are all 127.0.0.1, and a harmless-looking hostname can resolve to a private address. The fix that holds up: parse the URL first, refuse private and reserved addresses including IPv4-mapped IPv6, check the address DNS actually returned at connect time (which also stops DNS rebinding), and set redirect: "manual" so every redirect hop goes through the same checks. In my test, a plain fetch followed a public page's redirect and read "SECRET from 127.0.0.1"; the guarded version refused it. One trap along the way: adding ::ffff:0:0/96 to Node's BlockList blocks every IPv4 address, including 8.8.8.8.
Check the parsed address, then the resolved address, then every redirect.
This is the guard from a lead-research pipeline I built, which reads exhibitor websites listed on a trade-show directory: the URLs come from a third party, so each one is treated as hostile. The version below is trimmed from that code and tested on its own.
Which addresses should be blocked?
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7: What's there: Private networks100.64.0.0/10: What's there: Carrier-grade NAT, used inside some clouds192.0.0.0/24,198.18.0.0/15,224.0.0.0/4,240.0.0.0/4: What's there: Reserved, benchmarking, multicast
Where does each check run?
Each checkpoint catches what the one before can't see.
The guard
const blocked = new net.BlockList();
for (const [a, p] of [
ββ["0.0.0.0", 8],
ββ["10.0.0.0", 8],
ββ["100.64.0.0", 10],
ββ["127.0.0.0", 8],
ββ["169.254.0.0", 16],
ββ["172.16.0.0", 12],
ββ["192.0.0.0", 24],
ββ["192.168.0.0", 16],
ββ["198.18.0.0", 15],
ββ["224.0.0.0", 4],
ββ["240.0.0.0", 4],
])
ββblocked.addSubnet(a, p, "ipv4");
for (const [a, p] of [
ββ["::", 128],
ββ["::1", 128],
ββ["fc00::", 7],
ββ["fe80::", 10],
])
ββblocked.addSubnet(a, p, "ipv6");
function unmapIpv4(ip) {
ββconst canonical = new URL(`http://[${ip}]`).hostname.slice(1, -1); // normalises ::ffff:127.0.0.1 to ::ffff:7f00:1
ββconst m = canonical.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
ββif (!m) return undefined;
ββconst [hi, lo] = [parseInt(m[1], 16), parseInt(m[2], 16)];
ββreturn [hi >> 8, hi & 255, lo >> 8, lo & 255].join(".");
}
export function isPrivateIp(ip) {
ββif (allow.has(ip)) return false;
ββif (net.isIPv6(ip)) {
ββββconst v4 = unmapIpv4(ip);
ββββreturn v4 ? isPrivateIp(v4) : blocked.check(ip, "ipv6");
ββ}
ββreturn blocked.check(ip, "ipv4");
}const blocked = new net.BlockList();
for (const [a, p] of [
ββ["0.0.0.0", 8],
ββ["10.0.0.0", 8],
ββ["100.64.0.0", 10],
ββ["127.0.0.0", 8],
ββ["169.254.0.0", 16],
ββ["172.16.0.0", 12],
ββ["192.0.0.0", 24],
ββ["192.168.0.0", 16],
ββ["198.18.0.0", 15],
ββ["224.0.0.0", 4],
ββ["240.0.0.0", 4],
])
ββblocked.addSubnet(a, p, "ipv4");
for (const [a, p] of [
ββ["::", 128],
ββ["::1", 128],
ββ["fc00::", 7],
ββ["fe80::", 10],
])
ββblocked.addSubnet(a, p, "ipv6");
function unmapIpv4(ip) {
ββconst canonical = new URL(`http://[${ip}]`).hostname.slice(1, -1); // normalises ::ffff:127.0.0.1 to ::ffff:7f00:1
ββconst m = canonical.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
ββif (!m) return undefined;
ββconst [hi, lo] = [parseInt(m[1], 16), parseInt(m[2], 16)];
ββreturn [hi >> 8, hi & 255, lo >> 8, lo & 255].join(".");
}
export function isPrivateIp(ip) {
ββif (allow.has(ip)) return false;
ββif (net.isIPv6(ip)) {
ββββconst v4 = unmapIpv4(ip);
ββββreturn v4 ? isPrivateIp(v4) : blocked.check(ip, "ipv6");
ββ}
ββreturn blocked.check(ip, "ipv4");
}The obvious way to block IPv4-mapped addresses is to add ::ffff:0:0/96 to the list. Don't:
const b = new net.BlockList();
b.addSubnet("::ffff:0:0", 96, "ipv6");
b.check("8.8.8.8", "ipv4"); // true
b.check("1.1.1.1", "ipv4"); // trueconst b = new net.BlockList();
b.addSubnet("::ffff:0:0", 96, "ipv6");
b.check("8.8.8.8", "ipv4"); // true
b.check("1.1.1.1", "ipv4"); // trueNode's BlockList also matches IPv4 addresses against IPv4-mapped IPv6 rules, so that one rule blocks the whole internet. Unwrap mapped addresses and check them as IPv4 instead, as isPrivateIp does.
export function checkUrl(raw) {
ββconst u = new URL(raw); // WHATWG parsing turns 2130706433, 0x7f.1 and 127.1 into 127.0.0.1
ββif (u.protocol !== "http:" && u.protocol !== "https:") throw new Refused(`scheme ${u.protocol}`);
ββconst host = u.hostname.replace(/^\[|\]$/g, "");
ββif (net.isIP(host) && isPrivateIp(host)) throw new Refused(`private address ${host}`);
ββreturn u;
}
// Hostnames are checked after DNS, at connect time: this is what stops DNS rebinding.
export const agent = new Agent({
ββconnect: {
ββββlookup(hostname, options, cb) {
ββββββdns.lookup(hostname, { ...options, all: true }, (err, list) => {
ββββββββif (err) return cb(err);
ββββββββconst bad = list.find((a) => isPrivateIp(a.address));
ββββββββif (bad) return cb(new Refused(`${hostname} resolves to ${bad.address}`));
ββββββββreturn options.all ? cb(null, list) : cb(null, list[0].address, list[0].family);
ββββββ});
ββββ},
ββ},
});
export async function safeFetch(raw, { maxRedirects = 5 } = {}) {
ββlet url = checkUrl(raw);
ββfor (let hop = 0; ; hop++) {
ββββlet res;
ββββtry {
ββββββres = await fetch(url, { dispatcher: agent, redirect: "manual", signal: AbortSignal.timeout(15_000) });
ββββ} catch (e) {
ββββββthrow e?.cause instanceof Refused ? e.cause : e;
ββββ}
ββββconst loc = res.status >= 300 && res.status < 400 && res.headers.get("location");
ββββif (!loc) return res;
ββββawait res.body?.cancel();
ββββif (hop >= maxRedirects) throw new Refused("too many redirects");
ββββurl = checkUrl(new URL(loc, url).href); // every hop is checked again
ββ}
}export function checkUrl(raw) {
ββconst u = new URL(raw); // WHATWG parsing turns 2130706433, 0x7f.1 and 127.1 into 127.0.0.1
ββif (u.protocol !== "http:" && u.protocol !== "https:") throw new Refused(`scheme ${u.protocol}`);
ββconst host = u.hostname.replace(/^\[|\]$/g, "");
ββif (net.isIP(host) && isPrivateIp(host)) throw new Refused(`private address ${host}`);
ββreturn u;
}
// Hostnames are checked after DNS, at connect time: this is what stops DNS rebinding.
export const agent = new Agent({
ββconnect: {
ββββlookup(hostname, options, cb) {
ββββββdns.lookup(hostname, { ...options, all: true }, (err, list) => {
ββββββββif (err) return cb(err);
ββββββββconst bad = list.find((a) => isPrivateIp(a.address));
ββββββββif (bad) return cb(new Refused(`${hostname} resolves to ${bad.address}`));
ββββββββreturn options.all ? cb(null, list) : cb(null, list[0].address, list[0].family);
ββββββ});
ββββ},
ββ},
});
export async function safeFetch(raw, { maxRedirects = 5 } = {}) {
ββlet url = checkUrl(raw);
ββfor (let hop = 0; ; hop++) {
ββββlet res;
ββββtry {
ββββββres = await fetch(url, { dispatcher: agent, redirect: "manual", signal: AbortSignal.timeout(15_000) });
ββββ} catch (e) {
ββββββthrow e?.cause instanceof Refused ? e.cause : e;
ββββ}
ββββconst loc = res.status >= 300 && res.status < 400 && res.headers.get("location");
ββββif (!loc) return res;
ββββawait res.body?.cancel();
ββββif (hop >= maxRedirects) throw new Refused("too many redirects");
ββββurl = checkUrl(new URL(loc, url).href); // every hop is checked again
ββ}
}Three details carry the weight:
- The lookup hook runs at connect time. Checking DNS yourself and then letting
fetchresolve again leaves a gap: a hostname can answer with a public address for your check and a private one for the connection (DNS rebinding). Checking inside the connection's own lookup closes it. - Every address is checked, not just the first.
localhostusually resolves to both::1and127.0.0.1; one bad answer refuses the whole request.
fetch here is undici's ( npm i undici), because Node's built-in fetch takes a dispatcher only from the undici package.
What the tests show
The test runs two local servers: an internal one on 127.0.0.1 that returns a secret, and a "public" one on ::1 (allowed only in the test) that redirects to it. Six tests pass:
- Tricky spellings refused:
2130706433,0x7f.0.0.1,127.1,0177.0.0.1,[::ffff:127.0.0.1],[::ffff:7f00:1],169.254.169.254,[fd00::1],0.0.0.0, plusfile:andgopher:URLs.new URL()normalised the first four to127.0.0.1. - Public addresses pass:
8.8.8.8,2606:4700:4700::1111and::ffff:8.8.8.8. - The BlockList trap is real: with
::ffff:0:0/96added,8.8.8.8and1.1.1.1are blocked. localhostis refused at connect time, by the DNS check.
What else to put around it
- Timeouts and size limits: 15 seconds and a few megabytes, so a slow or huge response can't tie up workers.
- No credentials: never forward cookies or auth headers to a user-chosen URL.
- Egress rules: if the platform allows it, a network policy or proxy that only permits outbound internet traffic is a second layer that doesn't depend on this code.
- For AI agents too: a "fetch this URL" tool is the same risk with an LLM choosing the URL, and prompt injection in scraped data is how an attacker gets to choose it. Localhost is not authentication covers the service side: anything listening on loopback should still check who's calling.
Summary
For checking what users upload rather than what you fetch, see validating file uploads by magic bytes.
Written by Ali Ahmed (QuantumBreakz), AI engineer in Lahore Β· Original article
Originally published at https://aliahmed.si.