--- name: sh-kb-csrf description: "Knowledge base for finding Cross-Site Request Forgery - state-changing requests that rely only on ambient credentials (cookies) with no anti-CSRF token or SameSite protection. Use when hunting CSRF. CWE-352, OWASP A01:2021-Broken Access Control." --- # Cross-Site Request Forgery (CSRF) - Hunter Knowledge Base A logged-in victim's browser is tricked into sending a state-changing request; the app trusts the ambient cookie and performs the action as the victim. Requires cookie-based auth and a missing anti-CSRF control. ## Preconditions to confirm first 1. The endpoint performs a **state change** (create/update/delete/transfer/settings). 2. Auth is via **ambient credentials** (session cookie / HTTP Basic), not a per-request header token that JS must attach (`Authorization: Bearer`) - pure Bearer-in-header APIs are generally not CSRF-able. 3. There is **no** effective anti-CSRF defense on that route. ## Sinks / patterns (grep targets) State-changing route handlers (`POST`/`PUT`/`PATCH`/`DELETE`, or `GET` that mutates) that: - lack CSRF middleware/decorator, or explicitly disable it: `csrf_exempt`, `@csrf.exempt`, `skip_before_action :verify_authenticity_token`, `csrf: false`, Spring `.csrf().disable()`, Express without `csurf`, `SameSite=None`/absent on the session cookie. - Grep: `csrf_exempt|verify_authenticity_token|csrf().disable|csurf|SameSite|@csrf`. - **Framework posture, per stack** (what "on" looks like, and how it is switched off): - Django: `CsrfViewMiddleware` in `MIDDLEWARE`; `@csrf_exempt` on a view, `csrf_exempt(as_view())` in urls, DRF `SessionAuthentication` enforces CSRF but `TokenAuthentication` does not (so a view mixing cookie auth with exemption is exposed); `CSRF_COOKIE_SAMESITE`/`SESSION_COOKIE_SAMESITE` set to `None`. - Flask/FastAPI: no CSRF by default; `flask_wtf.CSRFProtect` missing or `@csrf.exempt`; FastAPI with cookie auth and no token/origin check is exposed. - Express/Nest/Next: `csurf` is deprecated, check for a maintained equivalent or custom double-submit; Next.js route handlers (`route.ts` POST) with cookie auth have no built-in CSRF check (server actions compare `Origin` to `Host` by default); Nest `app.use(csurf())` absent. - Spring: `http.csrf().disable()` / `csrf(AbstractHttpConfigurer::disable)` together with session-cookie login, `ignoringRequestMatchers`/`ignoringAntMatchers` covering state-changing routes. Disabling is fine for stateless Bearer APIs only. - Laravel: `VerifyCsrfToken::$except` entries; `api` routes using the `web` session guard. Rails: `protect_from_forgery with: :null_session` (unauthenticated on failure, still verify) or `:exception` missing, `skip_forgery_protection`. ASP.NET: missing `[ValidateAntiForgeryToken]`/`AutoValidateAntiforgeryToken`, `[IgnoreAntiforgeryToken]` on cookie-auth actions. ## Detection recipe 1. From `codebase-map.json`, list state-changing endpoints and their auth mechanism. 2. Check the global CSRF posture: is protection enabled framework-wide? Then find per-route exemptions. 3. Check cookie flags: `SameSite=Lax/Strict` blocks most cross-site POSTs; `SameSite=None` re-opens it. 4. Confirm the endpoint doesn't already require a non-ambient token or a custom header (which forces a preflight and blocks simple cross-site requests). 5. Check **how** the token is validated, not just that one exists: validation skipped when the token is absent (`if token and ...`), skipped for some methods or content types, token not bound to the session/user (any valid token accepted), token compared to a cookie the attacker can set via a sibling subdomain (double-submit without HMAC signing), or checked only on `POST` while `PUT`/`DELETE`/method-override (`_method`, `X-HTTP-Method-Override`) reach the same handler. 6. Check **non-obvious state changes**: `GET` endpoints that mutate (logout, unsubscribe, approve, delete, OAuth link/connect callbacks, "confirm email change" links), login CSRF (forcing a victim into the attacker's account), password-less settings changes, API-key creation, webhook/redirect-URI registration. 7. CORS interplay: `Access-Control-Allow-Origin` reflecting `Origin` with `Allow-Credentials: true` turns CSRF-style writes into full cross-origin reads; check it together with the cookie flags. Cross-site WebSocket upgrades authenticated by cookie with no `Origin` check (cross-site WebSocket hijacking) are the same class. ## Variant hunting Once one exempt or unprotected route is found: list every other route in the same router/controller/blueprint that inherits the exemption; grep every `csrf_exempt`/`skip_before_action`/`ignoring*`/`except` entry and re-check what each really protects; check API versions, mobile/legacy routes, admin panels, and webhook-style endpoints that were exempted for third-party callers but also accept browser sessions; check sibling mutations on the same resource (profile edit exempt means email change may be too) and the GET twin of each POST. ## Payloads / PoC - Auto-submitting form: an HTML page with `
` and hidden inputs, plus ``; victim visiting it triggers the action. - For JSON endpoints that accept `text/plain` or don't check content-type: a form with `enctype="text/plain"` crafting a JSON-ish body. - GET-based state change: ``. - PoC = the victim, while logged in, loads the attacker page and the state change occurs. ## False-positive filters - Anti-CSRF token required and validated (synchronizer token, double-submit cookie) on the route. - `SameSite=Lax` (default in modern browsers) or `Strict` on the session cookie - mitigates most CSRF; note residual risk for top-level GET navigations under Lax. - Auth is a header token the browser won't auto-attach cross-site (Bearer), not a cookie. - Endpoint requires a custom header (forces CORS preflight) and CORS is not permissive. - A legitimately exempt route: signed webhook receivers (HMAC verified), Bearer/API-key-only APIs, endpoints that take no cookie auth. Confirm the handler really ignores session cookies before dismissing the exemption. - `SameSite=Lax` is not a full defense: same-site attackers (sibling subdomain, XSS elsewhere on the site), `GET` mutations via top-level navigation, and the brief Lax+POST allowance Chrome gives cookies with no explicit `SameSite` still apply. Report with reduced severity, and say which condition is needed. - Real evidence of a finding: cookie-authenticated state change, no validated token or `Origin`/`Referer` check (or one with a bypass), a cookie policy that sends it cross-site, and no preflight requirement. Impact must be stated (what the forged request changes). ## Detection signals (for defenders) - **Logs needed**: web/proxy/WAF access logs with method, path, status, `Origin`, `Referer`, `Sec-Fetch-Site`, `Content-Type`, session or user id; application audit log for the resulting state change. - **Exploitation shape**: state-changing requests (POST/PUT/DELETE, or mutating GET) carrying a cookie session where `Origin`/`Referer` is absent or a foreign site, or `Sec-Fetch-Site: cross-site`; requests with a `text/plain` or form content type to a JSON-only route; a settings/email/password change with no preceding page load of the settings view in the same session. - **Impact signals**: email, password, MFA, API key, webhook, or payout-destination changes shortly after a session arrives from an external referrer; the same victim-side action fanning out across many accounts with an identical foreign `Referer`. - **Behaviour detection ideas**: (1) sensitive account-change routes where `Origin`/`Referer` host is not an allowed host (or `Sec-Fetch-Site` is `cross-site`) and the response is 2xx; (2) many distinct users hitting the same mutation with the same external referrer host in a short window. - **ATT&CK**: no single technique maps cleanly; T1190 (Exploit Public-Facing Application) fits the abuse of the app, and T1098 (Account Manipulation) fits the common outcome of changed credentials, email, or keys. ## CWE / OWASP / severity CWE-352. OWASP A01:2021. Severity by action impact: account/email/password change or money transfer -> **high**; low-value toggles -> medium/low. ## Chaining hints CSRF + `xss` (steal token then forge) ; CSRF to change email/password -> account takeover; CSRF to add an attacker OAuth/app -> persistence; often combined with `access-control` to hit privileged actions. ## Mitigation Enable framework CSRF protection on all state-changing routes (don't blanket-exempt); require a synchronizer or double-submit token; set session cookies `SameSite=Lax`/`Strict` + `Secure`; prefer non-ambient auth for APIs; require a custom header for JSON APIs and lock down CORS.