Django 6.1.3

5.2 Security by default

CSRF tokens, masking, and origin checks

Why does Django mask the CSRF secret differently on every HTML render, and what exact checks run on a POST over HTTP vs. HTTPS?

Browsers automatically attach a site’s cookies to cross-site form submissions. If an authenticated reporter visits an attacker’s page containing a hidden <form action="https://desk.example/submit/" method="POST"> that auto-submits via JavaScript, the browser faithfully sends the reporter’s session cookie along with the forged story.

Django defeats this with CsrfViewMiddleware, implementing a double-submit cookie (or session) secret paired with per-render CSRF masking, strict "Origin" verification, and HTTPS "Referer" validation.

Open django/middleware/csrf.py lines 44–82. The raw secret stored in the "csrftoken" cookie is CSRF_SECRET_LENGTH = 32 characters drawn from the 62-character alphanumeric alphabet CSRF_ALLOWED_CHARS (string.ascii_letters + string.digits) — roughly 190 bits of entropy (32 * log2(62)).

Yet when a template renders {% csrf_token %} — which lazily evaluates get_token(request) via the csrf context processor — the hidden <input> is 64 characters long, and it changes on every single page reload even though the "csrftoken" cookie stays fixed!

Why? BREACH (the 2013 HTTP-compression side-channel attack). When a page is served with gzip or Brotli compression and reflects both attacker-controlled text (such as a query parameter) and a static secret in the same response body, an attacker can guess the secret one byte at a time by watching the compressed response shrink whenever a guess matches the secret.

Django breaks BREACH by applying a one-time pad in base-62 inside _mask_cipher_secret and reversing it in _unmask_cipher_token:

def _mask_cipher_secret(secret):
    mask = _get_new_csrf_string()
    chars = CSRF_ALLOWED_CHARS
    pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
    cipher = "".join(chars[(x + y) % len(chars)] for x, y in pairs)
    return mask + cipher

Every call to get_token generates a fresh random 32-character mask $M$, computes $C_i = (S_i + M_i) \bmod 62$ for each position $i$, and concatenates mask + cipher (64 characters). On verification, _unmask_cipher_token slices the first 32 characters as the mask, subtracts each index from the second 32 characters (chars[x - y], using Python’s negative indexing as modulo 62), recovers the original 32-character secret, and compares it against the cookie secret with constant_time_compare.

Figure 5.2 Every arithmetic step and POST outcome is verified from ch05-security. Two consecutive renders of the same cookie secret emit two completely unrelated 64-character strings so gzip cannot compress against a fixed secret, yet both unmask cleanly back to the same 32-character secret.

Why verification runs in process_view, not process_request

Look closely at the three middleware hooks on CsrfViewMiddleware:

  1. process_request (lines 401–412): Only reads the incoming cookie (or session key when CSRF_USE_SESSIONS = True), validates its length and alphabet via _check_token_format, and stashes the unmasked 32-character secret in request.META["CSRF_COOKIE"]. If the cookie is malformed, it rotates to a fresh secret. It never rejects a request here!
  2. process_view (lines 414–470): Runs after URLResolver.resolve has found the target callback. Why wait? Because process_view needs to inspect getattr(callback, "csrf_exempt", False) (set by csrf_exempt, csrf_exempt)! That is also why Chapter 4’s decorator-ordering rule matters: if an outer decorator wraps @csrf_exempt without copying attributes via functools.wraps, process_view never sees csrf_exempt and rejects the request anyway.
  3. process_response (lines 472–484): Only writes the "Set-Cookie: csrftoken=..." header — and calls patch_vary_headers(response, ("Cookie",)) — if META["CSRF_COOKIE_NEEDS_UPDATE"] was flipped to True (which happens when a template actually evaluates csrf_token, or when rotate_token runs on login).

Watch both the lazy "Vary: Cookie" behavior and all seven live POST paths against our newsroom "/submit/" view on Django 6.1.3:

Recorded on Django 6.1.3 ch05-security script
CsrfViewMiddleware: BREACH masking, Origin vs HTTPS Referer, and POST checks
  BREACH masking: len(secret)=32 len(t1)=64 len(t2)=64 distinct=True unmask(t1)==secret:True unmask(t2)==secret:True
  mask arithmetic (base-62): secret[0]='a'(0) + mask[0]='C'(28) mod 62 = 28 -> 'C'
  GET /wire/status/ (no csrf tag): Vary=None set_csrf_cookie=False
  GET /submit/ (uses csrf_token):  Vary='Cookie' set_csrf_cookie=True
    POST valid cookie + masked form token (HTTP, no Origin/Referer) -> 200 OK (accepted)
    POST valid cookie + X-CSRFToken header (AJAX) -> 200 OK (accepted)
    POST missing CSRF cookie -> 403 Forbidden (Forbidden (CSRF cookie not set.): /submit/)
    POST cookie present, missing token -> 403 Forbidden (Forbidden (CSRF token missing.): /submit/)
    POST mismatched Origin header (evil.example) -> 403 Forbidden (Forbidden (Origin checking failed - https://evil.example does not match any trusted origins.): /submit/)
    POST over HTTPS with NO Origin and NO Referer -> 403 Forbidden (Forbidden (Referer checking failed - no Referer.): /submit/)
    POST over HTTPS with matching https://desk.example Referer -> 200 OK (accepted)

HTTP vs. HTTPS: why "Origin" and "Referer" split

Trace lines 425–470 of django/middleware/csrf.py alongside those seven live outcomes.

Safe HTTP methods ("GET", "HEAD", "OPTIONS", "TRACE", RFC 9110) pass immediately via _accept. Every unsafe method ("POST", "PUT", "PATCH", "DELETE") must survive three ordered gates:

  1. Gate 1 — "Origin" header (lines 437–441): If the request sends an "Origin" header (modern browsers send it on all POSTs and CORS requests), _origin_verified compares "Origin" against f"{scheme}://{request.get_host()}" and then against CSRF_TRUSTED_ORIGINS (including subdomain wildcards like "https://*.desk.example"). A mismatched "Origin" fails with 403 on both HTTP and HTTPS, even if the double-submit token was valid!
  2. Gate 2 — Strict HTTPS "Referer" check (lines 442–463): Notice the elif request.is_secure(): branch — and compare trace line 17 (HTTP POST with no "Origin"/"Referer" → 200 OK) against trace line 22 (HTTPS POST with no "Origin"/"Referer" → 403 Forbidden: Referer checking failed - no Referer.)! Why does Django enforce strict "Referer" checking only on HTTPS when "Origin" is absent?

Read the famous comment in django/middleware/csrf.py lines 446–459: an active network attacker (MITM) sitting on a coffee-shop Wi-Fi network can intercept a user visiting plain http://desk.example/, inject a fake "csrftoken" cookie for "desk.example", and auto-submit a hidden POST form targeting https://desk.example/submit/ with matching cookie and form token! Because cookies are not isolated by scheme, the double-submit check alone cannot stop a plain-HTTP MITM from forging an HTTPS POST. Requiring an "https://" "Origin" or "Referer" ensures the submission genuinely originated from a secure origin.

  1. Gate 3 — Double-submit token check (_check_token, lines 349–399): Requires a valid secret from the cookie (or session), then extracts the submitted token from request.POST["csrfmiddlewaretoken"] (for "POST"), falling back to request.META[settings.CSRF_HEADER_NAME] ("HTTP_X_CSRFTOKEN" by default) for AJAX fetch() / "PUT" / "DELETE" calls. Notice that _does_token_match accepts either a 64-character masked token (from a DOM <input>) or the 32-character raw cookie value (when JavaScript reads "document.cookie" and puts it in X-CSRFToken).

Where CSRF protection leaks

CSRF verifies that a request came from your own origin. Next, we look at how Django guarantees that cookies, password-reset links, and signed payloads were created by your own server — and how you can rotate SECRET_KEY without throwing away every active token — in Cryptographic signing and key rotation.