Skip to Content
Mengty Learns
Security

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.

explanationintermediateTested with asvs 5.0.0 (V3, V4, V13), owasp_top_10 2025 (A01)Updated Nov 26, 2026

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

TL;DR

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.
CSRF forges requests from the victim's browser; SSRF forges requests from your server.

Solution

Stopping CSRF

  1. Use SameSite=Lax (or Strict) on session cookies so cross-site POST forms do not carry cookies.
  2. Require an unpredictable CSRF token (or custom header validated with Origin / Sec-Fetch-Site checks) on every state-changing POST/PUT/PATCH/DELETE route.
  3. Never mutate state on GET requests (because SameSite=Lax still sends cookies on top-level GET navigations).

Stopping SSRF

  1. Use a domain/scheme allowlist (https: only, exact allowed hosts) whenever business logic permits.
  2. 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).
  3. 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

Overview of CSRF Attack Blocked by SameSite + Token + Origin Check. 3 steps.
Overview3 steps in this flow

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

Overview of SSRF Blocked by Allowlist, Pinned DNS & Redirect Guard. 4 steps.
Overview4 steps in this flow

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

When to use
  • 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.
When to avoid
  • 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

Pros
  • 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.
Cons
  • 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