SSRF Explained: Validating User-Supplied URLs Safely
By Urlzee Team · Published · 7 min read
Server-side request forgery (SSRF) happens when your server fetches a URL chosen by someone else and that URL leads somewhere only the server can reach. The defence is to treat every user-supplied URL as untrusted: parse it properly, allow only http and https, resolve the hostname, reject private addresses, and repeat those checks on every redirect.
What is SSRF and why does it matter?
It is a confused-deputy problem. Your server sits inside a network and can talk to things the public internet cannot: databases, admin panels, internal APIs, and on cloud platforms a metadata service that hands out credentials to the machine itself. Those services often trust any request that arrives from inside.
If an application accepts a URL and requests it, the person supplying the URL is choosing where a trusted machine connects. Without checks, the request can be aimed at those internal systems, and the response may be shown back to the requester.
SSRF is common enough to be listed as its own category in the OWASP Top 10 for 2021. It is also easy to introduce by accident, because the vulnerable feature is usually something helpful.
Which features fetch user-supplied URLs?
More than most teams realise. Look for any code path where outside input decides what the server connects to.
| Feature | Where the URL comes from |
|---|---|
| Link preview or unfurling | A link pasted into a message or post |
| Webhooks | A callback address entered in settings |
| Import from URL | "Upload an image or file from a web address" |
| HTML-to-PDF or screenshot services | The page to render, and every resource it loads |
| Feed and sitemap readers | A subscribed feed address |
| URL expanders and link checkers | The link the user wants inspected |
| OAuth and SSO discovery | A metadata or issuer URL in configuration |
Urlzee has two tools of exactly this kind: the URL expander and the link checker both request whatever address a visitor types. The rest of this article describes the layers used to make that safe, which apply to any similar feature.
Why isn't a simple blocklist enough?
Because string matching checks what a URL looks like, and the connection goes to wherever it actually resolves. Three gaps matter:
- Addresses have many spellings. The same IP address can be written in several notations, and IPv6 can embed an IPv4 address. A filter looking for particular strings will miss some of them.
- Hostnames are indirection. A perfectly ordinary public domain name can have a DNS record that points at a private address. The text of the URL reveals nothing.
- Redirects change the destination. A URL that passes every check can answer with a redirect to one that would not. If your HTTP client follows redirects automatically, your validation only ever saw the first hop.
A sound defence therefore validates the parsed URL, then the resolved addresses, and does both again for each redirect.
How do you validate a user-supplied URL safely?
Apply the checks in layers, cheapest first.
- Parse with a real URL parser. Never use regular expressions to pull out the host. Use the parser's output for all later checks, because it normalises unusual notations.
- Allow only
httpandhttps. Reject everything else, includingfile:,ftp:andgopher:. - Reject embedded credentials. URLs of the form
https://user:pass@host/have no place in this kind of feature and are a classic way to disguise the real host. - Reject obviously internal names.
localhost, single-label hosts with no dot, and suffixes such as.local,.internal,.lanand.corp. - Resolve the hostname and check every address. If any A or AAAA record is in a non-public range, refuse.
- Do not follow redirects automatically. Read the
Locationheader yourself and run steps 1 to 5 on it before continuing. - Set limits. A short timeout, a maximum number of hops and a cap on how much of the response you read.
- Return as little as possible. Give the user the facts the feature needs, such as status code and final URL, not raw response bodies or detailed connection errors.
The address ranges to treat as non-public include:
| Range | What it is |
|---|---|
127.0.0.0/8, ::1 | Loopback |
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 | Private networks |
169.254.0.0/16, fe80::/10 | Link-local, where cloud metadata services live |
100.64.0.0/10 | Carrier-grade NAT |
0.0.0.0/8, :: | "This network" and unspecified |
fc00::/7 | IPv6 unique local |
224.0.0.0/4 and above, ff00::/8 | Multicast and reserved |
::ffff:0:0/96 | IPv4-mapped IPv6; check the embedded address |
What does this look like in code?
Here is a compact Node.js 18+ implementation of steps 1 to 7, with no dependencies. Save it as safe-fetch.mjs.
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
function isPrivateIPv4(ip) {
const [a, b] = ip.split(".").map(Number);
return (
a === 0 || a === 10 || a === 127 ||
(a === 100 && b >= 64 && b <= 127) ||
(a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && (b === 168 || b === 0)) ||
(a === 198 && (b === 18 || b === 19)) ||
a >= 224
);
}
function isPrivateIp(ip) {
if (isIP(ip) === 4) return isPrivateIPv4(ip);
const v = ip.toLowerCase().split("%")[0];
if (v === "::" || v === "::1") return true;
const mapped = v.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped) return isPrivateIPv4(mapped[1]);
if (v.startsWith("::ffff:")) return true; // other mapped forms: refuse
return (
v.startsWith("fc") || v.startsWith("fd") || /^fe[89ab]/.test(v) ||
v.startsWith("ff") || v.startsWith("64:ff9b:") || v.startsWith("2001:db8:")
);
}
async function assertSafeUrl(input) {
const url = new URL(input); // throws on malformed input
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error("Only http and https URLs are allowed.");
}
if (url.username || url.password) {
throw new Error("URLs with credentials are not allowed.");
}
const host = url.hostname.replace(/^\[|\]$/g, "");
const records = isIP(host) ? [{ address: host }] : await lookup(host, { all: true });
if (records.length === 0 || records.some((r) => isPrivateIp(r.address))) {
throw new Error("Host resolves to a non-public address.");
}
return url;
}
export async function safeFetch(input, { maxHops = 5, timeoutMs = 6000 } = {}) {
let current = input;
for (let hop = 0; hop <= maxHops; hop++) {
const url = await assertSafeUrl(current);
const res = await fetch(url, {
redirect: "manual",
signal: AbortSignal.timeout(timeoutMs),
});
const location = res.headers.get("location");
if (res.status >= 300 && res.status < 400 && location) {
await res.body?.cancel();
current = new URL(location, url).toString(); // resolve relative redirects
continue;
}
return res;
}
throw new Error("Too many redirects.");
}
And to use it:
import { safeFetch } from "./safe-fetch.mjs";
const res = await safeFetch("https://example.com/");
console.log(res.status, res.url);
The important line is redirect: "manual". It stops fetch from following redirects on its own, so each new location passes through assertSafeUrl before any connection is made.
What does validation alone not cover?
There is a timing gap between checking a hostname and connecting to it. The code above resolves the name, approves the addresses, and then fetch resolves the name again when it connects. If the DNS answer changes between those two lookups, the connection could go somewhere that was never checked. This is usually called DNS rebinding.
Application-level checks narrow that window but cannot close it by themselves. Stronger measures work at the connection and network level:
- Pin the address. Connect to the IP you validated, sending the original hostname for TLS and the
Hostheader, so there is no second lookup. - Restrict egress. Run URL-fetching code where firewall rules or network policy prevent connections to internal ranges at all. Then a missed case in the code still fails safely.
- Use a forward proxy. Send all outbound fetches through a proxy that enforces the address rules itself.
- Harden internal services. Require authentication on internal APIs and use the hardened, token-based mode that cloud providers offer for their metadata services. Internal services should not trust a request just because of where it came from.
Treat these as layers. For a fuller checklist, the OWASP Server-Side Request Forgery Prevention Cheat Sheet is the standard reference.
How does Urlzee apply this?
Urlzee handles user-supplied URLs in two places, and each has its own rules.
When a link is shortened, the destination is only stored, not fetched, but it is still validated. Urlzee accepts http and https only, with a maximum length of 2,048 characters. It rejects URLs containing credentials, whitespace or control characters. It refuses every raw IP address, public ones included, since legitimate destinations almost never use them. It also refuses hosts without a dot and internal suffixes such as .local, .internal and .lan. These rules are part of how URL shorteners prevent abuse.
When the expander or link checker fetches a URL, the same validation runs first. The hostname is then resolved, and the request is refused if any returned address is private, loopback, link-local or otherwise reserved. Redirects are followed manually, with validation and resolution repeated at each hop. A chain is cut off after 8 hops, each request has a timeout of a few seconds, and at most 64 KB of a page is read to find its title. The tools report status codes, hop URLs and the title, and nothing else from the response.
The structure is what carries over to your own code: validate, resolve, check, fetch one hop, and repeat. For a related risk on the other side of redirects, where your own site can be used to bounce visitors elsewhere, see open redirects explained.
Frequently asked questions
- What is SSRF in simple terms?
- Server-side request forgery is when an application fetches a URL supplied by a user and can be pointed at addresses only the server can reach, such as internal services or its own loopback interface. The server ends up making requests on an outsider's behalf.
- Which features are at risk of SSRF?
- Anything where the server requests a URL that came from outside: link previews, webhooks, import-from-URL, image or PDF fetchers, URL expanders and link checkers. If user input influences where your server connects, the risk applies.
- Is blocking localhost and 127.0.0.1 enough to prevent SSRF?
- No. Private addresses can be written in many forms, a public hostname can resolve to an internal IP, and a safe URL can redirect to an unsafe one. Validation has to check the resolved IP addresses and every redirect hop.
- Should I use an allow list or a block list?
- Use an allow list of permitted hosts whenever the feature only needs to reach known destinations. If it must reach arbitrary sites, block every non-public address range and combine that with network-level restrictions on what the server can connect to.