These are the notes for Cybersecurity Fundamentals (defensive), episode 42. In episodes 40 and 41 an attacker's script ran inside our pages. Today no script runs on our shop at all: another website makes the user's browser send a request to our shop, and the user's cookies go along automatically. That is cross-site request forgery (CSRF). We build the defences one by one: synchroniser tokens, Origin / Sec-Fetch-Site checks, custom headers for APIs, signed double-submit cookies, SameSite cookies, protection for the login form and cookie prefixes. Every term is explained the first time it appears, and the Glossary at the end defines them all again.
Neha, Ravi, the shop and every value are made up. The Python demos are toy request handlers that take dictionaries instead of real network requests. The browser behaviour was checked separately on 11 Nov 2026 with headless Chromium 153 (a real browser without a window, driven by Playwright) against small local Python servers: the shop on localhost:8902 and an "attacker" page on 127.0.0.1:8903, which the browser treats as two different sites. Every log line below is copied from those runs. Python samples run with Python 3.13. shop.example and evil.example are reserved example domains.
The problems you'll solve
| Problem | Idea it teaches |
|---|---|
| A prize page changes Neha's address | CSRF, session cookies, ambient authority |
| Prove the form came from our page | Synchroniser token pattern, hidden fields, constant-time compare |
| Ask the browser who sent the request | Origin, Referer, Fetch Metadata (Sec-Fetch-Site), same-site vs same-origin |
| APIs called from JavaScript | Custom request headers, CORS preflight |
| No sessions stored on the server | Double-submit cookie: naive vs signed (HMAC) |
| Don't send the cookie at all | SameSite=Strict, Lax, None; the 2-minute Lax+POST exception |
| A forged login; planted cookies | Login CSRF, pre-sessions, __Host- and __Secure- prefixes |
| Don't mix them up | CSRF vs XSS |
Problem 1: a request Neha never sent
Basic words first:
- A cookie is a small
name=valuethe server asks the browser to store (with aSet-Cookieheader). The browser sends it back in aCookieheader on later requests to that site. - A session cookie holds a random session ID that the server maps to a logged-in user (episode 28).
session=c0ffee42→ "this is Neha". - A state-changing request changes something on the server: change an address, transfer money, delete an account. These should use
POST,PUT,PATCHorDELETE, neverGET.
Neha is logged in to our shop. In another tab she opens a "prize" page on evil.example. It contains a hidden form pointing at the shop and one line of JavaScript that submits it:
<form id=f method=post action="https://shop.example/change-address">
<input name=addr value="1 Evil Lane">
</form>
<script>f.submit()</script>
Her browser sends the request to the shop and attaches her session cookie, as it always does.
Demo 1: the obvious defence, "check the session cookie"
# A toy shop. The session cookie is the only check.
SESSIONS = {"c0ffee42": "Neha"} # cookie value -> logged-in user
ADDRESS = {"Neha": "12 MG Road, Pune"}
def change_address(req):
user = SESSIONS.get(req["cookies"].get("session"))
if not user:
return "401 please log in"
ADDRESS[user] = req["form"]["addr"]
return f"200 {user}'s address is now {ADDRESS[user]}"
# 1. Neha, on the shop's own page
print(change_address({"cookies": {"session": "c0ffee42"},
"form": {"addr": "7 Park Street, Pune"}}))
# 2. a page on evil.example auto-submits a form to the shop.
# Her browser attaches her cookie, as it always does.
print(change_address({"cookies": {"session": "c0ffee42"},
"form": {"addr": "1 Evil Lane"}}))
200 Neha's address is now 7 Park Street, Pune
200 Neha's address is now 1 Evil Lane
Why it failed: a cookie proves which browser sent a request, not which page asked for it, or whether Neha meant to. OWASP defines CSRF as an attack that "tricks an authenticated user's web browser into performing an unwanted action on a trusted site".
Ambient authority
Ambient authority means rights that ride along automatically with every request, without the requesting page proving anything: cookies, saved HTTP Basic credentials, TLS client certificates, even the user's network position. CSRF abuses it.
evil.example page ──form──▶ Neha's browser (adds her cookie) ──▶ shop: "it's Neha"
The attacker's page can make the browser send a request, but the browser's same-origin policy won't let that page read the reply. So CSRF targets actions that change state, not data theft.
Problem 2: the synchroniser token
Real-life example: the token slip at a bank
| At a bank | In the shop |
|---|---|
| A token slip from the machine inside the branch | A CSRF token: a secret random value in the shop's own form |
| The counter serves only valid slips | The server checks the token; missing or wrong → 403 |
In the synchroniser token pattern, the server stores a random token in the user's session and puts it in its own forms as a hidden field (<input type="hidden">, a form value the user doesn't see). The evil page can't read the shop's page, so it can't learn the token.
Demo 2: synchroniser token
# Synchroniser token: a secret the shop puts in its OWN form
import secrets, hmac
SESSIONS = {"c0ffee42": {"user": "Neha", "csrf": secrets.token_urlsafe(32)}}
def address_form(cookie): # the shop's page, served to Neha
tok = SESSIONS[cookie]["csrf"]
return f'<input type="hidden" name="csrf" value="{tok}">'
def change_address(req):
s = SESSIONS.get(req["cookies"].get("session"))
if not s:
return "401 please log in"
sent = req["form"].get("csrf", "")
if not hmac.compare_digest(sent, s["csrf"]): # constant-time compare
return "403 CSRF token missing or wrong"
return f"200 {s['user']}'s address is now {req['form']['addr']}"
page = address_form("c0ffee42")
tok = page.split('value="')[1].split('"')[0] # the browser submits it back
print(page[:60] + "...")
print("own form :", change_address({"cookies": {"session": "c0ffee42"},
"form": {"addr": "7 Park Street", "csrf": tok}}))
print("evil form:", change_address({"cookies": {"session": "c0ffee42"},
"form": {"addr": "1 Evil Lane"}}))
print("guessed :", change_address({"cookies": {"session": "c0ffee42"},
"form": {"addr": "1 Evil Lane", "csrf": "1234"}}))
Output (the token is different on every run):
<input type="hidden" name="csrf" value="ye88Nc13k_5BhA9GDKaK...
own form : 200 Neha's address is now 7 Park Street
evil form: 403 CSRF token missing or wrong
guessed : 403 CSRF token missing or wrong
secrets.token_urlsafe(32): 32 random bytes (256 bits) from a CSPRNG, so it can't be guessed.hmac.compare_digestis a constant-time comparison (episode 27): it takes the same time however many characters match, so timing doesn't leak the token.
OWASP's rules for tokens:
- Per-session tokens (one per login) are fine; per-request tokens are "more secure than per-session tokens" but can break the Back button.
- Never put a token in a GET URL: "GET requests can potentially leak CSRF tokens" through history, logs and the
Refererheader. - "A CSRF token should not be transmitted in a cookie for synchronized patterns": send it in the page and get it back in a hidden field or a custom header.
Problem 3: ask the browser who sent it
Real requests logged by our shop server, from headless Chromium:
POST /change-address (Neha clicks the shop's own button)
Origin: http://localhost:8902
Sec-Fetch-Site: same-origin
Referer: http://localhost:8902/login
POST /change-address (auto-submitted from the attacker's page)
Origin: http://127.0.0.1:8903
Sec-Fetch-Site: cross-site
Referer: http://127.0.0.1:8903/
- The
Originheader names the origin (scheme + host + port) of the page that sent the request. - Fetch Metadata headers describe the request's context.
Sec-Fetch-Sitesays how the sender relates to us:same-origin,same-site,cross-site, ornone(the user typed the URL or used a bookmark). Page scripts can't change headers starting withSec-. - The
Refererheader carries the address of the page the request came from; it's the oldest signal but often trimmed byReferrer-Policyor removed.
Same site vs same origin
An origin is scheme + host + port: https://shop.example:443. A site is scheme + the registrable domain: https://shop.example. So https://blog.shop.example is same-site but a different origin. If someone takes over the blog subdomain, its requests are same-site. Accept only same-origin for state changes.
Demo 3: checking Sec-Fetch-Site, then Origin
OWASP calls Sec-Fetch-Site "the primary signal for CSRF protection", with Origin/Referer as the fallback for older browsers, and says a missing header or Origin: null is not proof of a same-origin request.
# Who sent it? Check Fetch Metadata first, then Origin.
SHOP = "https://shop.example"
def allowed(headers):
site = headers.get("Sec-Fetch-Site") # sent by modern browsers
if site is not None:
return site in ("same-origin", "none") # none = typed in the address bar
origin = headers.get("Origin") # fallback for older browsers
if origin is None or origin == "null":
return False # not proof: use the token
return origin == SHOP
CASES = {
"shop's own form": {"Sec-Fetch-Site": "same-origin", "Origin": SHOP},
"evil.example form": {"Sec-Fetch-Site": "cross-site", "Origin": "http://evil.example"},
"old browser, own form": {"Origin": SHOP},
"old browser, evil": {"Origin": "http://evil.example"},
"sandboxed iframe": {"Origin": "null"},
"no headers at all": {},
}
for name, h in CASES.items():
print(f"{name:22} -> {'accept' if allowed(h) else 'reject'}")
shop's own form -> accept
evil.example form -> reject
old browser, own form -> accept
old browser, evil -> reject
sandboxed iframe -> reject
no headers at all -> reject
Origin: null is sent by sandboxed iframes, some redirects and file: pages.
APIs: a custom request header
For endpoints called by your own JavaScript, require a custom request header (any header a plain HTML form can't set), e.g.
fetch('/api/address', {method: 'POST', headers: {'X-Requested-With': 'shop'}, body: ...})
An HTML form can't add custom headers. A script on another site can try, but the browser's CORS rules first send a preflight request (OPTIONS) asking "may this origin send this header?"; if your server doesn't say yes, the real request is never sent. OWASP calls this "particularly well suited for AJAX or API endpoints", as long as your CORS policy allows only trusted origins.
Problem 4: no server-side session
A stateless app keeps no session data on the server (for example, ten servers with no shared store), so there's nowhere to remember a token. The double-submit cookie puts a random token in a cookie and sends it in a header or field; the server checks that the two match. The attacker's page can't read the cookie, so it can't copy it.
But cookie injection breaks the naive version: a sibling subdomain (or a man-in-the-middle on plain HTTP) can plant a cookie in Neha's browser, so the attacker chooses both copies.
Demo 4: naive vs signed double-submit
An HMAC (episode 12) is a keyed fingerprint: only someone with the secret key can make a valid one.
# Double-submit cookie: naive vs signed (HMAC bound to the session)
import hmac, hashlib, secrets
SECRET = secrets.token_bytes(32) # only the server knows it
def naive_ok(cookie_tok, header_tok): # "do they match?"
return hmac.compare_digest(cookie_tok, header_tok)
def make_signed(session_id):
r = secrets.token_hex(16)
mac = hmac.new(SECRET, f"{session_id}!{r}".encode(), hashlib.sha256).hexdigest()
return f"{r}.{mac}"
def signed_ok(session_id, cookie_tok, header_tok):
if not hmac.compare_digest(cookie_tok, header_tok):
return False
r, mac = header_tok.split(".")
good = hmac.new(SECRET, f"{session_id}!{r}".encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(mac, good)
# The attacker controls a sibling subdomain and plants a cookie on Neha's browser,
# then sends the same value in the request.
planted = "aaaa.bbbb"
print("naive , planted pair :", naive_ok(planted, planted))
print("signed, planted pair :", signed_ok("neha-session", planted, planted))
real = make_signed("neha-session")
print("signed, Neha's own :", signed_ok("neha-session", real, real))
print("signed, other session:", signed_ok("ravi-session", real, real))
naive , planted pair : True
signed, planted pair : False
signed, Neha's own : True
signed, other session: False
OWASP recommends the signed double-submit cookie (bound to the session with an HMAC); the naive one "remains vulnerable to cookie injection attacks" and is "documented for reference only".
Problem 5: SameSite cookies
Real-life example: a school ID card
| A school ID card | A cookie's SameSite |
|---|---|
| Shown only inside school | SameSite=Strict: never sent on cross-site requests, even link clicks |
| Also shown at the gate when you walk in, not for errands | SameSite=Lax: sent on top-level navigations with GET (clicking a link to the site), not on cross-site POSTs, images, iframes or scripts |
| Shown everywhere | SameSite=None; Secure: always sent; must be Secure (HTTPS only) |
A top-level navigation means the address in the browser's address bar changes (you land on the site), as opposed to a request made inside another page (an image, a frame, a fetch).
What Chromium really sent
Our shop set four cookies: s_none (SameSite=None; Secure), s_lax (Lax), s_strict (Strict) and s_default (no SameSite attribute). Chromium reported the default one as Lax. Then we made requests and logged the Cookie header:
| Request | Cookies the shop received |
|---|---|
Shop's own form, POST (Sec-Fetch-Site: same-origin) |
s_none=1; s_lax=1; s_strict=1; s_default=1 |
| Attacker's link click, top-level GET | s_none=1; s_lax=1; s_default=1 |
Attacker's <img src=...>, GET |
s_none=1 |
| Attacker's auto-submitted form, POST (cookie just set) | s_none=1; s_default=1 |
| Same form 125 seconds after login | s_none=1 |
The surprise in row 4 is documented in the Chromium SameSite FAQ: cookies with no SameSite are treated as Lax (since the Chrome 80 rollout in 2020), but as a temporary exception for some single sign-on flows, "a cookie that is at most 2 minutes old will be sent on a top-level cross-site POST request". After 2 minutes, it wasn't. Lesson: set SameSite explicitly.
SameSite is a seatbelt, not the brakes
- OWASP: "Chromium-based browsers treat cookies without a SameSite attribute as Lax"; Firefox and Safari do not.
Laxstill sends cookies on top-level GET link clicks, so GET must never change state.SameSitedoes nothing against a same-site sibling subdomain.- OWASP: SameSite "does not replace a proper CSRF defense in most deployments".
A good session cookie:
Set-Cookie: __Host-session=...; Path=/; Secure; HttpOnly; SameSite=Lax
(HttpOnly: page scripts can't read it, episode 28. Secure: HTTPS only.)
Problem 6: login CSRF and cookie prefixes
Login CSRF
An evil page can submit the shop's login form with the attacker's username and password. Neha's browser is now logged in to the attacker's account; she searches, saves her address, maybe a card, and later the attacker logs in and reads it all. That's login CSRF. OWASP: it "can be mitigated by creating pre-sessions" (a session with a CSRF token before login, so the login form has a token too), and the server must create a new session after login to avoid session fixation (an attacker choosing your session ID in advance).
Cookie prefixes
Cookie injection came up again and again: a sibling subdomain planting or overwriting cookies. Cookie prefixes are rules the browser enforces based on the cookie's name:
__Host-: must beSecure, must havePath=/, must not have aDomainattribute, so it belongs to exactly one host. OWASP: it "Cannot be (over)written from another subdomain".__Secure-: must beSecure(weaker).
Our server sent these Set-Cookie headers to Chromium (from localhost, which Chromium treats as a secure context):
| Set-Cookie | Kept? |
|---|---|
__Host-good=1; Path=/; Secure |
kept |
__Host-dom=1; Domain=localhost; Path=/; Secure |
dropped (has Domain) |
__Host-path=1; Path=/app; Secure |
dropped (Path is not /) |
__Host-insecure=1; Path=/ |
dropped (no Secure) |
__Secure-ok=1; Path=/; Secure |
kept |
__Secure-no=1; Path=/ |
dropped (no Secure) |
plain=1; Path=/ |
kept |
CSRF vs XSS
| CSRF | XSS | |
|---|---|---|
| What runs | nothing on the target site; the attacker's page sends a request | the attacker's script runs inside the target page |
| Can read replies? | no | yes, including the CSRF token |
| Fix | tokens, Sec-Fetch-Site/Origin checks, SameSite |
output encoding, sanitising, CSP (episodes 40-41) |
OWASP: "Cross-Site Scripting (XSS) can defeat all CSRF mitigation techniques!" Fix XSS first.
The whole chain
- A cookie-only check accepted a forged form → CSRF, because cookies are ambient authority.
- Prove the form is ours → synchroniser token (hidden field, constant-time compare).
- Ask who sent it →
Sec-Fetch-Site, thenOrigin; custom headers + CORS for APIs. - Stateless apps → signed double-submit cookie.
- Keep cookies home → SameSite, set explicitly; GET never changes state.
- Forged logins and planted cookies → pre-sessions, new session after login,
__Host-prefix.
Common mistakes (and what they cause)
| Mistake | What happens (real output) | Why | Fix |
|---|---|---|---|
| Only checking the session cookie | 200 Neha's address is now 1 Evil Lane |
the browser attaches cookies itself | CSRF token or Sec-Fetch-Site check |
| Changing state on GET | Lax cookies still sent: GET /orders got s_lax=1 from a cross-site link |
Lax allows top-level GET | use POST/PUT/PATCH/DELETE |
| Naive double-submit | naive , planted pair : True |
the attacker plants both copies | HMAC-signed, bound to the session |
| Trusting a missing Origin | would accept no headers at all |
missing or null is not proof |
reject, or require the token |
| Relying on the browser default SameSite | the 0-second-old default cookie went on a cross-site POST | Lax+POST exception; Firefox/Safari differ | SameSite=Lax (or Strict) explicitly |
| Token in a GET URL | token in history, logs, Referer |
URLs leak | hidden field or header |
Accepting same-site |
a taken-over subdomain can send requests | same site ≠ same origin | accept only same-origin (and none) |
Mini project: a toy shop with CSRF protection in layers
Session cookie with the __Host- prefix and SameSite=Lax, a Sec-Fetch-Site/Origin check, and a synchroniser token.
# Mini project: a toy shop with CSRF protection in layers.
# 1) __Host- session cookie, SameSite=Lax, HttpOnly, Secure
# 2) Sec-Fetch-Site / Origin check 3) synchroniser token in the form
# Run: python3 mini.py then open http://localhost:8000/
import http.server, secrets, hmac
from urllib.parse import parse_qs
SHOP = "http://localhost:8000"
SESSIONS = {} # session id -> {"user", "csrf", "addr"}
def from_us(h):
site = h.get("Sec-Fetch-Site")
if site is not None:
return site in ("same-origin", "none")
return h.get("Origin") == SHOP
class Shop(http.server.BaseHTTPRequestHandler):
def session(self):
for part in (self.headers.get("Cookie") or "").split(";"):
k, _, v = part.strip().partition("=")
if k == "__Host-session" and v in SESSIONS:
return SESSIONS[v]
def reply(self, code, body, cookie=None):
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
if cookie:
self.send_header("Set-Cookie", f"__Host-session={cookie}; Path=/; Secure; HttpOnly; SameSite=Lax")
self.end_headers(); self.wfile.write(body.encode())
def do_GET(self): # log in as Neha and show the form
sid = secrets.token_urlsafe(32)
SESSIONS[sid] = {"user": "Neha", "csrf": secrets.token_urlsafe(32), "addr": "12 MG Road"}
s = SESSIONS[sid]
self.reply(200, f"""<form method=post action=/change-address>
<input type=hidden name=csrf value="{s['csrf']}"><input name=addr value="7 Park Street">
<button>Save</button></form>""", cookie=sid)
def do_POST(self):
form = {k: v[0] for k, v in parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode()).items()}
s = self.session()
if not s:
return self.reply(401, "please log in")
if not from_us(self.headers):
print("rejected: Sec-Fetch-Site =", self.headers.get("Sec-Fetch-Site"), flush=True)
return self.reply(403, "cross-site request rejected")
if not hmac.compare_digest(form.get("csrf", ""), s["csrf"]):
print("rejected: bad CSRF token", flush=True)
return self.reply(403, "CSRF token missing or wrong")
s["addr"] = form["addr"]
print("saved:", s["user"], "->", s["addr"], flush=True)
self.reply(200, "saved")
def log_message(self, *a): pass
if __name__ == "__main__":
http.server.ThreadingHTTPServer(("127.0.0.1", 8000), Shop).serve_forever()
Real runs:
- In Chromium: the cookie was stored as
__Host-session Lax httpOnly=true; clicking the shop's own button →saved; a cross-site auto-submitted form →please log in(SameSite=Lax kept the cookie home, so the first layer already stopped it). - With
curl, forcing the cookie in to test the other layers:
1 cross-site, cookie forced:
cross-site request rejected
2 same-origin, no token:
CSRF token missing or wrong
3 same-origin, token:
saved
Server log: rejected: Sec-Fetch-Site = cross-site, rejected: bad CSRF token, saved: Neha -> 7 Park Street.
(Real apps use their framework's built-in CSRF protection, e.g. Django's CsrfViewMiddleware or Flask-WTF's CSRFProtect, instead of writing it by hand.)
Practice
- Add a CSRF token to a change-password form.
- Make
allowed()explain why it rejectssame-site. - Set a
__Host-session cookie correctly. - Why does XSS beat every CSRF defence?
Solution 1
Same pattern as Demo 2: the change-password page includes <input type="hidden" name="csrf" value="{session csrf}">, and the handler rejects with 403 unless hmac.compare_digest(form["csrf"], session["csrf"]). For sensitive actions also ask for the current password (re-authentication, episode 28), which a forged request can't supply.
Solution 2
# Practice 2 solution: treat "same-site" as NOT trusted, but say why
SHOP = "https://shop.example"
def allowed(headers):
site = headers.get("Sec-Fetch-Site")
if site is not None:
if site == "same-site":
return False, "same-site: a sibling subdomain, not us"
return site in ("same-origin", "none"), site
origin = headers.get("Origin")
if origin in (None, "null"):
return False, "no proof: require the CSRF token"
return origin == SHOP, "Origin " + origin
for h in [{"Sec-Fetch-Site": "same-site", "Origin": "https://blog.shop.example"},
{"Sec-Fetch-Site": "same-origin"}, {"Origin": "null"}]:
print(allowed(h))
(False, 'same-site: a sibling subdomain, not us')
(True, 'same-origin')
(False, 'no proof: require the CSRF token')
Solution 3
Set-Cookie: __Host-session=<random>; Path=/; Secure; HttpOnly; SameSite=Lax
No Domain attribute, Path=/, Secure. The mini project sends exactly this; Chromium stored it (__Host-session Lax httpOnly=true).
Solution 4
An XSS script runs inside the shop's own page: its requests are same-origin, it can read the CSRF token from the page, and the browser attaches all cookies. Every CSRF check passes. That's why OWASP warns XSS "can defeat all CSRF mitigation techniques".
Quick quiz
POST /transfer with Neha's session cookie. Which should the shop reject?
A: Sec-Fetch-Site: same-origin, valid token · B: Sec-Fetch-Site: none (typed URL, GET /orders) · C: Sec-Fetch-Site: cross-site, no token · D: Origin: https://shop.example, valid token
Answer
C. It comes from another site and carries no CSRF token: a forged request. A and D come from the shop with a valid token; B is a normal page load typed into the address bar.
Interview questions
- What is CSRF and why does it work? Another site makes the victim's browser send a state-changing request; it works because browsers attach cookies automatically (ambient authority).
- Explain the synchroniser token pattern. Random token stored in the session, embedded in forms, compared in constant time on every state-changing request.
- What is Fetch Metadata?
Sec-Fetch-*headers the browser adds;Sec-Fetch-Site: cross-siteon a POST is a strong CSRF signal. - Same-site vs same-origin? Origin = scheme+host+port; site = scheme+registrable domain. Subdomains are same-site, cross-origin.
- SameSite Lax vs Strict vs None? Lax: sent on top-level GET navigations only; Strict: never cross-site; None: always, needs Secure.
- Is SameSite enough? No: defaults differ by browser, Lax allows GET, same-site attackers, and the Lax+POST exception.
- Why sign double-submit cookies? The naive version is beaten by cookie injection; the HMAC binds the token to the session.
- What is login CSRF? Forging a login into the attacker's account; fix with pre-session tokens and a fresh session after login.
- What does
__Host-guarantee? Secure, Path=/, no Domain: only this host can set it. - Do APIs using
Authorization: Bearerheaders need CSRF tokens? Usually not, since the browser doesn't attach that header automatically; cookie-authenticated APIs do.
Glossary
| Term | Meaning, with an example |
|---|---|
| Cookie | A name=value stored by the browser and sent back to the site: Cookie: session=c0ffee42. |
| Session cookie | A cookie holding a random session ID the server maps to a logged-in user. |
| State-changing request | A request that changes server data (change address, transfer); should be POST/PUT/PATCH/DELETE. |
| CSRF (cross-site request forgery) | Another site makes your browser send a request to a site where you're logged in. |
| Ambient authority | Rights attached automatically to every request: cookies, Basic auth, client certificates. |
| Same-origin policy | The browser rule that a page can't read responses from another origin. |
| CSRF token | A secret random value the site puts in its own forms and checks on submit. |
| Synchroniser token pattern | Token stored in the session + hidden form field; mismatch → 403. |
| Hidden field | <input type="hidden">: a form value sent with the form but not shown. |
| Constant-time comparison | Comparing secrets in a time that doesn't depend on how much matches: hmac.compare_digest. |
| Per-session / per-request token | One token per login vs a new token for every form. |
Origin header |
The origin of the page that sent a request: Origin: https://shop.example. |
Referer header |
The address of the page a request came from (older, less reliable). |
| Fetch Metadata | Sec-Fetch-Site, Sec-Fetch-Mode, Sec-Fetch-Dest: browser-set context headers. |
Sec-Fetch-Site |
same-origin, same-site, cross-site or none (typed URL). |
| Origin | Scheme + host + port: https://shop.example:443. |
| Site | Scheme + registrable domain: https://shop.example (subdomains included). |
Origin: null |
Sent by sandboxed iframes, some redirects, file: pages; not proof of anything. |
| Custom request header | A header forms can't set (e.g. X-Requested-With), required by an API. |
| CORS | Cross-origin resource sharing: rules for which other origins may call or read your server. |
| Preflight | The OPTIONS request a browser sends first to ask permission for a cross-origin request with custom headers. |
| Stateless app | An app that keeps no session data on the server. |
| Double-submit cookie | Token in a cookie and in the request; the server checks they match. |
| Cookie injection | Planting or overwriting a cookie from a sibling subdomain or over plain HTTP. |
| HMAC | A keyed fingerprint; only the key holder can make a valid one (episode 12). |
| Signed double-submit cookie | Token = random + HMAC(secret, session ID + random); bound to the session. |
SameSite |
Cookie attribute controlling cross-site sending: Strict, Lax, None. |
SameSite=Strict |
Never sent on cross-site requests. |
SameSite=Lax |
Sent cross-site only on top-level GET navigations. |
SameSite=None |
Always sent; must also be Secure. |
| Top-level navigation | The address bar changes: clicking a link to the site. |
| Lax+POST exception | Chromium sends a no-SameSite cookie at most 2 minutes old on a top-level cross-site POST. |
Secure |
Cookie sent only over HTTPS. |
HttpOnly |
Cookie hidden from page JavaScript. |
| Login CSRF | Forcing the victim's browser to log in to the attacker's account. |
| Pre-session | A session (with a CSRF token) created before login. |
| Session fixation | An attacker choosing your session ID in advance; fixed by a new session after login. |
| Cookie prefix | A name prefix the browser enforces rules for: __Host-, __Secure-. |
__Host- |
Must be Secure, Path=/, no Domain: can't be set or overwritten from another subdomain. |
__Secure- |
Must be Secure. |
| XSS | Cross-site scripting: the attacker's script runs in your page (episode 40). |
Summary
- Browsers attach cookies automatically, so a cookie never proves intent: that's CSRF.
- Use a CSRF token (synchroniser or signed double-submit), and check
Sec-Fetch-Site(fallbackOrigin); require a custom header for JavaScript APIs. - Set
SameSiteexplicitly (LaxorStrict), plusSecureandHttpOnly; never change state with GET. - Protect the login form too, and start a new session after login.
- Name session cookies with
__Host-. - XSS defeats every CSRF defence: fix XSS first.
Next episode: SSRF and open redirects: when someone tricks our server into sending requests.