TExcelTAD

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.
  • Origin header: sent by browsers on cross-origin requests and on all POSTs, naming the page's origin (or null). Sec-Fetch-Site (Fetch Metadata): same-origin, same-site, cross-site or none (typed URL, bookmark), set by the browser and not changeable by page script.
  • SameSite=Lax session cookies: not sent on cross-site POSTs, iframes, images or fetch, only on top-level GET navigations (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).

bash · try it yourself
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.

<form method="POST" action="https://shop.example.com/api/cart">, submit()page (script runs here)https://attacker.example.nethttps://shop.example.comcookie session: SameSite=LaxSecure; HttpOnlyPOST (no cookie)200✕same origin: no (host differs)✕same site: no (example.net ≠ example.com)✓preflight: none (simple request, navigation or same origin)✓request sent: yes✕cookie attached: no (cross-site POST: Lax allows only top-level GET)✕script reads the response: no (the form navigates the page away)SameSite blocks the cookie, so this cross-site POST is not authenticated

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, change Content-Type to text/plain or form encoding (JSON endpoints that accept these can be reached from a plain HTML form), and replay with a foreign Origin. Burp generates a proof-of-concept HTML form from a request for testing in your lab browser.
  • Code review: @csrf_exempt and equivalent opt-outs, state-changing GET routes, token checks that skip when the token is absent, tokens not bound to the session.
  • Logs: state-changing requests whose Origin or Referer is foreign, or whose Sec-Fetch-Site is cross-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 Referer with a substring test ("bank.lab.test" in referer accepts bank.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?

  1. It is encrypted
  2. It is in the bank's pages, which the same-origin policy doesn't let evil.example read
  3. Tokens expire instantly
  4. Browsers delete it

Which gap does SameSite=Lax leave?

  1. Cross-site POST forms
  2. State-changing GET requests reached by top-level navigation, and same-site attackers
  3. Image requests
  4. fetch() from other sites

Which request header can page JavaScript NOT forge in a browser?

  1. X-Requested-With
  2. Sec-Fetch-Site
  3. A custom header
  4. Content-Type

Is an API that uses only Authorization: Bearer headers (no cookies) exposed to CSRF?

  1. Yes, always
  2. No: browsers don't attach that header automatically to cross-site requests
  3. Only on GET
  4. 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?

  1. No, Lax blocks every POST
  2. Yes: blog.example.com and shop.example.com are the same site, and SameSite only restricts cross-site requests
  3. Only if CORS allows it
  4. Only over HTTP