CSRF & SSRF Defenses
How Cross-Site Request Forgery (CSRF) and Server-Side Request Forgery (SSRF) work, and how SameSite cookies, anti-CSRF tokens, allowlists, and metadata blocks stop them.
TL;DR
CSRF abuses a victim's browser to send authenticated requests to your server; SSRF abuses your server to send requests into your private network or cloud metadata (169.254.169.254). Defend CSRF with SameSite cookies + CSRF tokens + Origin/Sec-Fetch-Site checks, and defend SSRF with strict URL allowlists, disabled redirects, and pinned-IP private/metadata blocks.
Intent
Separate browser-side request forgery (CSRF) from server-side request forgery (SSRF), and apply layered defenses that survive edge cases like subdomains and DNS rebinding.
Problem
Both attacks exploit confused-deputy trust:
- In CSRF, your backend trusts cookies that the browser attaches automatically, even when the request was triggered by
evil.example. - In SSRF (now part of
A01:2025 Broken Access Control), your backend fetches a user-supplied URL (webhook, avatar importer, PDF generator) and unwittingly reaches internal admin APIs or cloud IMDSv1 credentials.
Solution
Stopping CSRF
- Use
SameSite=Lax(orStrict) on session cookies so cross-sitePOSTforms do not carry cookies. - Require an unpredictable CSRF token (or custom header validated with
Origin/Sec-Fetch-Sitechecks) on every state-changingPOST/PUT/PATCH/DELETEroute. - Never mutate state on
GETrequests (becauseSameSite=Laxstill sends cookies on top-levelGETnavigations).
Stopping SSRF
- Use a domain/scheme allowlist (
https:only, exact allowed hosts) whenever business logic permits. - Block private, loopback, link-local (
169.254.0.0/16), and IPv6 ULA ranges after DNS resolution, and connect to the resolved IP directly (preventing DNS rebinding). - Disable automatic HTTP redirects (or re-validate every redirect target) and enforce cloud IMDSv2 (session-token required).
Real-world analogy
▶ Flow: watch it work
CSRF protection flow
CSRF Attack Blocked by SameSite + Token + Origin Check
Press Start or tap any step dot to trace the path.
▸All steps (3)
SSRF protection flow
SSRF Blocked by Allowlist, Pinned DNS & Redirect Guard
Press Start or tap any step dot to trace the path.
▸All steps (4)
Code
Validating Origin for CSRF and checking resolved IP + disabling redirects for SSRF:
// UNSAFE: fetches any URL from the user with redirects enabled
const unsafeRes = await fetch(req.body.webhookUrl);
// SAFE: enforce https:, reject private/link-local IPs, disable redirects (ASVS V4, V13)
import { lookup } from 'node:dns/promises';
import net from 'node:net';
function isPrivateOrLinkLocal(ip: string): boolean {
if (net.isIPv4(ip)) {
return (
ip.startsWith('10.') ||
ip.startsWith('127.') ||
ip.startsWith('169.254.') ||
ip.startsWith('192.168.') ||
/^172\.(1[6-9]|2\d|3[01])\./.test(ip)
);
}
return ip === '::1' || ip.startsWith('fe80:') || ip.startsWith('fc') || ip.startsWith('fd');
}
export async function safeFetchWebhook(rawUrl: string) {
const url = new URL(rawUrl);
if (url.protocol !== 'https:') throw new Error('Only HTTPS allowed');
const { address } = await lookup(url.hostname);
if (isPrivateOrLinkLocal(address)) throw new Error('Blocked private/metadata IP');
return fetch(url, { redirect: 'error' });
}When to use / when to avoid
- Use SameSite=Lax + CSRF token + Origin/Sec-Fetch-Site validation on all cookie-authenticated mutations.
- Use an explicit domain allowlist wherever possible for server-side outbound fetches.
- Enable IMDSv2 on cloud VMs and block 169.254.169.254 from application egress.
- Do not rely on CORS alone to stop CSRF—simple form POSTs bypass CORS preflight.
- Do not validate only the URL string against "localhost" (attackers use 127.0.0.1, [::1], 0.0.0.0, or DNS records pointing to 127.0.0.1).
How to implement
Harden cookies and state-changing routes
Set SameSite=Lax; HttpOnly; Secure and verify Origin / Sec-Fetch-Site + CSRF token on POST/PUT/DELETE.
Route outbound fetches through a safe client
Centralize fetch calls for user URLs behind an allowlist, DNS IP check, and redirect: 'error'.
Enforce network-level egress controls
Use Kubernetes NetworkPolicy or cloud security groups so app pods cannot reach internal metadata IPs at all.
Pros / Cons
- Layered CSRF checks (SameSite + token + Origin) work across old and modern browsers.
- Network egress policies + IMDSv2 stop SSRF even if an application parser has a bypass.
- DNS rebinding protection in Node/JS requires pinning the resolved IP in the HTTP agent, not just checking dns.lookup() before fetch().
- Allowlists can feel restrictive when customers bring arbitrary webhook URLs.
Relations
Check yourself
Check Yourself
1. Why is CORS not a sufficient defense against CSRF?
2. An SSRF validator checks that a hostname is not '169.254.169.254', then calls fetch(url) with redirects enabled. How can an attacker bypass this?
Sources
Related Notes
SQL Injection & Parameterized Queries
How SQL injection happens, why parameterized queries separate code from data, ORM raw-query escape hatches, and least-privilege database users.
HTTP Security Headers Cheatsheet
Practical reference for CSP, HSTS (and preload caveats), X-Content-Type-Options, Referrer-Policy, Permissions-Policy, frame-ancestors, and COOP/COEP using Cloudflare Pages _headers.