Your server has access your users don't: to the database, to the internal admin panel, and to the cloud access keys. As long as the server only sends requests to addresses you chose, all of that stays safe inside. The trouble starts when that address comes from user input.
That hole is called SSRF (Server-Side Request Forgery): an attacker can make your server send a request to an address the attacker picks. Picture an office receptionist who will fetch things from any address you write on a slip. You write "the directors' archive room, 5th floor". You aren't allowed in there yourself. But the receptionist is an insider, so the doors open for them, and they bring you what's inside. In SSRF, the receptionist is your server, the slip is the URL the attacker sends, and the archive room is an internal service that can only be reached from inside.
Why the server becomes a weapon
Features that fetch a URL from the user are everywhere: link previews, an avatar from a URL, and webhooks (automatic requests to a customer's URL). The vulnerable version looks like this:
app.post('/fetch-preview', async (req, res) => {
const response = await fetch(req.body.url) // VULNERABLE: a URL from the user, fetched as it is
res.send(Buffer.from(await response.arrayBuffer()))
})
The server fetches req.body.url (the URL in the request body) as it is, then sends what it receives to the user. A server usually also sits on an internal network that the internet can't reach. Through SSRF, the attacker borrows the server's position to reach three kinds of targets:
- Cloud metadata at
169.254.169.254: a special address inside an AWS, GCP or Azure machine that tells the machine about itself. That information includes temporary IAM credentials (access keys to the cloud services). - Internal services on
localhost(the server machine itself) or a private IP (an address on the internal network): Redis, Elasticsearch or admin panels. These services often have no password because they're "only reachable from inside". - Schemes other than http: the scheme (protocol) is the start of the URL, before
://.file:///etc/passwdreads a file on that server if the HTTP library supportsfile://. cURL in PHP does, while Node's built-infetchrefuses it.
Say your server runs on AWS EC2 (a rented server at AWS) with IMDSv1 (the old metadata service, explained below). The preview feature above receives http://169.254.169.254/latest/meta-data/iam/security-credentials/. The answer is the machine's IAM role name (the name of its set of permissions). One more request to .../security-credentials/<role-name> returns temporary AWS credentials: AccessKeyId, SecretAccessKey and Token. This is exactly what happened in the Capital One breach in 2019. The attacker used SSRF through a misconfigured WAF (web application firewall), took the credentials from the metadata, then downloaded the data of about 106 million people from S3 (AWS file storage).
Reading a URL with new URL
Don't check a URL by searching its text. Let new URL() split it into parts, exactly the way fetch will read it later. This table shows the two parts that get checked: protocol and hostname (the host's name):
| URL | protocol |
hostname |
|---|---|---|
https://images.cdn.com/pic.jpg |
https: |
images.cdn.com |
http://images.cdn.com/pic.jpg |
http: |
images.cdn.com |
https://evil.com/x |
https: |
evil.com |
file:///etc/passwd |
file: |
(empty) |
https://IMAGES.CDN.COM/x |
https: |
images.cdn.com |
not-a-url |
throws TypeError: Invalid URL |
protocolalways ends with a colon:'https:', not'https'.- For
httpandhttps, the parser (the code that splits the URL) has already lowercased thehostname. - Text that isn't a full URL makes
new URLthrow an error, so wrap it intry...catch.
Allowlist: the most effective fix
The function isUrlSafeForFetch below only lets through https: URLs whose host is on the list. The handler fetches only a URL that passes:
function isUrlSafeForFetch(url, allowlist) {
try {
const parsed = new URL(url)
if (parsed.protocol !== 'https:') return false // refuse http:, file:, gopher:, etc.
const host = parsed.hostname.toLowerCase()
return allowlist.some((h) => h.toLowerCase() === host)
} catch {
return false // not a valid URL
}
}
const ok = ['images.cdn.com', 'storage.googleapis.com']
app.post('/fetch-preview', async (req, res) => {
if (!isUrlSafeForFetch(req.body.url, ok)) return res.status(400).send('URL not allowed')
const response = await fetch(req.body.url, { redirect: 'error' })
res.send(Buffer.from(await response.arrayBuffer()))
})
These are the results of isUrlSafeForFetch for each URL from the table above, with the ok list in the code:
url |
The step that stops it | Result |
|---|---|---|
https://images.cdn.com/pic.jpg |
passes every step | true |
http://images.cdn.com/pic.jpg |
protocol http: |
false |
https://evil.com/x |
evil.com isn't on the allowlist |
false |
file:///etc/passwd |
protocol file: |
false |
not-a-url |
new URL throws, lands in catch |
false |
https://IMAGES.CDN.COM/x |
passes every step, its host is images.cdn.com |
true |
- An allowlist is a list of the hosts that are allowed. Everything not on it is refused, including internal addresses nobody thought of.
- Compare the hostname with
===, notincludesorendsWith. Upper and lower case mean the same in a hostname, so make them the same first withtoLowerCase(). - A
catchwith no variable (catch {) is fine in modern JavaScript. Here that block only returnsfalse.
Extra layers
redirect: 'error': a host that passes the allowlist can answer with a302(a redirect, "go to another address") tohttp://169.254.169.254/.... With this option,fetchfails right away instead of going to that address.- Block private IPs when an allowlist isn't possible, for example for webhooks to customers' URLs. Resolve the hostname (ask DNS for all of its IPs), then refuse it if even one is not a public address, IPv4 or IPv6. The list of address ranges
127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16and169.254.0.0/16is not enough.0.0.0.0also reaches localhost, and IPv6 addresses such as::1and::ffff:169.254.169.254are not covered. So don't write the list yourself. Use a library, such as ipaddr.js, and accept an IP only whenrange()is'unicast'(an ordinary public address). Then send the request to that resolved IP, so the hostname can't switch to another IP between the check and the request. The attack that uses that switch is called DNS rebinding. - An outbound (egress) firewall: at the network level, the application server may only reach the destinations it actually needs.
IMDSv1 vs IMDSv2
IMDS is the metadata service on EC2. IMDSv1 answers one plain GET, so a single SSRF is enough. IMDSv2 requires a session token (a temporary IMDS token, not a login session). You get the token first with a PUT, then send it in a header on every GET:
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/
Most SSRF bugs can only send a GET with no extra headers, so they can't get the token. A GET without a token to an instance (an EC2 machine) that requires IMDSv2 gets 401 Unauthorized. Require IMDSv2 with the command aws ec2 modify-instance-metadata-options --instance-id i-xxx --http-tokens required.
⚠️ How an allowlist still gets fooled
- Matching text instead of the parsed result.
url.includes('images.cdn.com')orstartsWith('https://images')can be fooled by a URL that only looks similar. Parse withnew URL, then comparehostnamewith===. - Forgetting the protocol check. The right host over
http:orfile:must still be refused. - Forgetting upper case.
IMAGES.CDN.COMis the same host. Make it lowercase withtoLowerCase(). - Following redirects. The check at the start means nothing if
fetchis then sent on to an internal address.
TL;DR: SSRF (Server-Side Request Forgery) means an attacker makes your server request an address they choose. Targets include internal services, file://, and the cloud metadata at 169.254.169.254 (the machine's information about itself). On AWS EC2 with IMDSv1 (the old metadata service), it returns temporary AWS credentials. Prevent it with an allowlist, a list of the hosts that are allowed: parse the URL with new URL inside try...catch (a failed parse means false), require protocol === 'https:', and match the lowercased hostname with ===. Add redirect: 'error' so fetch doesn't follow redirects. When an allowlist isn't possible, get all the host's IPs from DNS first and refuse every IP that is not public (IPv4 and IPv6). Limit egress (outbound traffic), and require IMDSv2. IMDSv2 needs a session token from a PUT, so an ordinary SSRF that can only GET can't read the metadata.
⚡ Your server, borrowed by an attacker
Write:
const response = await fetch(req.body.url) // VULNERABLE: a URL from the user, fetched as it is
Guess first: 169.254.169.254 is the cloud metadata address, which gives information about the machine itself. A server on AWS EC2 (with IMDSv1, the old version) fetches http://169.254.169.254/latest/meta-data/iam/security-credentials/ sent by a user. What leaks?
Temporary AWS credentials. The first response holds the machine's role name (its set of permissions), and one more request to that name gives the attacker access keys to your cloud services.
Meaning: SSRF (Server-Side Request Forgery): an attacker makes your server send a request to an address they pick. In this code, req.body.url is a URL from the user that is fetched as it is. That address can be an internal service the internet can't reach.
⚡ Parse with new URL
Meaning: Don't check a URL by searching its text. new URL() parses it exactly the way fetch will read it. protocol (the start of the URL) always ends with a colon, hostname (the host's name) is already lowercase, and text that isn't a URL makes new URL() throw an error.
⚡ An allowlist of hosts
Write:
if (parsed.protocol !== 'https:') return false // refuse http:, file:, gopher:, etc.
const host = parsed.hostname.toLowerCase()
return allowlist.some((h) => h.toLowerCase() === host)
Meaning: Only https: URLs with a host on the allowlist list are allowed. parsed is the result of new URL(url). Compare the host with ===, not includes. Wrap it all in try...catch, so a URL that fails to parse gives false.
⚡ Extra layers
Meaning: The option redirect: 'error' makes fetch fail when the host answers with a redirect, so the request isn't sent on to an internal address. On AWS EC2, require IMDSv2 (the new version of the metadata service). IMDSv2 needs a session token through a PUT before any GET, while most SSRF bugs can only send a GET.