SSRF: how server-side request forgery works and how to close it
Server-side request forgery (SSRF) is what happens when an application fetches a URL that someone else chose and the request lands somewhere it should not: an admin page on the same machine, a service inside your network or a cloud metadata service.
This guide explains where SSRF hides in ordinary features, why checking the hostname text is not enough and what network controls add, and gives you a local Node.js lab whose verification table and regression test check an allowlist against ten kinds of input.
In this guide
Egress lab: allowlist verification table and SSRF regression test
An illustration written for this page, not client code. Four fetchers take ten inputs through a stand-in network of local servers on 127.0.0.1, including a mock metadata service that returns a fixed word, a redirect chain and a DNS rebinding fixture, and print a verification table of what the URL parser reported, what each name resolved to, the port and the redirect hops.
How to use itHide the instructions
A regression test on Node.js's built-in test runner fails for the three weaker fetchers and passes for the checked one. It needs Node.js only. Use it on your own computer to learn, and to test code you own.
ssrf.txt
ILLUSTRATION ONLY. The partner names, addresses, servers and inputs below were written for this page. They are not a client's code or a client's result. Use the lab on your own computer to learn, and to test code you own. Do not point any part of it at a system you do not own or are not authorised in writing to test, and do not aim it at a real cloud metadata service.
WHAT IT NEEDS
Node.js, with nothing to install. The lab uses only built-in modules (node:http, node:net, node:assert and node:test) and the global URL class and fetch(). The Node.js documentation lists the test runner as stable from version 20.0.0 and fetch() as no longer experimental from version 21.0.0. The outputs below were recorded on Node.js 26.0.0 on macOS. The commands under RUN IT set LAB_FETCHER the way macOS and Linux shells do; on Windows, set it the way your shell does.
WHAT IT DOES NOT DO
Every server in the lab listens on 127.0.0.1, on a port the operating system picks. Addresses such as 169.254.169.254 and 10.0.0.5 exist only in the lab's own list of services: a transport handed to node:http connects each request to the matching local server instead, and records which address and port the request was for. Nothing is sent to a real metadata service or to any other machine. Names are answered by a fake resolver inside the lab, never by DNS. The mock metadata service is a local server that returns one fixed word, LAB-METADATA-MARKER. The two partner addresses come from 203.0.113.0/24, which IANA's IPv4 special-purpose registry lists as Documentation (TEST-NET-3, RFC 5737). Nothing reads a file.
THE STAND-IN NETWORK
images.partner.test resolves to 203.0.113.10 partner image server: /logo.png returns PARTNER-IMAGE-OK, /go redirects to http://169.254.169.254/metadata
cdn.partner.test resolves to 203.0.113.20 the rebinding fixture: the first lookup answers 203.0.113.20 (returns PARTNER-CDN-OK), every later lookup answers 169.254.169.254
files.partner.test resolves to 10.0.0.5 a partner name whose record points at a private address
169.254.169.254:80 mock metadata service, returns LAB-METADATA-MARKER
10.0.0.5:80 internal admin page, returns LAB-INTERNAL-ADMIN-MARKER
127.0.0.1:80 loopback admin page, returns LAB-LOOPBACK-ADMIN-MARKER
Any other address and port: no service, and the attempt is recorded (LAB_NO_SERVICE).
THE FOUR FETCHERS
fetchUnsafe fetches whatever it is given and follows redirects, up to five.
fetchWithTextFilter refuses URL text containing localhost, 127., 169.254., 10.0. or 192.168., then behaves like fetchUnsafe.
fetchCheckedOnce parses the URL, applies the allowlist (scheme, host, port), resolves the name and checks every address against blocked ranges, then hands the original text to the same client as fetchUnsafe.
fetchChecked does all of that on every hop, connects to the address it checked, and stops after three hops. This is the one to copy.
SET-UP
Make an empty folder, save the five files below into it under the names shown, and run the commands under RUN IT from that folder.
==== File 1 of 5: lab-network.mjs ====
// lab-network.mjs: the lab's stand-in network. Every server listens on
// 127.0.0.1, on a port the operating system picks. The addresses the
// fetchers ask for, such as 169.254.169.254, exist only in SERVICES: the
// lab transport looks each one up and connects to the matching local
// server, so no request leaves this computer. Names are answered by a fake
// resolver inside the lab, never by DNS.
import http from 'node:http'
import net from 'node:net'
export const MARKERS = {
partnerImage: 'PARTNER-IMAGE-OK',
partnerCdn: 'PARTNER-CDN-OK',
metadata: 'LAB-METADATA-MARKER',
internalAdmin: 'LAB-INTERNAL-ADMIN-MARKER',
loopbackAdmin: 'LAB-LOOPBACK-ADMIN-MARKER',
}
// What each lab name answers, in order. files.partner.test is a partner
// name whose record points at a private address. cdn.partner.test is the
// rebinding fixture: its first answer is a partner address, and every
// later answer is the address that stands in for a metadata service.
const NAME_ANSWERS = {
'images.partner.test': ['203.0.113.10'],
'files.partner.test': ['10.0.0.5'],
'cdn.partner.test': ['203.0.113.20', '169.254.169.254'],
}
function replyWith(text) {
return function (request, response) {
response.writeHead(200, { 'content-type': 'text/plain' })
response.end(text)
}
}
// The partner's image server: one image, and one path that redirects to
// the stand-in metadata address.
function partnerImages(request, response) {
if (request.url === '/logo.png') {
replyWith(MARKERS.partnerImage)(request, response)
return
}
if (request.url === '/go') {
response.writeHead(302, { location: 'http://169.254.169.254/metadata' })
response.end()
return
}
response.writeHead(404)
response.end()
}
// Which local server answers for each lab address and port. The mock
// metadata service is only a local server that returns a fixed word.
const SERVICES = {
'203.0.113.10:80': partnerImages,
'203.0.113.20:80': replyWith(MARKERS.partnerCdn),
'169.254.169.254:80': replyWith(MARKERS.metadata),
'10.0.0.5:80': replyWith(MARKERS.internalAdmin),
'127.0.0.1:80': replyWith(MARKERS.loopbackAdmin),
}
function listenOnLoopback(handler) {
return new Promise(function (resolve) {
const server = http.createServer(handler)
server.listen(0, '127.0.0.1', function () {
resolve(server)
})
})
}
// Starts one local server per lab address. Returns the address book (lab
// address and port to local port) and a function that stops them all.
export async function startLabNetwork() {
const addressBook = {}
const servers = []
for (const destination of Object.keys(SERVICES)) {
const server = await listenOnLoopback(SERVICES[destination])
addressBook[destination] = server.address().port
servers.push(server)
}
async function stop() {
for (const server of servers) {
server.closeAllConnections()
await new Promise(function (resolve) {
server.close(resolve)
})
}
}
return { addressBook: addressBook, stop: stop }
}
function labNotFound(name) {
const error = new Error('the lab has no answer for ' + name)
error.code = 'ENOTFOUND'
return error
}
// A fake resolver with its own lookup counts. Each fetcher run gets a new
// one, so the rebinding fixture starts again from its first answer.
export function createLabResolver() {
const counts = {}
function nextAnswer(name) {
const answers = NAME_ANSWERS[name]
if (!answers) return null
const count = counts[name] || 0
counts[name] = count + 1
return answers[Math.min(count, answers.length - 1)]
}
// The same shape as dns.promises.lookup(name, { all: true }).
async function lookupAll(name) {
const address = nextAnswer(name)
if (!address) throw labNotFound(name)
return [{ address: address, family: 4 }]
}
// The same shape as dns.lookup(), which net.connect() calls.
function lookup(name, options, callback) {
const address = nextAnswer(name)
if (!address) {
callback(labNotFound(name))
return
}
if (options && options.all) {
callback(null, [{ address: address, family: 4 }])
return
}
callback(null, address, 4)
}
return { lookupAll: lookupAll, lookup: lookup }
}
// The lab transport, passed to node:http as createConnection. It does what
// the network would: it finds the address (with options.lookup when the
// caller supplied one, as net.connect() does, or else the lab's resolver),
// records the attempt, and connects to the local server for that address
// and port. An address and port with no lab service fails with
// LAB_NO_SERVICE, and nothing is sent.
function createLabTransport(addressBook, resolver, attempts) {
function connectTo(address, port, callback) {
const destination = address + ':' + port
attempts.push(destination)
const localPort = addressBook[destination]
if (!localPort) {
const error = new Error('no lab service at ' + destination)
error.code = 'LAB_NO_SERVICE'
callback(error)
return
}
callback(null, net.connect(localPort, '127.0.0.1'))
}
return function labTransport(options, callback) {
const port = Number(options.port) || 80
if (net.isIP(options.host)) {
connectTo(options.host, port, callback)
return undefined
}
const lookup = options.lookup || resolver.lookup
lookup(options.host, {}, function (error, address) {
if (error) {
callback(error)
return
}
connectTo(address, port, callback)
})
return undefined
}
}
// Everything one fetcher run needs: a fresh resolver, a transport and a
// list of every address and port the run tried to connect to.
export function createLabRun(addressBook) {
const resolver = createLabResolver()
const attempts = []
const transport = createLabTransport(addressBook, resolver, attempts)
return { resolver: resolver, transport: transport, attempts: attempts }
}
==== File 2 of 5: fetchers.mjs ====
// fetchers.mjs: four ways to fetch a URL a user supplied, as a link
// preview, webhook, importer or image fetcher would. Only fetchChecked is
// meant to be copied. Each takes the URL text and a lab run, and returns
// what happened. In your own code, leave out createConnection: it is the
// lab transport, standing in for the network.
import http from 'node:http'
import net from 'node:net'
const REDIRECT_STATUSES = [301, 302, 303, 307, 308]
// One GET with node:http. Resolves with the status, the Location header and
// the body, or with the error code if the request failed.
function sendGet(target, options) {
return new Promise(function (resolve) {
let request
try {
request = http.get(target, options, function (response) {
let body = ''
response.setEncoding('utf8')
response.on('data', function (chunk) {
body += chunk
})
response.on('end', function () {
resolve({ status: response.statusCode, location: response.headers.location, body: body })
})
})
} catch (error) {
resolve({ error: error.code })
return
}
request.on('error', function (error) {
resolve({ error: error.code })
})
})
}
// 1. UNSAFE: fetches whatever it is given and follows redirects, up to five.
export async function fetchUnsafe(input, run) {
const hops = []
let target = input
for (let hop = 1; hop <= 5; hop++) {
const reply = await sendGet(target, { createConnection: run.transport })
if (reply.error) return { outcome: 'ERROR', reason: reply.error, hops: hops }
if (!REDIRECT_STATUSES.includes(reply.status)) return { outcome: 'GOT', body: reply.body, hops: hops }
target = new URL(reply.location, target).href
hops.push(reply.status + ' to ' + target)
}
return { outcome: 'ERROR', reason: 'too many redirects', hops: hops }
}
// 2. TEXT FILTER: refuses a URL whose text contains a blocked address or
// name, then behaves exactly like fetchUnsafe.
const BLOCKED_TEXT = ['localhost', '127.', '169.254.', '10.0.', '192.168.']
export async function fetchWithTextFilter(input, run) {
for (const text of BLOCKED_TEXT) {
if (input.includes(text)) return { outcome: 'REFUSED', code: 'text', reason: 'the text contains ' + text, hops: [] }
}
return fetchUnsafe(input, run)
}
// The allowlist. The lab speaks plain http on port 80; a real feature would
// allow https: and port 443 only.
const POLICY = {
schemes: ['http:'],
hosts: ['images.partner.test', 'files.partner.test', 'cdn.partner.test'],
ports: [80],
maxHops: 3,
}
const DEFAULT_PORTS = { 'http:': 80, 'https:': 443 }
// The URL class leaves port empty when it is the scheme's default.
function portOf(url) {
if (url.port !== '') return Number(url.port)
return DEFAULT_PORTS[url.protocol]
}
// Ranges no fetch may reach: rows of the IANA special-purpose address
// registries, plus multicast from OWASP's list. An IPv4 rule also matches
// the IPv4-mapped IPv6 form when the address is checked as 'ipv6'. The lab's
// partners use documentation addresses (RFC 5737), so this list leaves
// those out; a production list would include 192.0.2.0/24, 198.51.100.0/24
// and 203.0.113.0/24 too.
const BLOCKED_RANGES = [
['0.0.0.0', 8, 'ipv4'],
['10.0.0.0', 8, 'ipv4'],
['100.64.0.0', 10, 'ipv4'],
['127.0.0.0', 8, 'ipv4'],
['169.254.0.0', 16, 'ipv4'],
['172.16.0.0', 12, 'ipv4'],
['192.168.0.0', 16, 'ipv4'],
['224.0.0.0', 4, 'ipv4'],
['240.0.0.0', 4, 'ipv4'],
['::', 128, 'ipv6'],
['::1', 128, 'ipv6'],
['64:ff9b::', 96, 'ipv6'],
['64:ff9b:1::', 48, 'ipv6'],
['fc00::', 7, 'ipv6'],
['fe80::', 10, 'ipv6'],
['ff00::', 8, 'ipv6'],
]
const BLOCKED = new net.BlockList()
for (const range of BLOCKED_RANGES) {
BLOCKED.addSubnet(range[0], range[1], range[2])
}
// check() reads an address as IPv4 unless told otherwise, so pass the type.
export function isBlockedAddress(address) {
const type = net.isIPv6(address) ? 'ipv6' : 'ipv4'
return BLOCKED.check(address, type)
}
function refusal(code, reason) {
return { refusal: { code: code, reason: reason } }
}
function checkUrl(url) {
if (!POLICY.schemes.includes(url.protocol)) return refusal('scheme', 'scheme ' + url.protocol + ' is not allowed')
if (!POLICY.hosts.includes(url.hostname)) return refusal('host', 'host ' + url.hostname + ' is not on the allowlist')
if (!POLICY.ports.includes(portOf(url))) return refusal('port', 'port ' + portOf(url) + ' is not allowed')
return null
}
// Parses once, checks the URL against the allowlist, resolves the name once
// and checks every address it returns. In your own code, lookupAll(name) is
// dns.promises.lookup(name, { all: true }).
async function checkDestination(target, resolver) {
let url
try {
url = new URL(target)
} catch {
return refusal('url', 'not a valid URL')
}
const urlProblem = checkUrl(url)
if (urlProblem) return urlProblem
let answers
try {
answers = await resolver.lookupAll(url.hostname)
} catch {
return refusal('dns', 'the name did not resolve')
}
for (const answer of answers) {
if (isBlockedAddress(answer.address)) return refusal('address', 'address ' + answer.address + ' is in a blocked range')
}
return { url: url, address: answers[0].address, family: answers[0].family }
}
// 3. CHECKED ONCE: parses the URL, checks it against the allowlist, resolves
// the name and checks every address, then hands the original text to the
// same client as fetchUnsafe. That client resolves the name again and
// follows redirects without checking them.
export async function fetchCheckedOnce(input, run) {
const verdict = await checkDestination(input, run.resolver)
if (verdict.refusal) return { outcome: 'REFUSED', code: verdict.refusal.code, reason: verdict.refusal.reason, hops: [] }
return fetchUnsafe(input, run)
}
// A lookup function that always answers with the address already checked,
// so the connection cannot resolve the name a second time. node:http still
// sends the name in the Host header, as the last test in ssrf.test.mjs shows.
export function pinnedLookup(address, family) {
return function (hostname, options, callback) {
if (options && options.all) {
callback(null, [{ address: address, family: family }])
return
}
callback(null, address, family)
}
}
// 4. CHECKED: the version to copy. Every hop is parsed once, checked against
// the allowlist and the blocked ranges, and connected to the address that
// was checked. A redirect starts the checks again from the top.
export async function fetchChecked(input, run) {
const hops = []
let target = input
for (let hop = 1; hop <= POLICY.maxHops; hop++) {
const verdict = await checkDestination(target, run.resolver)
if (verdict.refusal) {
return { outcome: 'REFUSED', code: verdict.refusal.code, reason: 'hop ' + hop + ': ' + verdict.refusal.reason, hops: hops }
}
const options = { lookup: pinnedLookup(verdict.address, verdict.family), createConnection: run.transport }
const reply = await sendGet(verdict.url, options)
if (reply.error) return { outcome: 'ERROR', reason: reply.error, hops: hops }
if (!REDIRECT_STATUSES.includes(reply.status)) return { outcome: 'GOT', body: reply.body, hops: hops }
target = new URL(reply.location, verdict.url).href
hops.push(reply.status + ' to ' + target)
}
return { outcome: 'REFUSED', code: 'hops', reason: 'too many redirects', hops: hops }
}
export const FETCHERS = {
fetchUnsafe: fetchUnsafe,
fetchWithTextFilter: fetchWithTextFilter,
fetchCheckedOnce: fetchCheckedOnce,
fetchChecked: fetchChecked,
}
==== File 3 of 5: cases.mjs ====
// cases.mjs: one input per row of the verification table. Every address
// here is one of the lab's stand-ins and reaches only a local server.
export const CASES = [
{ id: 'R1', label: 'allowed URL', input: 'http://images.partner.test/logo.png' },
{ id: 'R2', label: 'loopback address', input: 'http://127.0.0.1/admin' },
{ id: 'R3', label: 'link-local address', input: 'http://169.254.169.254/metadata' },
{ id: 'R4', label: 'private-range address', input: 'http://10.0.0.5/admin' },
{ id: 'R5', label: 'allowed name, private address', input: 'http://files.partner.test/admin' },
{ id: 'R6', label: 'another notation', input: 'http://2852039166/metadata' },
{ id: 'R7', label: 'allowed host redirects', input: 'http://images.partner.test/go' },
{ id: 'R8', label: 'rebinding name', input: 'http://cdn.partner.test/app.js' },
{ id: 'R9', label: 'unexpected port', input: 'http://images.partner.test:8080/logo.png' },
{ id: 'R10', label: 'unexpected scheme', input: 'file:///lab-only/marker.txt' },
]
// The only lab addresses and ports a fetch is meant to reach.
export const ALLOWED_DESTINATIONS = ['203.0.113.10:80', '203.0.113.20:80']
==== File 4 of 5: table.mjs ====
// table.mjs: runs every row through every fetcher and prints the
// verification table, then checks the blocked ranges and shows what global
// fetch does with a redirect. Everything runs on 127.0.0.1.
import http from 'node:http'
import net from 'node:net'
import { CASES } from './cases.mjs'
import { FETCHERS, isBlockedAddress } from './fetchers.mjs'
import { createLabResolver, createLabRun, startLabNetwork } from './lab-network.mjs'
const DEFAULT_PORTS = { 'http:': '80', 'https:': '443' }
function printGrid(title, columns, rows) {
const widths = columns.map(function (column, index) {
let width = column.length
for (const row of rows) width = Math.max(width, row[index].length)
return width
})
console.log(title)
const lines = [columns].concat(rows)
for (const line of lines) {
const cells = line.map(function (cell, index) {
return cell.padEnd(widths[index])
})
console.log(cells.join(' ').trimEnd())
}
console.log('')
}
// What the URL class reported: scheme, host and the port that will be used.
function describeParse(input) {
let url
try {
url = new URL(input)
} catch {
return ['not a URL', '', '']
}
const host = url.hostname || '(none)'
let port = url.port
if (port === '') port = DEFAULT_PORTS[url.protocol] ? DEFAULT_PORTS[url.protocol] + ' (default)' : '(none)'
return [url.protocol, host, port]
}
// What the lab's resolver answers for the host, asked twice.
async function describeResolution(host) {
if (host === '(none)') return '(no host)'
if (net.isIP(host)) return '(an IP address)'
const resolver = createLabResolver()
const first = (await resolver.lookupAll(host))[0].address
const second = (await resolver.lookupAll(host))[0].address
if (first === second) return first
return '1st ' + first + ', 2nd ' + second
}
function describeResult(result) {
if (result.outcome === 'GOT') return 'GOT ' + result.body
if (result.outcome === 'REFUSED') return 'REFUSED (' + result.code + ')'
return 'ERROR ' + result.reason
}
async function runAllFetchers(network) {
const results = {}
for (const row of CASES) {
results[row.id] = {}
for (const name of Object.keys(FETCHERS)) {
const run = createLabRun(network.addressBook)
results[row.id][name] = await FETCHERS[name](row.input, run)
}
}
return results
}
async function printVerificationTable(results) {
const inputRows = CASES.map(function (row) {
return [row.id, row.label, row.input]
})
printGrid('TABLE 1. THE INPUTS', ['Row', 'Input class', 'URL as typed'], inputRows)
const seenRows = []
for (const row of CASES) {
const parsed = describeParse(row.input)
const resolved = await describeResolution(parsed[1])
const hops = results[row.id].fetchUnsafe.hops
seenRows.push([row.id, parsed[0], parsed[1], parsed[2], resolved, hops.length ? hops.join('; ') : 'none'])
}
printGrid('TABLE 2. WHAT THE CHECKS SEE', ['Row', 'Scheme', 'Host (URL parser)', 'Port', 'Name resolved to', 'Redirect hops (unsafe run)'], seenRows)
const names = Object.keys(FETCHERS)
const resultRows = CASES.map(function (row) {
return [row.id].concat(names.map(function (name) {
return describeResult(results[row.id][name])
}))
})
printGrid('TABLE 3. WHAT EACH FETCHER DID', ['Row'].concat(names), resultRows)
console.log('WHY THE TWO CHECKED FETCHERS REFUSED')
for (const row of CASES) {
for (const name of ['fetchCheckedOnce', 'fetchChecked']) {
const result = results[row.id][name]
if (result.outcome === 'REFUSED') console.log(row.id + ' ' + name + ': ' + result.reason)
}
}
console.log('')
}
function printBlockedRangeCheck() {
const addresses = ['203.0.113.10', '127.0.0.1', '169.254.169.254', '10.0.0.5', '::1', '::ffff:169.254.169.254', 'fd00:ec2::254', 'fe80::1']
const rows = addresses.map(function (address) {
return [address, isBlockedAddress(address) ? 'yes' : 'no']
})
printGrid('BLOCKED-RANGE CHECK (isBlockedAddress, built on net.BlockList)', ['Address', 'Blocked'], rows)
}
function listen(handler) {
return new Promise(function (resolve) {
const server = http.createServer(handler)
server.listen(0, '127.0.0.1', function () {
resolve(server)
})
})
}
// Global fetch against two loopback servers: one redirects to the other.
async function printFetchRedirectModes() {
const target = await listen(function (request, response) {
response.end('LAB-METADATA-MARKER')
})
const redirector = await listen(function (request, response) {
response.writeHead(302, { location: 'http://127.0.0.1:' + target.address().port + '/metadata' })
response.end()
})
const start = 'http://127.0.0.1:' + redirector.address().port + '/go'
console.log('GLOBAL FETCH AND REDIRECTS (two servers on 127.0.0.1)')
const followed = await fetch(start)
console.log('redirect not set: status ' + followed.status + ', redirected ' + followed.redirected + ', body ' + (await followed.text()))
try {
await fetch(start, { redirect: 'error' })
console.log('redirect: error: no error')
} catch (error) {
console.log('redirect: error: ' + error.name + ': ' + error.message + ' (cause: ' + error.cause.message + ')')
}
for (const server of [target, redirector]) {
server.closeAllConnections()
server.close()
}
}
const network = await startLabNetwork()
const results = await runAllFetchers(network)
console.log('Node.js ' + process.version)
console.log('')
await printVerificationTable(results)
printBlockedRangeCheck()
await printFetchRedirectModes()
await network.stop()
==== File 5 of 5: ssrf.test.mjs ====
// ssrf.test.mjs: a regression test for the fetcher LAB_FETCHER names. It
// passes for fetchChecked and fails for the other three.
import assert from 'node:assert/strict'
import http from 'node:http'
import { after, before, test } from 'node:test'
import { ALLOWED_DESTINATIONS, CASES } from './cases.mjs'
import { FETCHERS, pinnedLookup } from './fetchers.mjs'
import { MARKERS, createLabRun, startLabNetwork } from './lab-network.mjs'
const fetcherName = process.env.LAB_FETCHER || 'fetchChecked'
const fetcher = FETCHERS[fetcherName]
let network
before(async function () {
network = await startLabNetwork()
})
after(async function () {
await network.stop()
})
test('R1 the allowed URL still delivers the partner image', async function () {
const run = createLabRun(network.addressBook)
const result = await fetcher(CASES[0].input, run)
assert.equal(result.body, MARKERS.partnerImage, fetcherName + ' gave ' + result.outcome)
})
for (const row of CASES) {
test(row.id + ' ' + row.label + ': no connection outside the allowlist', async function () {
const run = createLabRun(network.addressBook)
await fetcher(row.input, run)
const outside = run.attempts.filter(function (destination) {
return !ALLOWED_DESTINATIONS.includes(destination)
})
assert.deepEqual(outside, [], fetcherName + ' connected to ' + outside.join(', '))
})
}
// Node's own connection code, not the lab transport: a made-up name pinned
// to 127.0.0.1 connects there, and the server sees the name as the Host.
test('pinnedLookup connects to the pinned address and keeps the name', async function () {
const server = http.createServer(function (request, response) {
response.end(request.headers.host)
})
await new Promise(function (resolve) {
server.listen(0, '127.0.0.1', resolve)
})
const port = server.address().port
const hostHeader = await new Promise(function (resolve, reject) {
const options = { hostname: 'images.partner.test', port: port, path: '/', lookup: pinnedLookup('127.0.0.1', 4) }
http.get(options, function (response) {
let body = ''
response.on('data', function (chunk) {
body += chunk
})
response.on('end', function () {
resolve(body)
})
}).on('error', reject)
})
server.closeAllConnections()
server.close()
assert.equal(hostHeader, 'images.partner.test:' + port)
})
==== RUN IT ====
node table.mjs
node --test ssrf.test.mjs
LAB_FETCHER=fetchCheckedOnce node --test ssrf.test.mjs
LAB_FETCHER=fetchWithTextFilter node --test ssrf.test.mjs
LAB_FETCHER=fetchUnsafe node --test ssrf.test.mjs
==== OUTPUT OF node table.mjs (Node.js 26.0.0, macOS) ====
Node.js v26.0.0
TABLE 1. THE INPUTS
Row Input class URL as typed
R1 allowed URL http://images.partner.test/logo.png
R2 loopback address http://127.0.0.1/admin
R3 link-local address http://169.254.169.254/metadata
R4 private-range address http://10.0.0.5/admin
R5 allowed name, private address http://files.partner.test/admin
R6 another notation http://2852039166/metadata
R7 allowed host redirects http://images.partner.test/go
R8 rebinding name http://cdn.partner.test/app.js
R9 unexpected port http://images.partner.test:8080/logo.png
R10 unexpected scheme file:///lab-only/marker.txt
TABLE 2. WHAT THE CHECKS SEE
Row Scheme Host (URL parser) Port Name resolved to Redirect hops (unsafe run)
R1 http: images.partner.test 80 (default) 203.0.113.10 none
R2 http: 127.0.0.1 80 (default) (an IP address) none
R3 http: 169.254.169.254 80 (default) (an IP address) none
R4 http: 10.0.0.5 80 (default) (an IP address) none
R5 http: files.partner.test 80 (default) 10.0.0.5 none
R6 http: 169.254.169.254 80 (default) (an IP address) none
R7 http: images.partner.test 80 (default) 203.0.113.10 302 to http://169.254.169.254/metadata
R8 http: cdn.partner.test 80 (default) 1st 203.0.113.20, 2nd 169.254.169.254 none
R9 http: images.partner.test 8080 203.0.113.10 none
R10 file: (none) (none) (no host) none
TABLE 3. WHAT EACH FETCHER DID
Row fetchUnsafe fetchWithTextFilter fetchCheckedOnce fetchChecked
R1 GOT PARTNER-IMAGE-OK GOT PARTNER-IMAGE-OK GOT PARTNER-IMAGE-OK GOT PARTNER-IMAGE-OK
R2 GOT LAB-LOOPBACK-ADMIN-MARKER REFUSED (text) REFUSED (host) REFUSED (host)
R3 GOT LAB-METADATA-MARKER REFUSED (text) REFUSED (host) REFUSED (host)
R4 GOT LAB-INTERNAL-ADMIN-MARKER REFUSED (text) REFUSED (host) REFUSED (host)
R5 GOT LAB-INTERNAL-ADMIN-MARKER GOT LAB-INTERNAL-ADMIN-MARKER REFUSED (address) REFUSED (address)
R6 GOT LAB-METADATA-MARKER GOT LAB-METADATA-MARKER REFUSED (host) REFUSED (host)
R7 GOT LAB-METADATA-MARKER GOT LAB-METADATA-MARKER GOT LAB-METADATA-MARKER REFUSED (host)
R8 GOT PARTNER-CDN-OK GOT PARTNER-CDN-OK GOT LAB-METADATA-MARKER GOT PARTNER-CDN-OK
R9 ERROR LAB_NO_SERVICE ERROR LAB_NO_SERVICE REFUSED (port) REFUSED (port)
R10 ERROR ERR_INVALID_PROTOCOL ERROR ERR_INVALID_PROTOCOL REFUSED (scheme) REFUSED (scheme)
WHY THE TWO CHECKED FETCHERS REFUSED
R2 fetchCheckedOnce: host 127.0.0.1 is not on the allowlist
R2 fetchChecked: hop 1: host 127.0.0.1 is not on the allowlist
R3 fetchCheckedOnce: host 169.254.169.254 is not on the allowlist
R3 fetchChecked: hop 1: host 169.254.169.254 is not on the allowlist
R4 fetchCheckedOnce: host 10.0.0.5 is not on the allowlist
R4 fetchChecked: hop 1: host 10.0.0.5 is not on the allowlist
R5 fetchCheckedOnce: address 10.0.0.5 is in a blocked range
R5 fetchChecked: hop 1: address 10.0.0.5 is in a blocked range
R6 fetchCheckedOnce: host 169.254.169.254 is not on the allowlist
R6 fetchChecked: hop 1: host 169.254.169.254 is not on the allowlist
R7 fetchChecked: hop 2: host 169.254.169.254 is not on the allowlist
R9 fetchCheckedOnce: port 8080 is not allowed
R9 fetchChecked: hop 1: port 8080 is not allowed
R10 fetchCheckedOnce: scheme file: is not allowed
R10 fetchChecked: hop 1: scheme file: is not allowed
BLOCKED-RANGE CHECK (isBlockedAddress, built on net.BlockList)
Address Blocked
203.0.113.10 no
127.0.0.1 yes
169.254.169.254 yes
10.0.0.5 yes
::1 yes
::ffff:169.254.169.254 yes
fd00:ec2::254 yes
fe80::1 yes
GLOBAL FETCH AND REDIRECTS (two servers on 127.0.0.1)
redirect not set: status 200, redirected true, body LAB-METADATA-MARKER
redirect: error: TypeError: fetch failed (cause: unexpected redirect)
==== REGRESSION TEST RESULTS (Node.js 26.0.0, macOS) ====
The lines below are copied from the test runner's output. Durations change from run to run, and the stack traces under each failure are left out because they show the folder the lab ran in.
Run: node --test ssrf.test.mjs
✔ R1 the allowed URL still delivers the partner image (11.241875ms)
✔ R1 allowed URL: no connection outside the allowlist (1.332416ms)
✔ R2 loopback address: no connection outside the allowlist (0.081292ms)
✔ R3 link-local address: no connection outside the allowlist (0.065125ms)
✔ R4 private-range address: no connection outside the allowlist (0.057584ms)
✔ R5 allowed name, private address: no connection outside the allowlist (0.060625ms)
✔ R6 another notation: no connection outside the allowlist (0.064583ms)
✔ R7 allowed host redirects: no connection outside the allowlist (1.054667ms)
✔ R8 rebinding name: no connection outside the allowlist (0.600458ms)
✔ R9 unexpected port: no connection outside the allowlist (0.078792ms)
✔ R10 unexpected scheme: no connection outside the allowlist (0.042625ms)
✔ pinnedLookup connects to the pinned address and keeps the name (1.631875ms)
ℹ tests 12
ℹ pass 12
ℹ fail 0
Exit code: 0
Run: LAB_FETCHER=fetchCheckedOnce node --test ssrf.test.mjs
✔ R1 the allowed URL still delivers the partner image (11.722166ms)
✔ R1 allowed URL: no connection outside the allowlist (1.519083ms)
✔ R2 loopback address: no connection outside the allowlist (0.086041ms)
✔ R3 link-local address: no connection outside the allowlist (0.081166ms)
✔ R4 private-range address: no connection outside the allowlist (0.051625ms)
✔ R5 allowed name, private address: no connection outside the allowlist (0.071708ms)
✔ R6 another notation: no connection outside the allowlist (0.064417ms)
✖ R7 allowed host redirects: no connection outside the allowlist (2.590959ms)
✖ R8 rebinding name: no connection outside the allowlist (1.342625ms)
✔ R9 unexpected port: no connection outside the allowlist (0.172417ms)
✔ R10 unexpected scheme: no connection outside the allowlist (0.051083ms)
✔ pinnedLookup connects to the pinned address and keeps the name (1.658333ms)
ℹ tests 12
ℹ pass 10
ℹ fail 2
Exit code: 1
Failure messages, in the order of the runner's failing tests list:
AssertionError [ERR_ASSERTION]: fetchCheckedOnce connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchCheckedOnce connected to 169.254.169.254:80
Run: LAB_FETCHER=fetchWithTextFilter node --test ssrf.test.mjs
✔ R1 the allowed URL still delivers the partner image (11.608375ms)
✔ R1 allowed URL: no connection outside the allowlist (1.606083ms)
✔ R2 loopback address: no connection outside the allowlist (0.084792ms)
✔ R3 link-local address: no connection outside the allowlist (0.051ms)
✔ R4 private-range address: no connection outside the allowlist (0.066541ms)
✖ R5 allowed name, private address: no connection outside the allowlist (2.167375ms)
✖ R6 another notation: no connection outside the allowlist (1.049167ms)
✖ R7 allowed host redirects: no connection outside the allowlist (1.172625ms)
✔ R8 rebinding name: no connection outside the allowlist (0.940875ms)
✖ R9 unexpected port: no connection outside the allowlist (0.33875ms)
✔ R10 unexpected scheme: no connection outside the allowlist (0.192958ms)
✔ pinnedLookup connects to the pinned address and keeps the name (2.162875ms)
ℹ tests 12
ℹ pass 8
ℹ fail 4
Exit code: 1
Failure messages, in the order of the runner's failing tests list:
AssertionError [ERR_ASSERTION]: fetchWithTextFilter connected to 10.0.0.5:80
AssertionError [ERR_ASSERTION]: fetchWithTextFilter connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchWithTextFilter connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchWithTextFilter connected to 203.0.113.10:8080
Run: LAB_FETCHER=fetchUnsafe node --test ssrf.test.mjs
✔ R1 the allowed URL still delivers the partner image (11.290458ms)
✔ R1 allowed URL: no connection outside the allowlist (1.468125ms)
✖ R2 loopback address: no connection outside the allowlist (1.866709ms)
✖ R3 link-local address: no connection outside the allowlist (1.097083ms)
✖ R4 private-range address: no connection outside the allowlist (0.80725ms)
✖ R5 allowed name, private address: no connection outside the allowlist (0.681708ms)
✖ R6 another notation: no connection outside the allowlist (0.612833ms)
✖ R7 allowed host redirects: no connection outside the allowlist (0.919834ms)
✔ R8 rebinding name: no connection outside the allowlist (0.69925ms)
✖ R9 unexpected port: no connection outside the allowlist (0.275ms)
✔ R10 unexpected scheme: no connection outside the allowlist (0.180459ms)
✔ pinnedLookup connects to the pinned address and keeps the name (1.555708ms)
ℹ tests 12
ℹ pass 5
ℹ fail 7
Exit code: 1
Failure messages, in the order of the runner's failing tests list:
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 127.0.0.1:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 10.0.0.5:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 10.0.0.5:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 169.254.169.254:80
AssertionError [ERR_ASSERTION]: fetchUnsafe connected to 203.0.113.10:8080
==== READING THE TABLES ====
Table 2 is the allowlist verification table: one row per input class, with what the URL class reported (scheme, host and the port that will be used), what the lab's resolver answered when asked twice, and the redirect the unsafe run met.
GOT followed by a word: the fetcher delivered that response. PARTNER-IMAGE-OK and PARTNER-CDN-OK are the intended results. Any LAB-...-MARKER word means the request reached a stand-in internal service.
REFUSED (text): the URL text contained a blocked string.
REFUSED (host), (port) or (scheme): the parsed URL was not on the allowlist.
REFUSED (address): a name on the allowlist resolved to an address in a blocked range.
ERROR LAB_NO_SERVICE: the fetcher tried to connect to an address and port where the lab runs nothing. On a real network, that attempt is the request.
ERROR ERR_INVALID_PROTOCOL: node:http refused the scheme before connecting. That came from the HTTP module, not from a rule in the fetcher.
The regression test passes a fetcher only if every connection it attempts, on every row, is to 203.0.113.10:80 or 203.0.113.20:80, and the allowed URL still returns the partner image.
==== USING THE TEST ON YOUR OWN CODE ====
1. List every place your server fetches a URL that a user, a partner, a stored setting or a model can influence: link previews, webhooks and their test requests, imports from a URL, images and files by URL, document renderers, and integrations with an editable base address.
2. Give each one two parts a test can swap: the function that resolves names (dns.promises.lookup with all: true in production) and the connection (Node.js's own unless a test passes createConnection). The fetchers here take both from the run object.
3. Add your function to FETCHERS in fetchers.mjs and run ssrf.test.mjs with LAB_FETCHER set to its name.
4. Replace POLICY with your own allowlist. Add your real partner names to NAME_ANSWERS in lab-network.mjs, with documentation addresses standing in for them, and keep a row for every input class, so the test still covers loopback, link-local, private, another notation, a redirect, a rebinding name, a port and a scheme.
5. For a feature that uses https, set POLICY to https: and port 443. The lab's servers speak plain http, so the lab tests the checks, not TLS.
6. Keep the test in your suite, so a later change that loosens the allowlist, follows redirects again or resolves the name a second time fails a build instead of reaching production.What SSRF is
Server-side request forgery is a flaw in a feature that fetches something by URL.
MITRE catalogues it as CWE-918 and describes it this way: the web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
OWASP's Server-Side Request Forgery Prevention Cheat Sheet calls SSRF an attack vector that abuses an application to interact with the internal or external network or the machine itself, and names the mishandling of URLs as one of its enablers.
In plain terms, the attacker picks the address and your server makes the request. The request leaves from your server's place on the network, so it can reach what your server can reach. CWE-918 says that by providing URLs to unexpected hosts or ports, attackers can make it appear that the server is sending the request, possibly bypassing access controls such as firewalls that prevent them from reaching those URLs directly.
OWASP's API Security Top 10 entry, API7:2023 Server Side Request Forgery, says the flaw lets an attacker coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall or a VPN.
The request also carries your server's identity. On a cloud server that can be literal: when the server has a role attached, the metadata service described further down makes that role's temporary credentials available to software running on the machine, and an SSRF attack lets an outsider borrow that software.
OWASP's Top 10 now files SSRF under access control. Its 2025 introduction says Server-Side Request Forgery (SSRF) has been rolled into A01:2025 Broken Access Control, and CWE-918 is among the weaknesses A01:2025 maps. CWE-918's memberships also include A10:2021 Server-Side Request Forgery (SSRF), a category of the 2021 edition.
In ASVS 5.0, requirement 1.3.6, a Level 2 requirement in chapter V1, on encoding and sanitisation, asks that the application protects against SSRF attacks by validating untrusted data against an allowlist of protocols, domains, paths and ports and sanitising potentially dangerous characters before using the data to call another service.
API7:2023 is one entry in the OWASP API Security Top 10, which the API security guide in this library covers.
CWE-918 lists XSPA, short for Cross Site Port Attack, as an alternate term, and says the server can be used as a proxy to conduct port scanning of hosts in internal networks. That is one of several things an attacker can do with a server that fetches on request.
Where SSRF hides in ordinary features
Any feature in which your server fetches something on a user's behalf can carry SSRF.
OWASP's cheat sheet gives three examples: an avatar image the user supplies by URL for the application to download and use, a custom webhook where users specify handlers or callback URLs, and internal requests to interact with another service to serve a specific functionality.
API7:2023 names webhooks, file fetching from URLs, custom single sign-on and URL previews as features that encourage developers to access an external resource based on user input. Look for these in your own application:
- Link previews: a message, comment or listing that shows a card for a link pasted into it.
- Webhooks: the URL a customer enters to receive events, and any test request sent when they save it.
- Imports from a URL: a spreadsheet, calendar feed, product feed or document fetched from an address the user types.
- Images and files by URL: avatars, logos and attachments the server downloads, resizes or scans.
- Document renderers: HTML-to-PDF conversion and invoice generation. Where a server converts uploaded files to PDF, the WSTG test for SSRF suggests trying iframe, img, base or script elements, or CSS url() functions, that point to internal services.
- Integrations with an editable base address or callback URL stored in settings.
- AI features that fetch a page or file that a user or a model names. CWE-918 lists AI/ML among its applicable technologies with the note "often prevalent", and the LLM output handling guide in this library covers the model's side of it.
- Parsers that fetch on their own. The cheat sheet notes that an application vulnerable to XML external entity (XXE) injection can be exploited to perform an SSRF attack.
- Frameworks that make outbound requests for you. The Next.js guide in this library includes an SSRF advisory for Server Actions.
What your server can reach that an attacker cannot
The damage depends on what sits within your server's reach.
The WSTG test for SSRF, WSTG-INPV-19, says a successful attack can grant access to restricted actions, internal services or internal files within the application or the organisation, and in some cases can lead to remote code execution. CWE-918 lists reading application data, executing unauthorised code or commands, and bypassing protection mechanisms among its consequences.
- Services on the same machine. The WSTG's example uses the loopback interface to reach an admin page restricted to the host, and says trust relationships in which requests from the local machine are handled differently from ordinary requests are often what enables SSRF to be a critical vulnerability.
- Systems on your internal network. The WSTG describes back-end systems that users cannot reach directly. In its words, they often have non-routable private IP addresses and, because the network topology protects them, often lack more sophisticated controls.
- Ports and other protocols. CWE-918 says the server can be used to port scan internal hosts, to access documents on the system with file:// URLs, or to use other protocols such as gopher:// or tftp://. In the first scenario of API7:2023, an attacker supplies a profile picture URL and works out from the response time whether an internal port is open.
- Other people's systems. API7:2023 says successful exploitation can, in some cases, lead to denial of service or the server being used as a proxy to hide malicious activities.
Cloud metadata services and SSRF
Cloud servers can ask a metadata service about themselves. Amazon's EC2 documentation describes instance metadata as data about an instance that you can use to configure or manage it. The service answers at 169.254.169.254 over IPv4 and, where its IPv6 address is enabled on a Nitro-based instance in an IPv6-supported subnet, at fd00:ec2::254.
When an IAM role is associated with the instance, the iam/security-credentials category holds the temporary security credentials associated with that role.
AWS says the data can only be accessed from within the instance itself, but is not protected by authentication or cryptographic methods, and that anyone with direct access to the instance, and potentially any software running on it, can view its metadata.
A fetch feature is software running on the instance. OWASP's cheat sheet says that in cloud environments SSRF is often used to access and steal credentials and access tokens from metadata services, and names the AWS and Azure Instance Metadata Services and the GCP metadata server.
The second scenario in API7:2023 ends this way: a webhook's test request is pointed at an internal cloud metadata service, and because the application shows the response, the attacker can view the cloud environment's credentials.
API7:2023 adds that cloud providers, Kubernetes and Docker expose management and control channels over HTTP on predictable, well-known paths, which it calls an easy target for an SSRF attack. What the hardened version of the AWS service requires is covered under network controls below.
Why checking the hostname text is not enough
A tempting first fix is to read the URL text and refuse anything that mentions localhost, 127. or 169.254.
The lab on this page includes that fix as fetchWithTextFilter. It stopped the three rows that spell out a blocked address and let three others reach a stand-in internal service. Each of those rows shows a separate gap between the text a user typed and the address your server finally connects to, and a fourth gap appears only once the name is checked properly.
Node.js documents its URL class as implementing the same WHATWG URL Standard that web browsers use. Under that standard, a host that ends in a number is handed to the IPv4 parser, which returns either an IPv4 address or failure.
A part that starts with 0x is read as hexadecimal and a part with a leading zero as octal, fewer than four parts are allowed with the last number supplying the remaining bytes, and the result is written out as four decimal numbers.
Row R6 of the lab asked for http://2852039166/metadata. The URL class reported the host as 169.254.169.254, the text filter found nothing to object to, and the request reached the stand-in metadata service.
The WSTG lists alternative IP representations among the common filter bypasses, and CWE-918's observed examples include an SSRF protection bypassed because incorrect validation of the intended decimal IP address format allowed octal and hexadecimal formats to be parsed. The fix is to parse once and check what the parser produced, then pass that same parsed object to the code that makes the request.
OWASP's cheat sheet adds a rule for a URL that crosses a service boundary as a string: reject a URL whose host is not read identically by every parser in play, rather than reconciling the readings.
In Node.js, that rules out the legacy url.parse() for this job. Its documentation says it uses a lenient, non-standard algorithm, is prone to security issues such as host name spoofing, and should not be used with untrusted input.
Row R5 asked for files.partner.test, a name on the lab's allowlist whose record points at 10.0.0.5, a private address. Nothing in the text looks internal, so the text filter fetched the stand-in internal admin page. Only resolving the name shows where it leads, and the cheat sheet says to validate the resolved destination IP addresses against the application's permitted networks.
Check every address, not only the first. The Node.js documentation says dns.lookup() resolves a host name into the first found A or AAAA record unless the all option is true, in which case it returns every address in an array. It also says dns.lookup() does not necessarily have anything to do with the DNS protocol, because it uses an operating system facility that associates names with addresses.
The lab's two checked fetchers take every answer and refuse the request if any one of them falls in a blocked range.
DNS rebinding works in the gap between checking a name and using it. The cheat sheet says domain allowlisting alone does not prevent DNS rebinding, and that a second, unchecked DNS lookup between validation and connection can bypass the checks. Row R8 uses the lab's rebinding fixture, a fake resolver that answers cdn.partner.test with a partner address the first time and with the stand-in metadata address every time after. fetchCheckedOnce resolved the name, checked the answer and approved it, then handed the URL to an ordinary HTTP client. That client resolved the name again and fetched LAB-METADATA-MARKER.
The fix is to connect to the address you checked. The cheat sheet asks for an HTTP client that connects to the validated IP while keeping the original hostname for the Host header, TLS Server Name Indication and certificate verification, with the same destination policy applied to retries and fallback connections.
In Node.js, http.request() and socket.connect() both accept a lookup option, a custom lookup function that otherwise defaults to dns.lookup(). The lab's pinnedLookup() answers every call with the address already checked. The documentation says the all option passed to lookup is set to true when autoSelectFamily is enabled, so the function answers in both shapes.
One test in the lab runs it through Node.js's own connection code: a made-up name pinned to 127.0.0.1 connected there, and the server received the name in its Host header.
An allowed host can answer with a redirect to somewhere that is not allowed. Under the Fetch Standard, a request's redirect mode is "follow" unless stated otherwise, and "follow" follows all redirects incurred when fetching a resource. The "error" mode returns a network error when a request is met with a redirect, and the standard stops with a network error once the redirect count reaches 20.
Node.js describes its global fetch() as a browser-compatible implementation. In the lab, on Node.js 26.0.0, fetch() with no redirect option followed a redirect from one loopback server to another that returns LAB-METADATA-MARKER, and came back with that word. With redirect: 'error', the same request threw TypeError: fetch failed, with the cause unexpected redirect.
Row R7 shows the same problem behind an allowlist. images.partner.test is allowed, and its /go path redirects to 169.254.169.254. fetchCheckedOnce checked the first URL only, followed the redirect and returned the metadata marker. fetchChecked treats each hop as a new request: it parsed the Location URL, ran every check again and refused at hop 2, because the host is not on the allowlist.
OWASP's cheat sheet and API7:2023 both say to disable redirect following. Re-checking every hop, with a small hop limit, is the alternative for a feature that needs redirects.
An open redirect on an allowed partner's site becomes a route past your allowlist in exactly this way; the open redirects guide in this library covers finding and fixing them on your own site.
Row R9 kept the allowed host and asked for port 8080. Every fetcher without a port check tried to connect there. In the lab nothing answered, but on a real network that attempt is the request, and API7:2023's first scenario reads open ports from response times. Compare the port the request will actually use.
The Node.js documentation says the URL class reports an empty port when the URL uses the default for its scheme, 80 for http and 443 for https, so a rule that compares the port text with "443" refuses an ordinary https URL.
Row R10 used file:. Node.js's http module refused it with ERR_INVALID_PROTOCOL before connecting. That refusal came from the HTTP module, not from any rule in the fetcher, so it would change with the client. OWASP's cheat sheet says SSRF is not limited to HTTP, and CWE-918 names file://, gopher:// and tftp://. Allow the schemes you mean to use and refuse the rest by name.
SSRF prevention: an allowlist enforced at the connection
The lab's fetchChecked is the pattern to copy.
Each step below closes one of the gaps above, and each one is something a code review can point to.
- Take less than a URL where you can. The cheat sheet says not to accept complete URLs from the user, because URLs are difficult to validate and the parser can be abused depending on the technology used. Where network information is needed, accept only a valid IP address or domain name, match it against an allowlist and build the request from the matching entry, with a scheme, port and path the application fixes itself. A webhook form that stores a partner ID and looks up the partner's endpoint does not parse a customer's URL.
- Allow named schemes, hosts and ports, and compare against exact entries rather than testing whether the text contains or ends with something. ASVS 5.0 requirement 1.3.6 lists protocols, domains, paths and ports. API7:2023 adds the remote origins users are expected to download resources from, and the media types each feature accepts.
- Parse once with the WHATWG URL class, check what it reports, and pass the parsed object on. Refuse anything it rejects, and refuse a URL that another component in the chain would read differently.
- Resolve the name yourself and check every address it returns, with dns.promises.lookup() and all: true in Node.js. Refuse the request if any one address falls in a blocked range, even for a name on your allowlist.
- Connect to the address you checked, by passing a lookup function that returns it, as pinnedLookup() does, so the connection cannot resolve the name again.
- Check every redirect or refuse them. Pass redirect: 'error' to fetch(), or follow redirects in your own loop and run every check again on each Location, with a small hop limit.
- Return only what the feature needs. API7:2023 says not to send raw responses to clients. An avatar fetcher can check that it received an image and return only the resized copy, and a webhook test can report success or failure without echoing the body.
- Keep error messages plain. A refusal that names the internal address it met tells an attacker what is inside your network. The lab's fetchers return their reasons so the table can print them; a real feature logs the detail on the server and returns a general failure.
- Run the fetching where it can reach little. API7:2023 says to isolate the resource fetching mechanism in your network, since these features are usually aimed at remote resources and not internal ones.
What a blocklist cannot do that an allowlist can
Some features cannot name their destinations in advance.
OWASP's cheat sheet separates two cases: an application that sends requests only to identified and trusted applications, where an allowlist is available, and one that can send requests to any external IP address or domain name, such as a webhook to whatever endpoint a customer runs, where it is not.
For the second case it says a block-list is not an impenetrable wall but is the best solution in that scenario. Its deny-list section opens with "Deny-lists are bypass-prone. Prefer allow-lists." CWE-918 rates a denylist that includes private network addresses and internal domain names as moderately effective, and notes that while denylists can often be bypassed, this might be the strongest option available for a product that must connect to arbitrary destinations.
The difference is what each list has to know. A blocklist has to name every destination your server must never reach: every private and special range in both IPv4 and IPv6, and every internal name. Anything missing from it is allowed. An allowlist names the few destinations the feature exists to reach, so an address nobody thought to list is refused, and the feature cannot be pointed at somebody else's systems at all.
In the lab, fetchChecked's allowlist refused rows R2, R3, R4, R6, R9 and R10 before any name was resolved.
An allowlist still needs the range check underneath it. Row R5 is a name on the allowlist whose record points at a private address, and only the address check refused it. The ranges for that check come from IANA's special-purpose address registries. The IPv4 registry lists 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16 as Private-Use under RFC 1918, 127.0.0.0/8 as Loopback, 169.254.0.0/16 as Link Local under RFC 3927, 100.64.0.0/10 as Shared Address Space and 0.0.0.0/8 as "This network".
The IPv6 registry lists ::1/128 as the loopback address, fe80::/10 as Link-Local Unicast, fc00::/7 as Unique-Local and ::ffff:0:0/96 as IPv4-mapped addresses.
The cheat sheet's minimum list also blocks multicast and the NAT64 translation prefixes, and says to normalise addresses before comparing, because an IPv4-mapped address reaches the same host as its IPv4 form.
In Node.js, net.BlockList holds the ranges. Its documentation shows that IPv6 notation for IPv4 addresses works when the address is checked with the type ipv6, and the type defaults to ipv4, so pass it. The lab's isBlockedAddress() does, and its output shows ::ffff:169.254.169.254 and fd00:ec2::254 blocked alongside the IPv4 forms.
From version 26.8.0 the documentation lists BlockList.PRIVATE_RANGES, eight ranges covering the RFC 1918 blocks, loopback and link-local in IPv4 and IPv6, and fc00::/7. That is a starting point rather than the cheat sheet's full minimum, which also includes 0.0.0.0/8, multicast and the NAT64 prefixes.
Where a feature must reach any public address, keep everything else from fetchChecked: parse once, check every resolved address against the blocked ranges, connect to the checked address, refuse or re-check redirects, and allow only http: and https: on the ports you expect.
For that case the cheat sheet also describes a way for the receiving system to prove the call was legitimately initiated: it generates a random token that the caller must pass back, and its receiving endpoint accepts only POST requests.
What network controls add
Code checks decide what the feature asks for.
Network controls decide what the server can reach whatever the code asks. OWASP's cheat sheet hardens both layers as defence in depth. At the network layer, only the routes the application should use stay available, with a firewall, either a specific device or the one in the operating system, defining the legitimate flows, and it calls network segregation highly recommended to block illegitimate calls at network level.
CWE-918 says an allowlist of permitted destinations could live in the application code or be enforced by firewalls or network segmentation.
Egress rules and where the fetcher runs
An egress rule is an allowlist the network enforces. Run the fetching code as its own process or service, give it outbound access to the destinations it needs, and keep the metadata address, internal ranges and neighbouring services off its routes.
API7:2023 warns that limiting outbound traffic from an application has become more challenging because of the connected nature of modern applications, which is an argument for isolating the fetcher rather than locking down the whole server.
A web application firewall sits on the other side of the server. It sees the request coming in, and in row R8 that request named only cdn.partner.test; the metadata address appeared later, inside the server, when the name was resolved a second time.
A rule that looks for internal addresses in parameters is a blocklist on text, with the gaps the lab shows. The web application firewall guide in this library covers what one is good for.
Harden the metadata service as your provider documents
AWS offers two ways to reach instance metadata: IMDSv2, which is session-oriented, and IMDSv1, a request and response method. Its documentation says an IMDSv2 request starts with a PUT request that returns a token, and every GET must carry that token; when token use is set to required, a request without a valid token gets a 401 Unauthorized error.
A PUT request that contains an X-Forwarded-For header is rejected, and by default the response to the PUT has a hop limit of 1 at the IP protocol level. Each instance can be configured to accept only IMDSv2 calls, which makes IMDSv1 calls fail.
OWASP's cheat sheet calls IMDSv2 an additional defence-in-depth mechanism for AWS that mitigates some of the instances of SSRF, and recommends migrating to it and disabling IMDSv1. With token use required, a forged GET without a token gets a 401 instead of metadata, but the forged request still leaves your server, so the fixes in the code still matter.
AWS also says not to store sensitive data such as passwords or long-lived encryption keys as user data, because potentially any software running on the instance can view it.
Other providers document their own metadata services and settings, so check yours. A metadata setting left more permissive than anything on the server needs is the kind of finding the security misconfiguration guide covers.
Walking through the egress lab
The lab is an illustration written for this page, not a client's code.
It builds a small stand-in network on your own computer: five local servers on 127.0.0.1, each standing in for an address such as a partner's image server, an internal admin page or a cloud metadata service, plus two more for the fetch() check.
The metadata stand-in returns one fixed word, LAB-METADATA-MARKER. A transport handed to Node.js's http module connects each request to the matching local server and records the address and port it was meant for, so no request leaves the machine.
Names are answered by a fake resolver inside the lab, never by DNS, and the partner addresses come from 203.0.113.0/24, which IANA's IPv4 registry lists as Documentation under RFC 5737.
Four fetchers and ten rows
Four fetchers take the same ten inputs. fetchUnsafe fetches anything and follows redirects. fetchWithTextFilter refuses text that contains a blocked address, then behaves like fetchUnsafe. fetchCheckedOnce parses the URL, applies the allowlist, resolves the name and checks every address, then hands the original text to the same client as fetchUnsafe. fetchChecked does all of that on every hop and connects to the address it checked.
Table 2 of the output is the verification table: for each row, what the URL parser reported, what the name resolved to, the port that would be used and the redirect the unsafe run met. Table 3 shows what each fetcher did. fetchUnsafe reached a stand-in internal service in six of the ten rows and tried port 8080 in a seventh. fetchWithTextFilter refused three rows, reached an internal stand-in in three more and tried port 8080. fetchCheckedOnce refused seven rows and reached the metadata marker twice, through the redirect and the rebinding name. fetchChecked returned the partner image and the partner CDN response and refused the other eight rows: six at the allowlist, one at the address check and one at the second hop.
The regression test
ssrf.test.mjs runs twelve tests against the fetcher LAB_FETCHER names: the allowed URL still returns the partner image, each of the ten rows connects to nothing outside the two allowed partner addresses, and the pinned lookup works through Node.js's own connection code.
On Node.js 26.0.0, fetchChecked passed all twelve and the run exited with code 0. fetchCheckedOnce failed two, fetchWithTextFilter four and fetchUnsafe seven, and each of those runs exited with code 1, which the Node.js documentation says happens when any test fails.
Each failure names the address the fetcher connected to, such as fetchCheckedOnce connected to 169.254.169.254:80. Because the test counts connection attempts rather than responses, it also fails a fetcher that only tried a port, as in row R9.
SSRF testing in the code and on a running build
The WSTG test for SSRF, WSTG-INPV-19, has three objectives: identify SSRF injection points, test whether they are exploitable, and assess the severity.
Its remediation note says SSRF is known to be one of the hardest attacks to defeat without allow lists that require specific IPs and URLs to be allowed.
In the code, start from the outbound calls rather than the inputs. List every place the server makes a request: fetch(), http and https requests, HTTP client libraries, SDKs that take a base URL, headless browsers and document renderers, and XML parsers that resolve external entities.
For each one, trace where the scheme, host, port and path come from, and whether redirects are followed. CWE-918 says automated static analysis can find some instances of the weakness, typically by modelling data flow and control flow and searching for patterns that connect sources of input with sinks, and rates its effectiveness as High. A request made inside a library is still a sink to trace.
Against a running build, show that the server will make a request to a destination of your choosing, and ask it for nothing sensitive. Point the feature at a listener you control that records the request and returns a harmless word, as the lab's stand-ins do, never at a real metadata service or a system that belongs to someone else, and test only an application you own or are authorised in writing to test.
The evidence is the request arriving at your listener.
Then turn each confirmed case into a regression test like ssrf.test.mjs, so a later change that loosens the allowlist fails a build.
Remember inputs that do not look like URLs. The WSTG says the payloads can also be injected into header and cookie values, and the same test applies to a host name, port or path kept in settings that your server later builds into a URL.
For blind cases, API7:2023 says that, in general, basic SSRF, where the response comes back to the attacker, is easier to exploit than blind SSRF, where the attacker has no feedback. The WSTG says SSRF through POST requests may be blind, because the application may not return anything immediately and the injected data may instead be used in other functionality, for example PDF reports or invoice and order handling. A listener you control shows the request either way.
How SSRF fits a Clever Ops web application test
A web application and API penetration test works through the application and the API behind it in each role the scope names, so a feature that fetches by URL is examined when it is in scope.
Testing follows the same rules as any Clever Ops test: each finding is confirmed with the least intrusive proof available, and destructive actions are off by default for real people's accounts and for records that existed before the test.
Read-only code access to named areas, such as a webhook handler or an import job, can be added to the scope, and a finding that rests on the code alone says so.
Internal networks, servers and staff devices are not part of any Clever Ops service, so testing what sits behind your application goes to a network specialist. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it. A report is evidence for your own decisions, not a certificate.
Frequently asked questions
It is a way of getting your server to make a request for someone else. A feature that fetches a URL, such as a link preview or a webhook, is handed an address the attacker chose, and the server fetches it from its own place on the network. CWE-918 describes the weakness as a server that retrieves the contents of a URL without sufficiently ensuring the request is being sent to the expected destination.
Yes, inside a broader category. The OWASP Top 10:2025 introduction says Server-Side Request Forgery has been rolled into A01:2025 Broken Access Control, and CWE-918 is among the weaknesses A01:2025 maps. The OWASP API Security Top 10 2023 keeps it as its own entry, API7:2023 Server Side Request Forgery.
Not on its own. It changes what a forged request can get from the AWS metadata service: with token use required, AWS says a request without a valid session token receives 401 Unauthorized, and the token comes from a PUT request that is rejected if it carries an X-Forwarded-For header. OWASP calls IMDSv2 an additional defence-in-depth mechanism that mitigates some of the instances of SSRF. The forged request still leaves your server, so the allowlist and connection checks are still needed.
Not on its own. OWASP's cheat sheet says deny-lists are bypass-prone and to prefer allow-lists, and CWE-918 notes that denylists can often be bypassed. In the lab, a filter on the URL text missed an address written as one number, a partner name pointing at a private address, and a redirect. Check the resolved addresses rather than the text, connect to the address you checked, and use an allowlist wherever the feature's destinations are known.
It can only judge what is in the incoming request. In the lab's rebinding row, the request named a partner host, and the metadata address appeared only when the server resolved the name a second time. A firewall rule that looks for internal addresses in parameters is a text blocklist, with the gaps the lab shows. Fix the fetching code, and limit outbound traffic at the network.
Show that the server will make a request to a destination you choose, and stop there. Point the feature at a listener you control that returns a harmless word, never at a real metadata service or someone else's system, and test only applications you own or are authorised in writing to test. The lab on this page does the same thing on one computer, with stand-in addresses that reach local servers only.
SSRF in which the attacker never sees the response. API7:2023 says that, in general, it is harder to exploit than basic SSRF, and describes blind SSRF as SSRF in which the attacker has no feedback on whether the attack was successful. The WSTG says SSRF through POST requests may be blind, because the application may not return anything immediately and the injected data may instead be used in other functionality, for example PDF reports or invoice and order handling. The server still makes the request, so the same fixes apply.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.