Some features are risky by nature. A feature that fetches a URL on the user's behalf can be turned against your own internal network. A feature that accepts files can be used to store malware, run scripts in your origin, or fill your disks. And every response your server sends can either restrict or permit what the browser does with it. This lesson hardens all three: server-side request forgery (SSRF), file uploads, and security headers, with Node.js and nginx examples you can adapt.
Before you start
You should be familiar with XSS and Content Security Policy from Cross-Site Scripting (XSS), CSRF, and Browser Defenses, and with trust boundaries from Threat Modeling and Secure-by-Design Software Architecture. The examples use Node.js 22 or newer and TypeScript. Try the SSRF examples only on your own machine or an isolated test environment.
What SSRF is
SSRF happens when an application fetches a URL that the user controls, and the user points it somewhere the application can reach but they can't. Common features that fetch URLs include link previews, webhooks, "import from URL," image proxies, PDF generators, and integrations that call user-configured endpoints.
Your server usually sits inside a network with privileges the internet doesn't have. An SSRF bug can let an attacker:
- reach internal services such as admin panels, databases with HTTP interfaces, or monitoring tools bound to
localhost; - read cloud instance metadata, which on many platforms is served at the link-local address
169.254.169.254and can include temporary credentials for the server's cloud role; - scan internal ports, or use your server as a proxy to attack others.
SSRF was its own category in the 2021 OWASP Top 10. In the 2025 edition it's part of A01 Broken Access Control, and it's API7 in the OWASP API Security Top 10:2023.
// INSECURE TEACHING EXAMPLE: fetches any URL the caller sends, including internal ones.
app.post("/api/link-preview", requireSession, async (req, res) => {
const response = await fetch(String(req.body.url));
res.json({ title: extractTitle(await response.text()) });
});A request with url set to an internal address, or to a hostname that resolves to one, makes your server fetch it and hand back what it finds.
Why simple filters fail
Blocking the string localhost or 169.254.169.254 doesn't work. The same destination can be reached through:
- other spellings of the same address:
127.1, decimal2130706433, IPv6[::1], or IPv4-mapped IPv6 such as[::ffff:127.0.0.1]; - a public hostname whose DNS record points to a private address;
- DNS rebinding: a hostname that resolves to a public address when you check it and to a private one when you connect;
- redirects: a public URL that answers with a redirect to an internal one.
A robust defense checks the resolved IP address that you actually connect to, and handles redirects explicitly.
Defending against SSRF
Layer these controls, starting with the strongest:
- Avoid user-supplied URLs if you can. Let users pick from known integrations, or upload content instead of pointing at it.
- Allowlist destinations when the set is known, such as a list of partner API hostnames.
- Allow only
https:(and only standard ports), parse URLs with the WHATWGURLparser, and reject credentials in URLs. - Resolve and check every address against private, loopback, link-local, and other special ranges, inside the connection's own DNS lookup so a rebinding can't slip between check and use.
- Don't follow redirects automatically. If you must, re-run every check on each hop, with a small hop limit.
- Limit time and size of the response, and return only what you need (a title, not the whole body).
- Isolate the network. Run the fetcher with no route to internal networks, or through an egress proxy that enforces the rules. On cloud platforms, require the newer session-based metadata protocols (for example, IMDSv2 on AWS), which block simple SSRF reads of credentials.
Here is a fetcher that implements controls 3 to 6 with Node's built-in modules:
import { lookup as dnsLookup, type LookupAddress } from "node:dns";
import { get } from "node:https";
import { BlockList, isIP } from "node:net";
const blocked = new BlockList();
for (const [net, bits] of [["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16],
["172.16.0.0", 12], ["192.0.0.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15], ["224.0.0.0", 4], ["240.0.0.0", 4]] as const) {
blocked.addSubnet(net, bits, "ipv4");
}
// IPv4 rules also match IPv4-mapped IPv6 addresses such as ::ffff:127.0.0.1, so those need no rule of their own.
// (A ::ffff:0:0/96 rule would match every IPv4 address in BlockList and block everything.)
for (const [net, bits] of [["::", 128], ["::1", 128], ["fc00::", 7], ["fe80::", 10], ["ff00::", 8]] as const) {
blocked.addSubnet(net, bits, "ipv6");
}
const isBlocked = (address: string) => blocked.check(address, isIP(address) === 6 ? "ipv6" : "ipv4");
// Runs inside the connection, so the address checked is the address used.
function guardedLookup(hostname: string, options: { all?: boolean }, callback: (...args: any[]) => void) {
dnsLookup(hostname, { ...options, all: true }, (error, addresses: LookupAddress[]) => {
if (error) return callback(error);
if (addresses.length === 0 || addresses.some((entry) => isBlocked(entry.address))) {
return callback(new Error("Destination not allowed"));
}
if (options.all) return callback(null, addresses);
callback(null, addresses[0]!.address, addresses[0]!.family);
});
}
export function fetchPublicText(input: string, maxBytes = 512 * 1024): Promise<string> {
const url = new URL(input);
if (url.protocol !== "https:" || (url.port && url.port !== "443") || url.username || url.password) {
return Promise.reject(new Error("Only plain https URLs are allowed"));
}
// IP literals skip DNS lookup, so check them directly.
const host = url.hostname.replace(/^\[|\]$/g, "");
if (isIP(host) && isBlocked(host)) return Promise.reject(new Error("Destination not allowed"));
return new Promise((resolve, reject) => {
const request = get(url, { lookup: guardedLookup, timeout: 5_000 }, (response) => {
if (response.statusCode !== 200) {
response.resume();
return reject(new Error(`Unexpected status ${response.statusCode}`)); // redirects are not followed
}
let size = 0;
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => {
size += chunk.length;
if (size > maxBytes) request.destroy(new Error("Response too large"));
else chunks.push(chunk);
});
response.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
request.on("timeout", () => request.destroy(new Error("Timed out")));
request.on("error", reject);
});
}The blocklist approach above is a reasonable application-level control, but no blocklist is complete forever: new special-purpose ranges and platform-specific addresses appear. Treat it as one layer, and combine it with network isolation.
Verifying the SSRF guard
Write tests that run locally without network access to anything internal:
import { describe, expect, it } from "vitest";
import { fetchPublicText } from "./safe-fetch";
describe("fetchPublicText", () => {
it.each([
"http://public.test/",
"https://127.0.0.1/",
"https://[::1]/",
"https://169.254.169.254/latest/meta-data/",
"https://2130706433/",
"https://user:pass@public.test/",
"https://public.test:8443/",
])("refuses %s", async (url) => {
await expect(fetchPublicText(url)).rejects.toThrow();
});
});To test hostnames that resolve to private addresses, add a test hostname to a local resolver or mock dns.lookup and check that the request is refused.
File uploads
An upload feature hands strangers write access to your storage. The risks include files that execute (a script uploaded into a directory the web server runs), files that render as HTML or SVG in your origin and become stored XSS, oversized files and decompression bombs that exhaust disk or memory, path traversal through crafted file names, and metadata such as GPS coordinates in photos that leaks personal data.
Handle uploads with these rules:
- Limit size at the proxy and in the application, and limit the number of files per request.
- Decide types by content, not by name. Check the file's leading bytes (its signature) against an allowlist, and ignore the client's
Content-Type. Extensions and MIME types are just labels the client chose. - Generate the stored name yourself, such as a random ID, and keep the original name only as metadata, never as a path.
- Store outside the web root, ideally in object storage, so nothing uploaded can be executed by the web server.
- Re-encode images where possible. Decoding and re-encoding removes embedded scripts and metadata, including location data.
- Serve user files carefully: from a separate domain (so they don't share your origin's cookies and permissions), with
Content-Disposition: attachmentfor downloads, the verifiedContent-Type, andX-Content-Type-Options: nosniff. - Treat SVG and HTML as code. Don't accept them, or serve them only as downloads from a separate domain.
- Scan for malware if users share files with each other; it's an extra layer, not a replacement for the rules above.
import { randomUUID } from "node:crypto";
import { fileTypeFromBuffer } from "file-type";
import sharp from "sharp";
const ALLOWED = new Map([["image/jpeg", "jpg"], ["image/png", "png"], ["image/webp", "webp"]]);
const MAX_BYTES = 5 * 1024 * 1024;
export async function acceptAvatar(data: Buffer) {
if (data.length > MAX_BYTES) throw new Error("File too large");
const type = await fileTypeFromBuffer(data); // reads the file's signature, not its name
if (!type || !ALLOWED.has(type.mime)) throw new Error("Only JPEG, PNG, or WebP images are accepted");
// Re-encode: drops metadata (such as GPS) and anything that isn't image data; caps dimensions.
const clean = await sharp(data, { limitInputPixels: 40_000_000 })
.rotate()
.resize({ width: 1024, height: 1024, fit: "inside", withoutEnlargement: true })
.webp({ quality: 85 })
.toBuffer();
const key = `avatars/${randomUUID()}.webp`;
await storage.put(key, clean, { contentType: "image/webp" }); // private bucket, served via your code or a CDN
return key;
}If you extract archives, check every entry's resolved path stays inside the target directory, and cap the total extracted size and file count.
Security headers
Response headers instruct the browser to restrict what a page can do. They don't fix vulnerabilities, but they limit what an attacker can achieve with one. A production baseline for an HTML application:
Content-Security-Policy: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'; form-action 'self'
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-originWhat each one does:
- Content-Security-Policy: limits which scripts run (lesson 8).
frame-ancestorsreplacesX-Frame-Optionsfor clickjacking protection, andform-actionlimits where forms can submit. - Strict-Transport-Security: HTTPS only (lesson 2).
- X-Content-Type-Options: nosniff: the browser uses your declared content type instead of guessing, which matters for uploaded files.
- Referrer-Policy: limits how much of your URLs is sent to other sites. Use
no-referreron pages whose URLs contain tokens. - Permissions-Policy: turns off powerful browser features you don't use, for your page and any embedded frames.
- Cross-Origin-Opener-Policy: same-origin: isolates your window from pages it opens or that open it, which blocks some cross-window attacks.
Some headers are obsolete. X-XSS-Protection controlled a filter that modern browsers have removed; don't rely on it. Expect-CT is deprecated.
Setting headers in nginx
# In the server block for the site. "always" adds the header to error responses too.
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
# A nonce-based CSP must be generated per response by the application, not set statically here.Note that nginx's add_header directives in a location block replace, not extend, those inherited from the server block. If you add any header in a location, repeat the full set there, or use an included snippet.
Verifying headers
curl -sI https://your-site.test/ | grep -iE '^(content-security-policy|strict-transport|x-content-type|referrer-policy|permissions-policy|cross-origin-opener)'
curl -sI https://your-site.test/does-not-exist | grep -ic 'x-content-type-options'Add an automated test that requests a few representative pages (including an error page) and fails if a required header is missing. MDN's HTTP Observatory gives a public site a quick external review.
Common mistakes and troubleshooting
- Validating the URL string, not the resolved address. Check the IP you connect to, and handle IP literals and redirects.
- Following redirects in a URL fetcher. Disable them, or re-check every hop.
- Trusting file extensions or the client's MIME type. Check signatures and re-encode.
- Serving uploads from your main origin. Use a separate domain,
nosniff, andattachment. - Headers missing on error pages. Use nginx's
always, or set headers in the application for every response. - A strict header that breaks the site in production. Roll out CSP in report-only mode first, and start HSTS with a short
max-age.
If a legitimate URL is refused by the SSRF guard, log the hostname and the resolved addresses (not the full URL with any query string) so you can see which rule matched.
Practical exercise: harden three features
In a local practice project:
- Build a link-preview endpoint with
fetchPublicText, and run the refusal tests. - Build an avatar upload that checks signatures, re-encodes, stores under random names, and rejects SVG.
- Add the header baseline, verify it with
curlon a normal page and an error page, and add a test that checks the headers. - Update your threat model from lesson 11 with the SSRF and upload threats and their mitigations.
Key takeaways
- SSRF turns your server into a proxy to internal networks and cloud metadata; check the resolved address you connect to, refuse redirects, and isolate the network.
- Treat uploads as hostile: limit size, verify content, rename, store privately, re-encode, and serve from a separate domain.
- A small set of security headers limits the damage of other bugs; set them on every response, including errors, and verify them automatically.
References
- OWASP Server-Side Request Forgery Prevention Cheat Sheet (opens in a new tab)
- OWASP File Upload Cheat Sheet (opens in a new tab)
- OWASP HTTP Headers Cheat Sheet (opens in a new tab)
- Node.js: net.BlockList (opens in a new tab)
- IANA IPv4 Special-Purpose Address Registry (opens in a new tab)
- MDN: Permissions-Policy (opens in a new tab)
- nginx: add_header (opens in a new tab)
What's next
So far you've hardened code you write. Most of what you deploy, though, is code you didn't write. Software Supply Chain Security: Dependencies, SBOMs, and Secure CI/CD covers how to trust your dependencies, your build, and what you ship.

