CSRF: SameSite Cookies and Tokens
Cross-site request forgery uses the second fact of the trust model: the browser attaches a site's cookies to requests that other sites cause. A page on evil.example contains a hidden form that posts to https://bank.lab.test/transfer; the victim, logged in to the bank, opens the page; the browser sends the form with the bank's session cookie, and the bank sees an authenticated transfer. The attacker never sees the response, and doesn't need to. The survey's CSRF lesson covered the idea. Here we look at the defences in depth, because each one has a gap the others fill: SameSite cookies, synchronizer tokens, Origin checks and Fetch Metadata headers. A toy bank in your sandbox shows each defence refusing a forged request.
Definitions
- CSRF conditions: (1) an action changes state, (2) it is authorised only by ambient credentials (cookies, Basic auth, client certificates), (3) its parameters are predictable. Remove any one and CSRF is gone.
- Synchronizer token: a random value bound to the user's session, embedded in each form (hidden field) or sent in a custom header by JavaScript, and checked on every state-changing request. The attacker's page can't read it (same-origin policy).
- Double-submit cookie: the token is in a cookie and in the request; the server compares them. Weaker unless the cookie is signed and bound to the session, because a sibling subdomain can plant cookies.
Originheader: sent by browsers on cross-origin requests and on allPOSTs, naming the page's origin (ornull).Sec-Fetch-Site(Fetch Metadata):same-origin,same-site,cross-siteornone(typed URL, bookmark), set by the browser and not changeable by page script.SameSite=Laxsession cookies: not sent on cross-sitePOSTs, iframes, images orfetch, only on top-levelGETnavigations (cookies lesson).- Login CSRF: forcing the victim into the attacker's account (OAuth flaws showed it through a missing
state).
A forgeable bank and its defences
The toy bank on 127.0.0.1 keeps sessions in a dict and has a /transfer form. curl stands in for two browsers: the victim's genuine form submission (with the token it received and its own Origin), and the attacker page's auto-submitted form (with the victim's cookie, because we model a browser or a cookie that SameSite doesn't stop, the attacker's Origin, and no token, because the attacker can't read it).
cat > bank.py <<'PY'
import hmac, secrets, sys
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler
MODE = sys.argv[1] # none | token | origin
SESSIONS = {"sess-alice-lab": {"user": "alice", "csrf": "tok-" + "a" * 40}} # fixed for the demo; real: secrets.token_urlsafe(32)
BALANCE = {"alice": 1000}
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def app(environ, start_response):
sid = SimpleCookie(environ.get("HTTP_COOKIE", "")).get("sid")
sess = SESSIONS.get(sid.value) if sid else None
def reply(status, text):
start_response(status, [("Content-Type", "text/plain")])
return [text.encode() + b"\n"]
if environ["PATH_INFO"] != "/transfer":
return reply("200 OK", "bank home")
if sess is None:
return reply("401 Unauthorized", "login first")
if environ["REQUEST_METHOD"] != "POST":
return reply("405 Method Not Allowed", "use POST") # never change state on GET
form = parse_qs(environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH") or 0)).decode())
if MODE == "token":
sent = form.get("csrf", [""])[0]
if not hmac.compare_digest(sent, sess["csrf"]):
return reply("403 Forbidden", "CSRF token missing or wrong")
if MODE == "origin":
origin = environ.get("HTTP_ORIGIN")
site = environ.get("HTTP_SEC_FETCH_SITE")
if site not in (None, "same-origin") or origin not in (None, "https://bank.lab.test"):
return reply("403 Forbidden", f"cross-site request refused (Origin={origin}, Sec-Fetch-Site={site})")
amount, to = int(form["amount"][0]), form["to"][0]
BALANCE[sess["user"]] -= amount
return reply("200 OK", f"sent {amount} to {to}; alice now has {BALANCE['alice']}")
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
victim() { curl -s -b 'sid=sess-alice-lab' -H 'Origin: https://bank.lab.test' -H 'Sec-Fetch-Site: same-origin' \
-d "to=bob&amount=50&csrf=tok-$(printf 'a%.0s' $(seq 40))" -w ' [%{http_code}]' http://127.0.0.1:8000/transfer | tr -d '\n'; echo; }
attacker() { curl -s -b 'sid=sess-alice-lab' -H 'Origin: https://evil.example' -H 'Sec-Fetch-Site: cross-site' \
-d 'to=mallory&amount=900' -w ' [%{http_code}]' http://127.0.0.1:8000/transfer | tr -d '\n'; echo; }
for mode in none token origin; do
python3 bank.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
echo "=== defence: $mode"
printf ' victim submits the real form: '; victim
printf ' evil.example auto-submits: '; attacker
printf ' the same as a GET link: '; curl -s -b 'sid=sess-alice-lab' -w ' [%{http_code}]' 'http://127.0.0.1:8000/transfer?to=mallory&amount=900' | tr -d '\n'; echo
kill %1; wait 2>/dev/null
done=== defence: none
victim submits the real form: sent 50 to bob; alice now has 950 [200]
evil.example auto-submits: sent 900 to mallory; alice now has 50 [200]
the same as a GET link: use POST [405]
=== defence: token
victim submits the real form: sent 50 to bob; alice now has 950 [200]
evil.example auto-submits: CSRF token missing or wrong [403]
the same as a GET link: use POST [405]
=== defence: origin
victim submits the real form: sent 50 to bob; alice now has 950 [200]
evil.example auto-submits: cross-site request refused (Origin=https://evil.example, Sec-Fetch-Site=cross-site) [403]
the same as a GET link: use POST [405]
Without a defence the forged transfer goes through: the bank can't tell the victim's click from the attacker's page, because both requests carry the same cookie. With tokens, the forged form lacks the session's token and is refused, while the genuine form works. With Origin / Sec-Fetch-Site checks, the browser's own statement of where the request came from is enough to refuse it, with no change to the forms. In every mode the bank refuses to transfer on GET, which closes the gap that SameSite=Lax leaves (Lax cookies are sent on top-level GET navigations, so a link to a state-changing GET URL would still work).
Layering the defences
| Defence | Stops | Gap |
|---|---|---|
SameSite=Lax (default in Chromium) |
cross-site POSTs, iframes, images, fetch |
state-changing GETs; requests from same-site pages (a compromised or user-content subdomain); older browsers; in Chromium, a cookie without an explicit SameSite is still sent on top-level cross-site POSTs during its first two minutes (the "Lax + POST" mitigation) |
SameSite=Strict |
all cross-site requests | users arriving by link appear logged out; same-site gap remains |
| Synchronizer token | everything where the attacker can't read the page | XSS anywhere in the origin can read tokens; token leaks in URLs |
Origin / Sec-Fetch-Site check |
cross-origin / cross-site requests from browsers | requests with no headers (old browsers, some privacy tools): decide a policy for missing values |
No state change on GET |
link and image-based CSRF | none: it's a design rule |
| Re-authentication for critical actions | everything | user friction; use for e-mail, password, payouts |
Frameworks implement tokens for you (Django's CsrfViewMiddleware, Rails' protect_from_forgery, ASP.NET Core antiforgery, Spring Security's CSRF filter); keep them on. APIs authenticated with an Authorization: Bearer header rather than cookies are not exposed to CSRF, because browsers don't attach that header automatically.
The same-origin lab shows what the cookie column of the table means for one request. A page on https://attacker.example.net submits a form POST to https://shop.example.com: the request is sent either way (CSRF needs no response), but with SameSite=Lax the session cookie stays behind ("cross-site POST: Lax allows only top-level GET"), and so does it with Strict. With SameSite=None the cookie is attached and the lab flags a CSRF risk. Now move the form to https://blog.example.com: that page is same-site, so even Lax sends the cookie, which is the same-site gap in the first row.
How CSRF is detected
- Testing (in scope): for each state-changing request, remove the token, send another session's token, change the method to
GET, changeContent-Typetotext/plainor form encoding (JSON endpoints that accept these can be reached from a plain HTML form), and replay with a foreignOrigin. Burp generates a proof-of-concept HTML form from a request for testing in your lab browser. - Code review:
@csrf_exemptand equivalent opt-outs, state-changingGETroutes, token checks that skip when the token is absent, tokens not bound to the session. - Logs: state-changing requests whose
OriginorRefereris foreign, or whoseSec-Fetch-Siteiscross-site; CSRF-failure counts per endpoint (a spike may be an attack or a broken front end).
How it is fixed
Session cookies SameSite=Lax or Strict, plus a framework CSRF token or an Origin/Fetch Metadata check on every state-changing request, no state changes on safe methods, and re-authentication for the most sensitive actions.
Pitfalls
- Checking the token only if present (
if "csrf" in form and form["csrf"] != expected). - Using
Refererwith a substring test ("bank.lab.test" in refereracceptsbank.lab.test.evil.example). - CORS misconfigurations that let other origins read the token (CORS).
Practice
1. A JSON API reads request.get_json(force=True) and uses cookie sessions. Can a plain HTML form on another site reach it?
Yes: a form with enctype="text/plain" can send a body that is valid JSON, and force=True parses it regardless of the Content-Type. Require Content-Type: application/json (which forces a CORS preflight from other origins) and add a CSRF token or Origin check.
2. Why didn't the origin mode need any change to the bank's forms?
The browser adds Origin and Sec-Fetch-Site itself; the server only reads them. Tokens, in contrast, must be put into every form and every script that sends state-changing requests.
Test yourself
Why can't the attacker's page include the correct CSRF token?
- It is encrypted
- It is in the bank's pages, which the same-origin policy doesn't let evil.example read
- Tokens expire instantly
- Browsers delete it
Which gap does SameSite=Lax leave?
- Cross-site POST forms
- State-changing GET requests reached by top-level navigation, and same-site attackers
- Image requests
- fetch() from other sites
Which request header can page JavaScript NOT forge in a browser?
- X-Requested-With
- Sec-Fetch-Site
- A custom header
- Content-Type
Is an API that uses only Authorization: Bearer headers (no cookies) exposed to CSRF?
- Yes, always
- No: browsers don't attach that header automatically to cross-site requests
- Only on GET
- Only with CORS *
In the same-origin lab, a form on https://blog.example.com POSTs to https://shop.example.com, whose cookie is SameSite=Lax. Is the cookie sent?
- No, Lax blocks every POST
- Yes: blog.example.com and shop.example.com are the same site, and SameSite only restricts cross-site requests
- Only if CORS allows it
- Only over HTTP