Cybersecurity-Mastery

Home › Vulnerabilities › Cross-Site Request Forgery

Cross-Site Request Forgery

State-changing requests, token patterns, SameSite behaviour and CSRF-in-JSON edge cases.

Intermediate⌨ ~48 min hands-on📖 ~16 min read

▶ Here to build, not read? Jump to the Hands-On Practice.

Prerequisites: Cookies · Session Management · HTTP for Security Testing

Overview

Cross-Site Request Forgery abuses the browser's habit of automatically attaching a user's credentials (cookies, HTTP auth) to every request to a site, regardless of who initiated it. If an application decides "this request carries a valid session cookie, therefore the user intended it", an attacker can forge a state-changing request from a page the victim visits elsewhere, and the browser will send it fully authenticated. The user is the confused deputy: their browser acts on the attacker's behalf.

CSRF only affects actions that rely on ambient credentials and change state (transfer money, change email, add an admin). The defence is to require proof that the request came from your own application — a value the attacker cannot know or send cross-site — via anti-CSRF tokens, and to lean on the browser's SameSite cookie attribute, which stops cookies riding along on cross-site requests in the first place.

How it works

A vulnerable flow: the bank's "change email" endpoint accepts a POST with the new address and trusts the session cookie. The attacker hosts a page with an auto-submitting form:

html
<form action="https://bank.example/account/email" method="POST">
  <input type="hidden" name="email" value="attacker@evil.com">
</form>
<script>document.forms[0].submit()</script>

When the logged-in victim opens it, the browser attaches their bank cookie and the change succeeds. The attacker never sees the response (the same-origin policy hides it) — they do not need to; the side effect already happened. The fix breaks the one assumption the attack relies on: that a valid cookie implies user intent. A per-session, unpredictable token echoed in the form and verified server-side supplies the missing proof of intent, because the attacker's cross-site page cannot read it.

flowchart TD
    A["Cross-Site Request Forgery"] --> B["Concepts & terminology"]
    A --> C["Internal mechanics"]
    C --> D["Trust boundaries"]
    D --> E["Attack surface"]
    D --> F["Defensive controls"]
    E --> G["Detection & telemetry"]
    F --> G
    G --> H["Verification in the lab"]
🔑 Key terms
  • Ambient authority — Credentials the browser attaches automatically (cookies, HTTP auth) regardless of request origin.
  • Anti-CSRF token (synchronizer token) — An unpredictable per-session value the server issues and verifies to prove same-origin intent.
  • SameSite cookie — A cookie attribute (Lax/Strict/None) controlling whether cookies ride on cross-site requests.
  • Double-submit cookie — A stateless CSRF defence comparing a token in a cookie against one in the request body.
  • State-changing request — A request with a side effect (write/delete) — the only kind CSRF targets.
  • Login CSRF — Forcing a victim to log in as the attacker, poisoning their session.
Example
In the wild. Home-router CSRF (widespread, 2010s). Malicious pages issued forged requests to routers'

web interfaces (often still on default credentials) to change DNS servers, silently redirecting victims' traffic. It shows CSRF's reach beyond web apps into any cookie/credential-trusting HTTP interface, and why SameSite defaults were a meaningful ecosystem-wide fix.

Hands-On Practice

Tip
This is the main event. Bring up the lab, then work the walkthrough — every command has a ▸ Run button (needs the lab runner) and a 📋 Copy button. ~48 min, Kali attacker, fully local.

Mission. Forge a state-changing request from an attacker page, then defend with a token and SameSite.

🧪 Lab setup — Vulnerabilities

  • bWAPP / DVWA / Juice Shop — the web bug targets (see the Web Security part environment)
  • pwn-box — Ubuntu build/debug container for buffer/heap/format-string labs
docker-compose.yml
# vuln-lab/docker-compose.yml  —  Vulnerabilities part environment
services:
  bwapp:
    image: raesene/bwapp
    ports: ["8081:80"]
    networks: [labnet]
  dvwa:
    image: vulnerables/web-dvwa
    ports: ["8082:80"]
    networks: [labnet]
  pwn-box:
    image: ubuntu:22.04
    container_name: pwn-box
    cap_add: ["SYS_PTRACE"]          # allow gdb inside the container
    security_opt: ["seccomp=unconfined"]
    command: sleep infinity
    networks: [labnet]

networks:
  labnet:
    driver: bridge

Target for this lesson: bWAPP → CSRF (Change Password/Secret) at http://localhost:8081. Full setup: Vulnerabilities lab environment.

Guided walkthrough

1Capture the state-changing request
command
# In Burp, change the bWAPP secret and read the POST
Expected output
POST /csrf_1.php  body: password_new=x&password_conf=x&action=change
This is the request you'll forge — note it relies only on the session cookie.
2Build an attacker page
command
<form action="http://localhost:8081/csrf_1.php" method=POST>
 <input name=password_new value=hacked>
 <input name=password_conf value=hacked>
 <input name=action value=change></form>
<script>document.forms[0].submit()</script>
Expected output
Save as evil.html and open it while logged into bWAPP.
The browser attaches the bWAPP cookie automatically — the change succeeds.
3Confirm the forgery worked
command
# log in with the new value the attacker set
Expected output
The secret/password changed without the user's intent.
A valid cookie was treated as user intent — the core CSRF flaw.
4Fix: token + SameSite
command
# add a per-session csrf token to the form and verify server-side; set cookie SameSite=Lax
Expected output
The forged POST is now rejected (missing/invalid token); cross-site cookies stop riding along.
The attacker's page can't read the token and can't send the cookie cross-site.

Live terminal

kali@csrf — start the lab runner for a live shelloffline
Start the Lab Runner (see labserver/README.md), then click Connect lab runner and paste the token. Until then, copy commands from the walkthrough and run them in your own Kali terminal.
$

Try it yourself

Note
Try each for real. Open the hint only when stuck, the solution only to check.

Challenge 1. Does the attack still work if the endpoint uses GET instead of POST? Demonstrate.

Hint

An <img> tag issues a GET cross-site with cookies.

Solution

<img src="http://localhost:8081/csrf_1.php?password_new=x&password_conf=x&action=change"> — yes, GET is worse.

Challenge 2. Set the session cookie to SameSite=Strict and explain what breaks for legitimate users.

Hint

Strict blocks cookies even on top-level navigation from other sites.

Solution

Following a link from email won't carry the session — you land logged out; Lax is the usual balance.

Challenge 3. Bypass a CSRF defence that only checks the Referer header.

Hint

Referer can be absent or partially controllable.

Solution

Strip the Referer (<meta name=referrer content=no-referrer>) or use an allowed-prefix trick; hence tokens, not Referer, are the control.

Quick quiz

Why does an anti-CSRF token stop the attack?
The token is unpredictable and same-origin-readable only; a cross-site page can send the cookie but not the token.

Detect & defend (blue-team view)

  • Server-side: log requests whose Origin/Referer is cross-site on state-changing endpoints.
  • A spike of state changes with mismatched Origin is a CSRF-attempt signal.

Skills check

You can move on when you can, without notes:

Going deeper — Defending correctly

Layer these; do not rely on any single one:

  1. SameSite cookies — set session cookies SameSite=Lax (or Strict for sensitive apps). This alone stops most cross-site cookie-borne CSRF, but is a browser behaviour, not a guarantee for every client.
  2. Anti-CSRF tokens — issue a per-session (or per-request) token, embed it in forms/headers, and verify it server-side on every state-changing request. Frameworks (Django, Rails, Spring) provide this — use it.
  3. Custom-header requirement for APIs — require a header like X-Requested-With that cross-site forms cannot set, backed by CORS.
  4. Re-authentication / step-up for the most sensitive actions (change password, transfer funds).

Non-defences: checking the Referer alone (strippable/absent), using GET for writes (worst case), or relying on obscurity.

Check Yourself

Quick self-test — answers hidden. If you can't answer without notes, redo the relevant walkthrough step.

Q1. In one sentence, what security problem does Cross-Site Request Forgery address or create?

Show answer

Cross-Site Request Forgery matters because its behaviour determines where trust is placed; misplacing that trust is the root of the associated bug class.

Q2. Name one trust boundary involved in Cross-Site Request Forgery and what crosses it.

Show answer

Any point where attacker-influenced data meets privileged processing — e.g. user input reaching an interpreter, or a token reaching a verifier.

Q3. Give one attack against Cross-Site Request Forgery and the single control that most reduces its impact.

Show answer

State the attack precisely, then the primary control (validation, encoding, isolation, authentication, or least privilege) — not a laundry list.

Interview angles

  • Walk me through how Cross-Site Request Forgery works, then tell me where you would attack it.
  • How would you detect Cross-Site Request Forgery being abused in an environment you defend?
  • What is the difference between mitigating and eliminating the risk associated with Cross-Site Request Forgery?

Pitfalls & Best Practice

Common mistakes

  • Assuming SameSite defaults protect you everywhere — some clients and SameSite=None cookies still ride cross-site.
  • Validating the CSRF token only on some endpoints, leaving others exposed.
  • Using GET for state-changing actions, making CSRF trivial and cache-leaky.
  • Relying on the Referer/Origin header alone, which can be absent or spoofed in some contexts.
  • Exempting JSON APIs from CSRF thinking they are immune — they are not if they accept form-encoded bodies or use cookies.

Do this instead

  • Set session cookies SameSite=Lax or Strict, plus Secure and HttpOnly.
  • Use your framework's synchronizer-token protection on every state-changing request.
  • Require a custom header (enforced by CORS) for API state changes.
  • Step up authentication for the highest-impact actions.
  • Test that forged cross-site POSTs are rejected as part of your regression suite.

Reference

MITRE ATT&CK Mapping

No single ATT&CK technique maps cleanly to this concept. Once you apply it offensively or defensively, map the specific behaviour using the ATT&CK chapter.

OWASP Mapping

CWE Mapping

CWEWeakness
CWE-352Cross-Site Request Forgery

CAPEC Mapping

CAPECAttack pattern
CAPEC-62Cross Site Request Forgery

CVE References

  • No canonical CVE for a concept page. Search the NVD for concrete instances when studying real cases.

NIST References

RFC References

  • No governing RFC for this topic. Where a protocol is involved, its RFC is linked from the relevant networking chapter.

Research Papers

  • Reflections on Trusting Trust — Ken Thompson, 1984
  • Smashing the Stack for Fun and Profit — Aleph One, Phrack 49, 1996
  • The Protection of Information in Computer Systems — Saltzer & Schroeder, 1975

Books

  • The Web Application Hacker's Handbook, 2nd ed. — Stuttard & Pinto
  • Real-World Bug Hunting — Peter Yaworski
  • The Tangled Web — Michal Zalewski
  • Web Security for Developers — Malcolm McDonald

Official Documentation


Part of the Vulnerabilities section of Cybersecurity-Mastery. 🟡 Intermediate · ~48 min hands-on · Last updated 2026-08-12.

Cybersecurity-Mastery — interactive security learning · runs locally