My Node API has an endpoint that downloads an image from a URL the user supplies. Is it safe to call fetch(url) directly? What attacks should I guard against?
#javascript#node#security#ssrf
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
My Node API has an endpoint that downloads an image from a URL the user supplies. Is it safe to call fetch(url) directly? What attacks should I guard against?
#javascript#node#security#ssrf
No. Fetching user-controlled URLs from your server enables SSRF (server-side request forgery): an attacker asks your server to reach internal resources, such as http://127.0.0.1:6379, http://169.254.169.254/ (cloud metadata with credentials), or private network hosts, and may read the response.
new URL(); reject file:, ftp:, gopher:.redirect: 'manual' and re-validate each hop, with a small hop limit.AbortSignal.timeout.Sketch:
import dns from 'node:dns/promises';
import net from 'node:net';
async function assertPublic(host) {
const addrs = await dns.lookup(host, { all: true });
for (const { address } of addrs) {
if (isPrivate(address)) throw new Error('Blocked address');
}
}
Write isPrivate with a maintained IP range library rather than ad-hoc string checks.
Also remember response data from the remote site is untrusted.
There is a worked implementation in the DEV3 snippet library.