Skip to content

Add optional signed CSRF token mode and Origin fallback - #356

Merged
ryancramerdesign merged 3 commits into
processwire:devfrom
adrianbj:csrf-signed-mode
Oct 23, 2026
Merged

ryancramerdesign merged 3 commits into
processwire:devfrom
adrianbj:csrf-signed-mode

Conversation

@adrianbj

@adrianbj adrianbj commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Session-bound CSRF tokens fail for legitimate users whenever the session that rendered a form isn't the session that receives the POST. I instrumented every front-end form POST on a production site whose token would fail validation, classifying the cause from raw session state. Over the last 30 days: 39 legitimate-user failures (all with Sec-Fetch-Site present, i.e. real browsers — overwhelmingly mobile Safari and Chrome), concentrated on login, password reset, and registration:

  • session-gone (16) — session cookie arrived, but the session it points to is gone (expired/GC'd, or destroyed by an intervening logout)
  • stale-token (14) — page restored from the browser back/forward cache carries a token from an earlier session
  • no-cookie (9) — the browser sent no session cookie with the POST at all (ITP, in-app browsers, cross-site-entry SameSite behavior)

Each of these is a real person filling in a form and being told "this request appears to be forged." Sites currently have to work around it externally, and SessionCSRF isn't hookable, so workarounds have to reach into session internals.

Commit 1: signed mode ($config->SessionCSRF['mode'] = 'signed')

Following Django's CSRF design (a long-lived cookie independent of the session):

  • session (default) — exactly today's behavior, byte-for-byte.
  • signed — tokens are derived, not stored: HMAC-SHA256($config->userAuthSalt, binding cookie), where the binding cookie (<sessionName>_csrf) is a long-lived (1 year), httpOnly, Secure/SameSite-matched random cookie. A token stays valid across session expiration, re-creation, logout, and back/forward-cache restores. This fixes the session-gone and stale-token classes (30 of my 39) by construction.

Properties preserved: same API (renderInput(), getToken*(), hasValidToken(), validate() — no form or validation code changes when switching modes); same TOKEN<digits>X<timestamp> name shape; rotation at login for free (Session::___login() already calls CSRF->resetAll(), which now also rotates the binding cookie — Django rotates at login for the same reason); single-use tokens stay session-based in either mode (they require per-token server state by definition). Token comparison also switches to hash_equals() in both modes.

Commit 2: Origin fallback ($config->SessionCSRF['originFallback'], default off)

The no-cookie class is unfixable by any token scheme — no cookie means nothing to bind a token to. Django pairs its token with an Origin check for that reason, and Laravel now gates on Sec-Fetch-Site. When enabled and the submitted token fails validation, the POST is still accepted if the browser proves it is same-origin: an Origin header whose scheme matches the current request and whose host and port match one of $config->httpHosts (80/443 default), or — when no Origin is present — Sec-Fetch-Site: same-origin/none. These headers are browser-set and cannot be forged cross-site, so cross-site forgery remains blocked; requests with neither header are rejected as before.

Scope guards: applies only to the default token — named and single-use tokens never use it (rescuing a consumed single-use token would permit replay) — and only when a ProcessWire-shaped token was actually submitted, so tokenless bot/scanner POSTs are never rescued. This is a core-native version of a site-level fallback that has run in my production _init.php since June, silently rescuing all 39 of the failures above with zero user-facing errors.

The two commits are independent — either can be taken without the other — but together they cover every failure class I've measured.

Commit 3: review changes

  • Settings grouped as $config->SessionCSRF = ['mode' => 'session', 'originFallback' => false], merged with the class defaults (override one key), documented in config.php with #property lines. $config->protectCSRF is unchanged.
  • Origin check compares host and port (80/443 default for http/https) with $config->httpHosts.
  • Signed-mode binding cookie uses the __Host- prefix on HTTPS when sessionCookieDomain isn't set, so subdomains can't plant it; docs note the subdomain caveat otherwise, and that rotation invalidates forms in all tabs.

Verification

  • New wire/core/Session/SessionCSRF.test.php (WireTests): 55 checks covering both token modes and the fallback — format/stability, POST and AJAX-header validation, tamper rejection, session-loss survival (signed) vs non-survival (session), rotation on resetAll()/resetToken(), settings merge, Origin port matching, __Host- cookie naming, single-use semantics in both modes, fallback disabled-by-default, Origin host/scheme matching, Sec-Fetch-Site handling, neither-header rejection, tokenless-POST rejection, single-use replay rejection. All pass.
  • Full existing WireTests suite: identical results with and without these commits (nothing new fails).
  • End-to-end over HTTP against the real admin login form (site-blank profile):
Scenario session mode signed mode
Valid token, session cookie dropped (lost session) rejected as forged CSRF passes, login proceeds to credential check
Tampered token rejected as forged rejected as forged
No cookies at all rejected as forged rejected as forged

With 'originFallback' => true (session mode, no cookies sent at all):

Scenario Result
Stale token + Origin matching the site CSRF passes, login proceeds to credential check
Stale token + cross-site Origin rejected as forged
Stale token, no Origin/Sec-Fetch-Site (curl/scanner) rejected as forged

Defaults unchanged: with neither option set, behavior is identical to current dev.

In the default 'session' mode, CSRF tokens are random values stored in the
session, so a token is only valid for the session that created it. When the
session expires, is re-created, or the browser restores a page from its
back/forward cache, a previously rendered token no longer validates and a
legitimate same-origin submission is rejected as forged.

The new opt-in 'signed' mode derives tokens (HMAC-SHA256, keyed by
$config->userAuthSalt) from a long-lived httpOnly binding cookie that is
independent of the session, so tokens stay valid across session expiration
and re-creation for as long as the binding cookie lasts. The cookie is
rotated at login (via resetAll) and whenever tokens are reset. Single-use
tokens remain session-based in either mode, and both modes share the same
API, so no form or validation code changes when switching.

Also switches token comparison to hash_equals() for constant-time checks.
…ginFallback

Some legitimate same-origin POSTs cannot pass token validation under any token
scheme: the browser withholds all cookies from the POST (ITP, in-app browser
jars, cross-site-entry SameSite behavior), so there is neither a session nor a
binding cookie to validate against. This is the residue that even the signed
token mode cannot cover.

When $config->csrfOriginFallback is enabled (off by default) and the submitted
token fails validation, the request is still accepted if the browser proves it
is same-origin: an Origin header whose scheme matches the current request and
whose host is in $config->httpHosts, or - when no Origin header is present - a
Sec-Fetch-Site header of 'same-origin' or 'none'. These headers are set by the
browser and cannot be forged cross-site, so cross-site forgery remains blocked;
requests with neither header are rejected as before.

The fallback applies only to the default token - named and single-use tokens
never use it (rescuing a consumed single-use token would permit replay) - and
only when a ProcessWire-shaped token was actually submitted, so tokenless
POSTs from bots and scanners are never rescued.
@adrianbj

Copy link
Copy Markdown
Contributor Author

A real-world case from production today that the second commit (csrfOriginFallback) would have prevented, and that the first commit (signed mode) alone would not.

We have a staff "switch user" feature for support work: it impersonates a member via $session->forceLogin() and switches back the same way. Every forceLogin() goes through Session::___login(), which calls CSRF()->resetAll(), so the session gets a new token name each time. A staff member had a page open in the editor, switched to a member's account and back, and about ten minutes later clicked Save in that original tab. The POST carried the token name from before the switch, so isSubmitted() failed and the edit was discarded. They tried again 12 seconds later and got the same result.

The new postNotSubmitted() from 3.0.272 is the only reason we saw this, since before that release it would have looked like a successful save. It logged:

POST for page 16392 was not processed (token=missing, landmark=ok, postVars=542, max_input_vars=30000)

So it wasn't max_input_vars: the landmark arrived and the POST was far under the limit. The token was present, but under a name the session no longer recognized.

Signed mode doesn't help here, because the binding cookie rotates at login by design. The Origin fallback does: it was a same-origin POST from the admin carrying a TOKEN\d+X\d+ field, for the default token. The token reset at login is there to stop a token issued to another session from being reused. The Origin check closes that gap on its own, because a cross-site page can't make the browser send our Origin.

I reproduced it on a 3.0.273 install with this PR's SessionCSRF.php dropped in. The test loaded the page editor, ran forceLogin() to another user and back (with session_regenerate_id(true), as our switcher does), then submitted the full editor form from the original load:

  • No switch (control): saved.
  • After the switch, csrfOriginFallback off: not saved, and the same token=missing, landmark=ok log line as production.
  • After the switch, csrfOriginFallback on, same-origin Origin: saved.
  • After the switch, fallback on, no Origin or Sec-Fetch-Site header: not saved.
  • After the switch, fallback on, cross-site Origin: not saved.

A small, separate suggestion for postNotSubmitted(): token=missing only checks for the current session's token name, so "posted a stale token" and "posted no token" look the same. Logging something like token=stale when a TOKEN\d+X\d+ key is present would make this kind of failure obvious from the log line alone.

@ryancramerdesign

ryancramerdesign commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Thanks Adrian, and thanks for the switch-user case: a real gap that the earlier fixes (the login form refresh, ProcessLogin catching the CSRF exception, and postNotSubmitted()) don't cover, since they're about the admin login form and logging. Ryan and I have reviewed and tested this. The design is sound and opt-in, and signed mode works as described. A few changes, please:

1. Settings as one array. Since both settings belong to SessionCSRF, Ryan would like them grouped the way $config->PageFinder and $config->InputfieldWrapper already are:

$config->SessionCSRF = [
	'mode' => 'session', // or 'signed'
	'originFallback' => false,
];

documented in config.php with #property lines like PageFinder's, and merged with SessionCSRF's defaults, so a site can override one key. $config->protectCSRF stays where it is: it's the long-standing master switch and is used well beyond this class.

2. The Origin check ignores the port. requestIsSameOrigin() compares only PHP_URL_HOST with $config->httpHosts, which fails both ways:

  • with httpHosts = ['localhost:8888'], a same-origin POST from http://localhost:8888 is rejected;
  • with httpHosts = ['example.com'], a POST from http://example.com:8080 is accepted, though browsers treat a different port as a different origin.

Over HTTP against the admin login form on a local MAMP site (httpHosts = ['localhost:8888']), with the fallback on and no cookies, a same-origin Origin: http://localhost:8888 was rejected as forged. It passed only after changing httpHosts to localhost. Comparing host and port together, with 80/443 as the defaults for http/https, would fix both.

3. Signed mode and cookie tossing. The signed token is bound only to the binding cookie, not to the session. So someone who controls a subdomain could set a binding cookie value they chose in a visitor's browser, and then submit a token they fetched for that same value themselves. It's the known weakness of this kind of design, which Django shares. Session mode doesn't have it. Using the __Host- cookie name prefix when the site is on HTTPS and sessionCookieDomain isn't set would stop it there, since browsers don't let subdomains set __Host- cookies. Otherwise, a sentence in the docs about subdomains would do.

4. Smaller things:

  • In signed mode, resetting the default token rotates the binding cookie, which invalidates forms open in all of the user's tabs, not just the current one. That's fine, but worth a line in the docs.
  • SessionCSRF.php's copyright line still says 2022.

What I tested. Your test passes on MySQL, SQLite and PostgreSQL. Over HTTP against the admin login form:

  • the normal submit passes, as today;
  • session mode with the session cookie lost is rejected, as today;
  • signed mode with only the binding cookie kept passes;
  • a tampered token and no cookies at all are both rejected;
  • the fallback rejects Origin: http://evil.com.

With both settings off, behaviour is unchanged.

Your token=stale suggestion for postNotSubmitted() seems useful to me. It would make a case like yours obvious from one log line, and it could come as its own small PR.

-Claude

… cookie

Review changes for processwire#356:

- Group the settings as $config->SessionCSRF = ['mode' => 'session',
  'originFallback' => false], merged with the class defaults so a site can
  override one key. Replaces $config->csrfMode and $config->csrfOriginFallback.
- requestIsSameOrigin() compares host and port (80/443 default for
  http/https) against $config->httpHosts, so 'localhost:8888' matches a
  same-origin POST and 'example.com' no longer matches example.com:8080.
- Name the signed-mode binding cookie with the __Host- prefix on HTTPS when
  sessionCookieDomain is not set, so subdomains cannot plant it; document
  the subdomain caveat otherwise, and that rotation invalidates forms in
  all of the user's tabs.
- Update copyright year.
@adrianbj

Copy link
Copy Markdown
Contributor Author

Thanks Ryan — all done in 4c06908:

  1. Settings are now $config->SessionCSRF = ['mode' => 'session', 'originFallback' => false], documented in config.php with #property lines and merged with the class defaults, so one key can be overridden. protectCSRF is untouched.
  2. The Origin check now compares host and port (80/443 default). I reproduced your case over HTTP with httpHosts = ['localhost:8888']: a same-origin Origin: http://localhost:8888 now passes, while http://localhost and :9999 are rejected. With httpHosts = ['localhost'], Origin :8080 is rejected.
  3. On HTTPS with no sessionCookieDomain, the binding cookie is now __Host-<session>_csrf, so subdomains can't set it. Otherwise, the docs explain the subdomain risk and recommend session mode if not all subdomains are trusted.
  4. Added the all-tabs note on rotation and updated the copyright year.

The test now has 55 checks, adding the settings merge, port matching and __Host- naming. I'll send the token=stale logging for postNotSubmitted() as a separate small PR.

@adrianbj

Copy link
Copy Markdown
Contributor Author

The token=stale logging for postNotSubmitted() is now its own PR: #395.

-Adrian (via Claude Code)

@ryancramerdesign
ryancramerdesign merged commit 223a566 into processwire:dev Oct 23, 2026
@ryancramerdesign

Copy link
Copy Markdown
Member

Merged, thanks Adrian. Re-tested the updated version:

  • the 55-check test passes on MySQL, SQLite and PostgreSQL;
  • with the HTTP tests against the admin login form, the MAMP case now works: with httpHosts = ['localhost:8888'], Origin localhost:8888 passes, while localhost, :9999 and evil.com are rejected, and httpHosts = ['localhost'] rejects :8888;
  • signed mode works through $config->SessionCSRF, and tampered tokens and cookie-less posts are still rejected;
  • the full suites give the same results as dev.

-Claude

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants