Lesson 262 of 296
CSRF and SSRF
What you will learn
- What CSRF is and why browsers made it possible
- Defences: SameSite cookies, CSRF tokens, Origin checks
- What SSRF is and why it is dangerous in the cloud
- Defending against SSRF
- Webhook signature verification
On this page
CSRF: Cross-Site Request Forgery
CSRF tricks a logged-in user's browser into sending a request they did not intend. Browsers historically attached cookies to every request to a site, including requests started by other sites.
The attack: you are logged in to bank.example. You visit evil.example, which contains:
<form action="https://bank.example/transfer" method="POST" id="f">
<input name="to" value="attacker"><input name="amount" value="1000">
</form>
<script>document.getElementById("f").submit()</script>Your browser sends the POST with your bank session cookie. If the bank only checks the cookie, the transfer happens. The attacker never sees the response; they only need the action to happen.
CSRF needs: authentication by cookies (or other credentials the browser sends automatically), a state-changing action, and predictable request parameters. APIs authenticated only by an Authorization: Bearer header that JavaScript must add are not vulnerable to classic CSRF, because other sites cannot make the browser add that header.
CSRF defences
| Defence | How |
|---|---|
| SameSite cookies (Lesson 200) | SameSite=Lax (the default in modern browsers when not set) stops cookies on cross-site POSTs, iframes and fetches; Strict stops them on all cross-site requests. The most effective modern defence |
Check the Origin header | Browsers send Origin on cross-site and POST requests; reject state-changing requests whose origin is not yours. (Browsers also send Sec-Fetch-Site: cross-site.) |
| CSRF tokens | A random token tied to the session, included in forms or a header, and checked by the server; the attacker cannot read it from another site. Used by most server-rendered frameworks |
| Never change state with GET | Links and images can trigger GETs from anywhere (Lesson 194) |
| Re-authentication for sensitive actions | Ask for the password or a second factor before changing email or transferring money |
A middleware checking Origin for unsafe methods:
import type { Request, Response, NextFunction } from "express";
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
export function requireSameOrigin(allowedOrigins: string[]) {
const allowed = new Set(allowedOrigins);
return (req: Request, res: Response, next: NextFunction) => {
if (SAFE_METHODS.has(req.method)) return next();
const origin = req.header("Origin");
const fetchSite = req.header("Sec-Fetch-Site");
if (fetchSite === "cross-site" || (origin !== undefined && !allowed.has(origin))) {
res.status(403).json({ error: "Cross-site request blocked" });
return;
}
next();
};
}Tested: a POST with Origin: https://evil.example received 403; the same POST from the allowed origin passed. Next.js server actions apply a similar Origin check automatically (Lesson 181). Combine this with SameSite cookies; if requests without any Origin header must be accepted (some old clients), require a CSRF token for them.
SSRF: Server-Side Request Forgery
SSRF tricks your server into making requests to places the attacker chooses. Features that fetch a URL given by the user are the target: "import from URL", link previews, webhooks you send, image fetching, PDF generation from a page.
Why it is dangerous: your server is inside your network. It can reach things the attacker cannot:
- Cloud metadata endpoints, such as
http://169.254.169.254/on AWS, which can return temporary credentials for the server's IAM role (this caused the well-known Capital One breach in 2019). AWS's IMDSv2 requires a session token obtained with a PUT request, which blocks most simple SSRF; make sure it is enforced. - Internal services: admin panels, databases, Redis, Kubernetes APIs, on
localhostor private IP ranges. - Port scanning of the internal network.
The OWASP Top 10 2025 includes SSRF under Broken Access Control.
SSRF defences
- Allow-list destinations when you can ("only these partner domains").
- Otherwise validate URLs: only
https:(orhttp:) schemes; resolve the hostname and reject private, loopback, link-local and other internal IP ranges. - Check again after redirects (or disable redirects): a public URL can redirect to
169.254.169.254. - Beware DNS rebinding: a hostname can resolve to a public IP during the check and a private IP during the request. Connect to the IP you validated, or use a fetching proxy that enforces rules.
- Network controls: run URL-fetching code in an isolated service or subnet whose egress rules block internal ranges; enforce IMDSv2.
- Limit response size and time; do not return raw responses or detailed errors to the user.
A validator:
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
function isPrivateIPv4(ip: string): boolean {
const [a = 0, b = 0] = ip.split(".").map(Number);
return (
a === 10 || a === 127 || a === 0 ||
(a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) ||
(a === 100 && b >= 64 && b <= 127)
);
}
function mappedIPv4(ipv6: string): string | null {
const rest = ipv6.slice("::ffff:".length);
if (rest.includes(".")) return rest;
const [high, low] = rest.split(":").map((part) => parseInt(part, 16));
if (high === undefined || low === undefined || Number.isNaN(high) || Number.isNaN(low)) return null;
return [high >> 8, high & 255, low >> 8, low & 255].join(".");
}
function isPrivateIPv6(ip: string): boolean {
const lower = ip.toLowerCase();
if (lower.startsWith("::ffff:")) {
const v4 = mappedIPv4(lower);
return v4 === null || isPrivateIPv4(v4);
}
return lower === "::1" || lower === "::" || lower.startsWith("fc") || lower.startsWith("fd") || lower.startsWith("fe80");
}
export async function assertPublicHttpUrl(raw: string): Promise<URL> {
let url: URL;
try {
url = new URL(raw);
} catch {
throw new Error("Invalid URL");
}
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("Only http and https URLs are allowed");
const host = url.hostname.replace(/^\[|\]$/g, "");
const addresses = isIP(host) ? [{ address: host, family: isIP(host) }] : await lookup(host, { all: true });
for (const { address, family } of addresses) {
if (family === 4 ? isPrivateIPv4(address) : isPrivateIPv6(address)) {
throw new Error("URL points to a private or internal address");
}
}
return url;
}Tested: it rejected http://169.254.169.254/latest/meta-data/, http://127.0.0.1:6379, http://localhost:3000 (resolved to 127.0.0.1), http://[::1]/, http://10.0.0.5/, http://172.20.1.1/, http://192.168.1.1/, http://[::ffff:127.0.0.1]/ and file:///etc/passwd, and accepted URLs with public IPs. The mappedIPv4 helper exists because of a bug found while testing: the first version only handled IPv4-mapped IPv6 addresses written with dots, but the URL class rewrites [::ffff:127.0.0.1] as [::ffff:7f00:1], so the loopback address slipped through. Attackers use exactly these alternative spellings of internal addresses, which is why hand-written SSRF filters are risky and network-level egress rules matter. Remember this check alone does not stop DNS rebinding or redirects to private addresses; follow the extra steps above for full protection.
Webhook signatures (the other direction)
When others call your webhooks (Stripe, GitHub), anyone could send fake events to the URL. Providers sign each request with a shared secret (HMAC); verify the signature over the raw body before trusting it, and reject old timestamps to prevent replay:
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyWebhook(rawBody: string, timestamp: string, signatureHex: string, secret: string, nowSeconds: number, toleranceSeconds = 300): boolean {
if (Math.abs(nowSeconds - Number(timestamp)) > toleranceSeconds) return false;
const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
const given = Buffer.from(signatureHex, "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
}This follows the general scheme Stripe uses (a timestamp plus the body, signed with HMAC-SHA256). In practice use the provider's SDK (stripe.webhooks.constructEvent), which does exactly this. Parse JSON only after verifying, and keep the raw body (frameworks often parse it too early, which breaks verification).
How to say it in an interview
"CSRF tricks a logged-in user's browser into sending a state-changing request with its cookies from another site. I defend with SameSite cookies, checking the Origin or Sec-Fetch-Site header on unsafe methods, CSRF tokens where needed, never changing state with GET, and re-authentication for sensitive actions; bearer-token APIs are not vulnerable in the classic way. SSRF tricks my server into requesting attacker-chosen URLs, which in the cloud can expose metadata credentials or internal services. I allow-list destinations when possible, otherwise allow only http and https, resolve hostnames and reject private ranges, re-check redirects, guard against DNS rebinding, enforce IMDSv2 and restrict egress. For incoming webhooks I verify HMAC signatures over the raw body with a timestamp tolerance."
Key words
| Word | Meaning |
|---|---|
| CSRF | Forcing a user's browser to send an unwanted request |
| SameSite | Cookie attribute limiting cross-site sending |
| CSRF token | A secret per-session value checked on state-changing requests |
| Origin / Sec-Fetch-Site | Headers revealing where a request came from |
| SSRF | Making the server request attacker-chosen URLs |
| Metadata endpoint | A cloud service on 169.254.169.254 giving instance information and credentials |
| IMDSv2 | AWS metadata service version requiring a session token |
| DNS rebinding | A hostname changing to a private IP between check and use |
| HMAC signature | A keyed hash proving a message came from the secret holder |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.