Security

Preventing SSRF in APIs That Fetch URLs

How server-side request forgery reaches cloud metadata and internal services, why blocklists of strings fail, and a layered defence with Node.js code.

By the APIStack team··9 min read

A padlock resting on a laptop keyboard lit in red and green

Any service that fetches a URL supplied by a user can be turned into a proxy into its own network. Webhook senders, link previews, screenshot and PDF renderers, metadata extractors and "import from URL" features all share the problem, which is called server-side request forgery (SSRF).

This article is for developers who run such a service. It explains what an attacker can reach, why the obvious defence of rejecting bad-looking URLs does not work, and how to build a defence in layers. It ends with a compact guarded fetch for Node.js.

What SSRF reaches

Your server sits inside a network that the public internet cannot see. When it makes a request on a user's behalf, the request comes from inside. The user chooses the destination; your server supplies the network position and often the credentials. OWASP gave the problem its own category in the 2021 Top 10, which describes the consequences.

The most valuable target is the cloud metadata service. On AWS, Google Cloud and Azure, every virtual machine can read its own configuration from the link-local address 169.254.169.254, and that configuration includes temporary credentials for the machine's role. On an AWS instance that still allows the original metadata protocol, a fetch of http://169.254.169.254/latest/meta-data/iam/security-credentials/ through a vulnerable preview endpoint lists the role, and one more request returns its keys.

Beyond metadata, the same request can reach admin interfaces bound to localhost, databases and caches that trust the private network, internal HTTP services with no authentication, and other hosts that can be mapped by timing which addresses answer. Even when the response body is never shown to the user, a blind SSRF can still trigger actions on internal systems.

Why string blocklists fail

The first instinct is to reject URLs that contain localhost, 127.0.0.1 or 169.254.169.254. This checks the text of the URL, but the network stack acts on what the text resolves to, and many texts lead to the same address.

Alternate encodings of one address

An IPv4 address does not have to be written as four decimal numbers. http://2130706433/, http://0x7f.1/ and http://017700000001/ all mean 127.0.0.1: the WHATWG URL standard's IPv4 parser accepts decimal, hexadecimal and octal parts and fewer than four of them. A filter that compares strings sees none of these as loopback.

IPv6 adds more spellings. [::1] is loopback. [::ffff:169.254.169.254] is an IPv4-mapped IPv6 address that reaches the IPv4 metadata service on a dual-stack host, and it can also be written [::ffff:a9fe:a9fe]. Addresses in NAT64 and 6to4 ranges can embed an IPv4 address in the same way. AWS additionally serves metadata over IPv6 at fd00:ec2::254.

Names that resolve to private addresses

A hostname carries no information about where it points. Anyone can publish a DNS record for internal.example.com with the value 10.0.0.5 or 127.0.0.1. A check that looks only at the hostname passes it, and the HTTP client then connects to your private network.

Redirects

A URL can pass every check and then answer with 302 Location: http://169.254.169.254/. An HTTP client that follows redirects automatically never shows the second URL to your validation code.

DNS rebinding

Checking the resolved address is necessary but leaves a gap between the check and the connection. If your code resolves the name to validate it and the HTTP client resolves it again to connect, an attacker who controls the DNS server can answer the first query with a public address and the second with a private one. A record with a very short lifetime makes this reliable.

A defence in layers

The OWASP SSRF Prevention Cheat Sheet separates two cases. If your service only ever needs to call a known set of hosts, use an allowlist and stop there. If it must fetch arbitrary URLs, as a webhook sender or link preview does, an allowlist is impossible and you need every layer below. OWASP is explicit that a denylist alone is not a complete solution, which is why the later layers matter.

Parse and normalise

Parse the URL once with a standards-compliant parser and use only the parsed result from then on. In Node.js, new URL() normalises the alternate IPv4 encodings: the hostname of http://0x7f.1/ is reported as 127.0.0.1. Reject anything that fails to parse, and reject URLs that carry a username or password.

Restrict schemes and ports

Allow http: and https: only. Other schemes, such as file:, gopher: and ftp:, give an attacker access to local files or let them speak other protocols to internal services. Limit ports to the few that public web servers use, so the fetcher cannot be used to probe SSH, databases or mail servers.

Resolve and check every address

Resolve the hostname yourself and test every returned address, both IPv4 and IPv6, against the ranges that must never be reached. A name can have several records, and one private address among public ones is enough for an attack. The main ranges come from the IANA IPv4 special-purpose address registry and its IPv6 counterpart:

RangePurpose
127.0.0.0/8, ::1Loopback
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16Private networks
169.254.0.0/16, fe80::/10Link-local, including cloud metadata
100.64.0.0/10Carrier-grade NAT shared space (RFC 6598)
fc00::/7IPv6 unique local, including fd00:ec2::254
0.0.0.0/8, 224.0.0.0/3, ff00::/8Unspecified, multicast and reserved

Normalise IPv4-mapped IPv6 addresses to IPv4 before comparing, and treat NAT64 (64:ff9b::/96) and 6to4 (2002::/16) addresses as suspect, since they can wrap a private IPv4 address.

Pin the resolved address

Connect to the exact address you checked. In practice this means giving the HTTP client a custom DNS lookup function that returns only the validated addresses, while the URL keeps its hostname so that the Host header, TLS server name and certificate validation still work. This closes the DNS rebinding gap.

Re-check each redirect hop

Turn off automatic redirects. When a response is a redirect, resolve the Location against the current URL, run the new URL through the same parse, resolve, check and pin steps, and cap the number of hops.

Cap size and time

A fetcher is also a target for resource exhaustion. Set one deadline for the whole operation including redirects, and stop reading once the body passes a byte limit. Do not trust Content-Length; count the bytes as they arrive.

Control egress at the network level

Application checks can have bugs, so add a layer that does not depend on them. Run the fetcher in a subnet or container whose firewall rules deny traffic to private ranges and to the metadata address, or route its traffic through an egress proxy that enforces the same policy. Give the fetching component the smallest role you can, so that leaked credentials are worth little.

Require IMDSv2

On AWS, switch instances to Instance Metadata Service Version 2 and disable version 1. As the EC2 documentation describes, IMDSv2 requires a session token obtained with a PUT request and sent in a header on each read, and it rejects token requests that carry an X-Forwarded-For header. A typical SSRF bug lets the attacker choose only the URL of a GET, which is not enough to get a token. Google Cloud and Azure protect their metadata servers with a required request header instead: Metadata-Flavor: Google and Metadata: true.

A guarded fetch in Node.js

The following module puts the application layers together using only Node's standard library. It builds the range list with net.BlockList, which also matches IPv4-mapped IPv6 addresses against the IPv4 rules.

JavaScript
import dns from 'node:dns/promises'
import http from 'node:http'
import https from 'node:https'
import net from 'node:net'

const blocked = new net.BlockList()
for (const [prefix, bits] 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', 3]
]) blocked.addSubnet(prefix, bits, 'ipv4')
for (const [prefix, bits] of [
    ['::', 96], ['::ffff:0:0:0', 96], ['64:ff9b::', 96], ['2001::', 32], ['2001:db8::', 32],
    ['2002::', 16], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]
]) blocked.addSubnet(prefix, bits, 'ipv6')

function checkUrl(input) {
    const url = new URL(input)
    if (!['http:', 'https:'].includes(url.protocol)) throw new Error('Only http and https are allowed')
    if (url.username || url.password) throw new Error('Credentials in URLs are not allowed')
    if (url.port && !['80', '443', '8080', '8443'].includes(url.port)) throw new Error('Port not allowed')
    return url
}

// Resolve once, refuse if any answer is non-public, and return the checked records
async function resolvePublic(hostname) {
    const host = hostname.replace(/^\[|\]$/g, '')
    const family = net.isIP(host)
    const records = family ? [{ address: host, family }] : await dns.lookup(host, { all: true })
    const bad = (r) => blocked.check(r.address, r.family === 6 ? 'ipv6' : 'ipv4')
    if (!records.length || records.some(bad)) throw new Error('Destination is not a public address')
    return records
}

The second half makes the request. The lookup option is the pin: whatever the socket asks, it is given only the records that were just checked. Redirects are never followed by the client; the loop validates each new URL itself.

JavaScript
function requestPinned(url, records, { signal, maxBytes }) {
    const lookup = (_host, options, callback) =>
        options.all ? callback(null, records) : callback(null, records[0].address, records[0].family)
    return new Promise((resolve, reject) => {
        const client = url.protocol === 'https:' ? https : http
        const req = client.get(url, { lookup, signal }, (res) => {
            const chunks = []
            let size = 0
            res.on('data', (chunk) => {
                size += chunk.length
                if (size > maxBytes) req.destroy(new Error('Response too large'))
                else chunks.push(chunk)
            })
            res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) }))
        })
        req.on('error', reject)
    })
}

export async function guardedGet(input, { maxRedirects = 5, timeoutMs = 10_000, maxBytes = 2 * 1024 * 1024 } = {}) {
    const signal = AbortSignal.timeout(timeoutMs)
    let url = checkUrl(input)
    for (let hop = 0; hop <= maxRedirects; hop++) {
        const records = await resolvePublic(url.hostname)
        const res = await requestPinned(url, records, { signal, maxBytes })
        const location = [301, 302, 303, 307, 308].includes(res.status) && res.headers.location
        if (!location) return { url: url.href, ...res }
        url = checkUrl(new URL(location, url).href)
    }
    throw new Error('Too many redirects')
}

Called with http://2130706433/, http://[::ffff:169.254.169.254]/ or a hostname whose DNS record points at 10.0.0.5, guardedGet throws before any connection is made. Called with a public URL that redirects, it checks each hop and returns the final response.

Two limits of this example are worth knowing. It covers GET only; forwarding other methods means deciding which headers and bodies survive a redirect, and credentials should never be forwarded to a different origin. And it does not help with a headless browser: a page rendered for a screenshot or PDF loads sub-resources and follows redirects on its own, so there you need request interception that applies the same address check to every request the page makes.

APIStack's own APIs that fetch user-supplied URLs resolve and check the destination in this way before every request and every redirect hop.

Summary

  • SSRF turns a URL-fetching feature into access to your private network, and the cloud metadata service at 169.254.169.254 is the usual first target.
  • Checking the URL as a string fails: alternate IP encodings, IPv4-mapped IPv6, DNS names with private records, redirects and DNS rebinding all get past it.
  • Validate the address, not the text. Resolve the host, check every address against the special-purpose ranges, connect only to an address you checked, and repeat for each redirect.
  • Allow only http and https on a few ports, and cap total time, body size and redirect count.
  • Add layers that do not depend on your code: network egress rules, least-privilege roles and IMDSv2 on AWS.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading