---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/middleware/csrf.py: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/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)` (`django/middleware/csrf.py:get_token`) via the `csrf` context processor (`django/template/context_processors.py:csrf`) — 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` (`django/middleware/csrf.py:_mask_cipher_secret`) and reversing it in `_unmask_cipher_token` (`django/middleware/csrf.py:_unmask_cipher_token`):

```python
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` (`django/utils/crypto.py:constant_time_compare`).

```text figure=csrf-masking
CSRF BREACH masking & verification gates on Django 6.1.3

1. BREACH masking (32-char secret -> 64-char masked token per get_token() render):
   csrftoken cookie S[0..31] + fresh random mask M[0..31] -> M[0..31] || (S[i] + M[i]) mod 62
   Base-62 example: secret[0]='a'(0) + mask[0]='C'(28) mod 62 = 28 -> 'C'
   Unmask: (cipher[i] - mask[i]) mod 62 -> constant_time_compare(secret)

2. CsrfViewMiddleware.process_view() 3-gate POST funnel on /submit/:
   Gate 1 (Origin header present)      -> mismatch -> 403 Bad Origin (HTTP & HTTPS)
   Gate 2 (No Origin + is_secure())    -> missing/insecure/bad Referer -> 403 (MITM defense)
   Gate 3 (Double-submit token check)  -> POST['csrfmiddlewaretoken'] or X-CSRFToken -> 403 or 200
```

*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`, `django/views/decorators/csrf.py: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`:

```text recording=ch05-security
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.

> **History.** Up through Django `3.x`, Django stored the *masked* 64-character token directly in the cookie and did not check `"Origin"` against scheme-qualified `CSRF_TRUSTED_ORIGINS`. Django `4.0` moved masking exclusively to `get_token()` (keeping a 32-character secret in the cookie — see `_get_secret` line 248 for the legacy unmask branch) and upgraded `"Origin"` validation to require explicit schemes (`"https://..."`) in `CSRF_TRUSTED_ORIGINS`.

3. **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

- **Reading `csrf_token` in a base template poisons CDN caching.** Because `get_token()` sets `CSRF_COOKIE_NEEDS_UPDATE = True`, `process_response` stamps `Vary: Cookie` on every response that renders `{% csrf_token %}`. Compare `GET /wire/status/` (`Vary=None`) vs `GET /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 until `SECURE_PROXY_SSL_HEADER` or `CSRF_TRUSTED_ORIGINS` is set.** If the browser posts from `Origin: https://desk.example` but Django thinks `HttpRequest.is_secure` (`django/http/request.py:HttpRequest.is_secure`) is `False`, `_origin_verified` computes `good_origin = "http://desk.example"` and rejects every single form submission with `403 Origin checking failed`.
- **Login CSRF and `rotate_token`.** Always rotate the CSRF secret on privilege changes (`django.contrib.auth.login` calls `rotate_token(request)` automatically) so a pre-login cookie planted by a network attacker cannot be reused after authentication.
- **Unsafe state changes on `"GET"`.** `CsrfViewMiddleware` unconditionally 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](signing.md).
