← Back to Node.js, page 5

nodejs-0084 · Hard senior

How do you validate a user-supplied URL to prevent server-side request forgery (SSRF) in a Node.js service?

SSRF happens when a server fetches a URL chosen by a user, and the user points it at internal addresses such as 127.0.0.1 or cloud metadata at 169.254.169.254. Allow only http and https, parse with URL, resolve the host name yourself, reject private and special IP ranges (net.BlockList), connect to the checked IP, and limit redirects.

Full answer

Features such as "import from URL", webhooks, link previews and image fetchers make the server send requests for a user. An attacker supplies http://169.254.169.254/latest/meta-data/ (cloud credentials), http://localhost:6379 (a local Redis) or an internal admin address. The server may then return secrets or change internal systems.

A defence needs several layers, because simple string checks fail:

  1. Parse with the URL class and allow only http: and https:. Reject file:, ftp:, gopher: and others. Reject credentials in the URL (user@host), which are used in confusion tricks.
  2. Normalise the host. The URL parser converts 0x7f.1 or 2130706433 to 127.0.0.1, which is why you must check the parsed result, not the raw text.
  3. Resolve the host name to IP addresses (dns.lookup with all: true). Reject every address that is loopback, private (10/8, 172.16/12, 192.168/16), link-local (169.254/16), carrier-grade NAT, multicast or IPv6 equivalents. net.BlockList helps with ranges. If any address is blocked, reject.
  4. Connect to the IP you checked, not to the name again. Otherwise DNS rebinding changes the answer between the check and the connection. Pass a custom lookup function to the HTTP agent, or set the Host header and connect to the IP.
  5. Do not follow redirects blindly. A public URL can redirect to an internal one. Follow manually, with a small limit, and run the full check on each hop.
  6. Add timeouts, a response size limit and a restricted set of ports.
  7. Network-level controls matter most: run fetchers in a network segment without access to internal services, and require metadata service tokens (IMDSv2 on AWS).

An allow-list of known hosts is stronger than a block-list whenever the use case permits it.

javascript
const net = require('node:net');

const blocked = new net.BlockList();
blocked.addSubnet('127.0.0.0', 8);
blocked.addSubnet('10.0.0.0', 8);
blocked.addSubnet('172.16.0.0', 12);
blocked.addSubnet('192.168.0.0', 16);
blocked.addSubnet('169.254.0.0', 16);   // link-local, includes the cloud metadata address
blocked.addSubnet('0.0.0.0', 8);
blocked.addAddress('::1', 'ipv6');
blocked.addSubnet('fc00::', 7, 'ipv6'); // unique local addresses
blocked.addSubnet('fe80::', 10, 'ipv6');

// A pretend DNS: name -> addresses. A real service would call dns.promises.lookup(host, { all: true }).
const fakeDns = {
  'schoolabe.com': ['93.184.216.34'],
  'intranet.example': ['10.2.3.4'],
  'sneaky.example': ['93.184.216.34', '127.0.0.1'], // one public and one private answer
};
const resolve = async (host) => fakeDns[host] || [];

async function checkUrl(input) {
  let url;
  try { url = new URL(input); } catch { return 'rejected: not a valid URL'; }
  if (!['http:', 'https:'].includes(url.protocol)) return 'rejected: protocol ' + url.protocol;
  if (url.username || url.password) return 'rejected: credentials in the URL';

  const host = url.hostname.replace(/^\[|\]$/g, '');
  const addresses = net.isIP(host) ? [host] : await resolve(host);
  if (addresses.length === 0) return 'rejected: host does not resolve';

  for (const address of addresses) {
    const family = net.isIP(address) === 6 ? 'ipv6' : 'ipv4';
    if (blocked.check(address, family)) return 'rejected: ' + address + ' is a private address';
  }
  return 'allowed (connect to ' + addresses[0] + ')';
}

(async () => {
  const inputs = [
    'https://schoolabe.com/image.png',
    'http://127.0.0.1:6379/',
    'http://0x7f.1/',                       // the parser turns this into 127.0.0.1
    'http://2130706433/',                   // decimal form of 127.0.0.1
    'http://169.254.169.254/latest/meta-data/',
    'http://[::1]/admin',
    'http://intranet.example/',
    'http://sneaky.example/',
    'http://schoolabe.com@127.0.0.1/',      // the real host is after the @
    'file:///etc/passwd',
    'ftp://schoolabe.com/file',
    'not a url',
  ];
  for (const input of inputs) console.log(input.padEnd(44), await checkUrl(input));
})();

Name resolution is simulated with a lookup table, so the example is repeatable. In a real service, replace resolve() with dns.promises.lookup(host, { all: true }). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): https://schoolabe.com/image.png allowed (connect to 93.184.216.34) http://127.0.0.1:6379/ rejected: 127.0.0.1 is a private address http://0x7f.1/ rejected: 127.0.0.1 is a private address http://2130706433/ rejected: 127.0.0.1 is a private address http://169.254.169.254/latest/meta-data/ rejected: 169.254.169.254 is a private address http://[::1]/admin rejected: ::1 is a private address http://intranet.example/ rejected: 10.2.3.4 is a private address http://sneaky.example/ rejected: 127.0.0.1 is a private address http://schoolabe.com@127.0.0.1/ rejected: credentials in the URL file:///etc/passwd rejected: protocol file: ftp://schoolabe.com/file rejected: protocol ftp: not a url rejected: not a valid URL

Key points

  • Allow only http and https. Parse before checking.
  • Resolve the name, and block private, loopback and link-local ranges.
  • Connect to the checked IP to stop DNS rebinding.
  • Handle redirects hop by hop.
  • Network isolation is the strongest layer.

Common mistakes

  • Checking the URL text with a regular expression instead of parsing it.
  • Resolving the name for the check and again for the connection.
  • Following redirects automatically.
  • Blocking only 127.0.0.1 and forgetting 169.254.169.254, IPv6 and private ranges.

Follow-ups

  • What is DNS rebinding?
  • How does IMDSv2 reduce the impact of SSRF?
  • How would you build an allow-list for a link preview feature?

Tips

  • List the defence layers in order and end with network isolation.
  • Mention the parser normalising odd IP spellings.
  • Name DNS rebinding and redirects.