SSRF: tricking your server into fetching internal things
Any feature that fetches a URL the user provides (webhooks, link previews, "import from URL") can be pointed at your internal network or your cloud's metadata service. How server-side request forgery works and how to box it in.
In one sentence
Your server sits inside your network. If a user picks the URL it fetches, they borrow that position. Allowlist destinations, block private addresses after DNS resolution, and lock down cloud metadata.
The idea
"Import your avatar from a URL" sounds harmless. But the request is made by your server, which can reach localhost, internal admin panels, databases on private IPs and the cloud metadata endpoint at 169.254.169.254 that hands out credentials.
How to defend
- Allowlist when you can: only the domains this feature should ever call (e.g. your image CDN, the customer's verified webhook domain).
- Resolve, then check. Resolve the hostname yourself, reject private, loopback and link-local ranges (10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, ::1, fc00::/7), and connect to that IP so DNS can't change in between (DNS rebinding).
- Don't follow redirects blindly: a public URL can 302 to
http://169.254.169.254. - IMDSv2 (or your cloud's equivalent): metadata requires a token obtained with a PUT, which most SSRF can't do.
- Egress controls: run URL-fetching in an isolated service whose network can only reach the internet, with a role that has almost no permissions.
const { address } = await dns.lookup(new URL(input).hostname);
if (isPrivate(address)) throw new Error("Destination not allowed");
// connect to `address`, set the Host header, redirect: "manual"Key takeaways
- 01Any user-supplied URL your server fetches is a potential SSRF.
- 02Prefer allowlists; otherwise block private ranges after resolving DNS.
- 03Handle redirects and DNS rebinding explicitly.
- 04Protect cloud metadata and isolate URL-fetching services with minimal permissions.
Check your understanding
1 of 3
What is SSRF?
Related concepts
Least privilege
Assume something will get hacked. Least privilege makes sure that when it does, the attacker gets the keys to one room, not the whole building.
6 min read →Defense in depth
Every control has holes. Line up several independent ones and the holes rarely align: the Swiss cheese model.
6 min read →Path traversal
Never let user input decide a filesystem path. Map IDs to files, or resolve the full path and check it's still inside the allowed folder.
5 min read →