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:// 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.
Why the form token is twice as long as the cookie (BREACH masking)
Open django/ 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) — 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.
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:
process_request(lines 401–412): Only reads the incoming cookie (or session key whenCSRF_USE_SESSIONS = True), validates its length and alphabet via_check_token_format, and stashes the unmasked 32-character secret inrequest. If the cookie is malformed, it rotates to a fresh secret. It never rejects a request here!.META["CSRF_COOKIE"] process_view(lines 414–470): Runs afterURLResolverhas found the target.resolve callback. Why wait? Becauseprocess_viewneeds to inspectgetattr(callback, "csrf_exempt", False)(set bycsrf_exempt,csrf_exempt)! That is also why Chapter 4’s decorator-ordering rule matters: if an outer decorator wraps@csrf_exemptwithout copying attributes viafunctools.wraps,process_viewnever seescsrf_exemptand rejects the request anyway.process_response(lines 472–484): Only writes the"Set-Cookie: csrftoken=..."header — and callspatch_vary_headers(response, ("Cookie",))— ifMETA["CSRF_COOKIE_NEEDS_UPDATE"]was flipped toTrue(which happens when a template actually evaluatescsrf_token, or whenrotate_tokenruns 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:
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/ 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:
- 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_verifiedcompares"Origin"againstf"{scheme}://and then against{request .get_host()}" CSRF_TRUSTED_ORIGINS(including subdomain wildcards like"https://). A mismatched*.desk .example" "Origin"fails with403on both HTTP and HTTPS, even if the double-submit token was valid! - Gate 2 — Strict HTTPS
"Referer"check (lines 442–463): Notice theelif requestbranch — and compare trace line 17 (HTTP POST with no.is_secure(): "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/ lines 446–459: an active network attacker (MITM) sitting on a coffee-shop Wi-Fi network can intercept a user visiting plain http://, inject a fake "csrftoken" cookie for "desk.example", and auto-submit a hidden POST form targeting https:// 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.
- 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 fromrequest(for.POST["csrfmiddlewaretoken"] "POST"), falling back torequest(.META[settings .CSRF_HEADER_NAME] "HTTP_X_CSRFTOKEN"by default) for AJAXfetch()/"PUT"/"DELETE"calls. Notice that_does_token_matchaccepts either a 64-character masked token (from a DOM<input>) or the 32-character raw cookie value (when JavaScript reads"documentand puts it in.cookie" X-CSRFToken).
Where CSRF protection leaks
- Reading
csrf_tokenin a base template poisons CDN caching. Becauseget_token()setsCSRF_COOKIE_NEEDS_UPDATE = True,process_responsestampsVary: Cookieon every response that renders{% csrf_token %}. CompareGET /(wire/ status/ Vary=None) vsGET /submit/(Vary='Cookie') in the recording above: put a hidden form in your site-wide navbar and every public article suddenly becomes uncacheable at shared proxies. - Reverse-proxy HTTPS termination breaks
"Origin"checks untilSECURE_PROXY_SSL_HEADERorCSRF_TRUSTED_ORIGINSis set. If the browser posts fromOrigin: https://but Django thinksdesk .example HttpRequestis.is_secure False,_origin_verifiedcomputesgood_origin = "http://and rejects every single form submission withdesk .example" 403 Origin checking failed. - Login CSRF and
rotate_token. Always rotate the CSRF secret on privilege changes (djangocalls.contrib .auth .login rotate_token(request)automatically) so a pre-login cookie planted by a network attacker cannot be reused after authentication. - Unsafe state changes on
"GET".CsrfViewMiddlewareunconditionally accepts"GET","HEAD","OPTIONS", and"TRACE". Any view that mutates database rows on"GET"bypasses CSRF completely.
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.