SSRF (Server-Side Request Forgery) — Security

SSRF (Server-Side Request Forgery) means an attacker makes your server request an address they choose. Targets include internal services, file://, and the…

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:

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

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

Extra layers

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

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.

What you will learn