{"canonical_url":"https://engineer.company/glossary/csrf/","content_markdown":"# CSRF\n\n## What it is\n\nCSRF, short for cross-site request forgery, is the attack in which a page the\nvictim happens to open makes the victim's own browser send a request to another\nsite, one where they are logged in. The browser attaches that site's cookies as\nit always does, so the request arrives carrying the victim's session and looks\nlike something they chose to do. The Common Weakness Enumeration catalogues it\nas CWE-352 and describes the flaw from the server's side: the application does\nnot, or cannot, check well enough whether a request was intentionally made by\nthe user it appears to come from.\n\nThe OWASP prevention cheat sheet lists where the attack can start, from a\nmalicious web site to an email, a blog post, an instant message or a program,\nand what it can achieve: a funds transfer, a changed password, a purchase, a\ngrant of privileges. Each is an action on the site, a change of state, and that\nis where the cheat sheet puts its defences: a token on every state-changing\nrequest. CWE explains that the victim's permissions determine how far the attack\ncan reach, because the attacker borrows the victim's identity. Against an\nadministrator, the result can be complete control of the web application.\n\nCWE treats CSRF as a composite, a weakness that exists only where several others\nmeet. Among them are an origin validation error, CWE-346, and the unintended\nproxy or \"confused deputy\", CWE-441: the browser holds the victim's credentials\nand spends them on behalf of a page that has none. That sets CSRF apart from\ncross-site scripting, which CWE lists as a peer. With XSS the attacker's code\nruns inside the target site; with CSRF it stays on the attacker's page and only\nsends requests. It also sets it apart from CORS, which governs what a page may\nread from another origin. OWASP points out that a plain HTML form sends a simple\nrequest, one that needs no preflight, and that browsers permit such requests to\nany origin. CWE's own title spells the term Cross-Site Request Forgery, and the\nentry lists other names for the same thing, among them XSRF and Session Riding.\n\n## Why it matters\n\nCSRF has stayed on both of the best-known weakness lists. CWE-352 was in the CWE\nTop 25 in 2009, 2010 and 2011, and in every edition from 2019 to 2025. OWASP\ngave it a category of its own in the Top 10 of 2007 and 2010, as A5, and of\n2013, as A8. Since 2021 it has been part of A01, Broken Access Control, which\nsits at the top of the 2025 edition. OWASP reports that every one of the\napplications tested had some form of broken access control, and names CWE-352\namong its notable weaknesses.\n\nThe attack is hard to stamp out because the browser does the work. The W3C Fetch\nMetadata draft starts from that point: browsers are easily convinced to send\nrequests to a site's endpoints and to include the user's ambient credentials,\nsuch as cookies or a privileged position on an intranet, so applications have to\nbe very careful about how those endpoints behave, and being careful turns out to\nbe hard. CWE notes that almost any HTML element can launch the attack, image\ntags and links included. Its observed examples read like a list of\nadministrative actions carried out from someone else's page: user accounts added\nthrough a URL in an `img` tag (CVE-2004-1703), administrator privileges gained\nthe same way (CVE-2004-1842), and a web interface that let a forged request\nchange passwords or stop a virtual machine (CVE-2009-3759).\n\nScanners are little help. CWE says CSRF is currently difficult to detect\nreliably with automated techniques, because every application has its own\nimplicit policy about which requests an outsider may cause and which need strong\nconfidence that the user meant them. A tool cannot know that one form is\nharmless and the next one moves money. That makes CSRF a design question:\ndecide, request by request, what proves that the user meant it.\n\nBrowsers have moved in the defender's favour. OWASP's cheat sheet says current\nmainstream browsers enforce SameSite=Lax on cookies by default, which keeps them\noff most cross-site `POST` requests, and that every major browser has sent the\nFetch Metadata headers since March 2023. Both help, and neither settles the\nmatter. The cookie draft that defines SameSite calls Lax reasonable defence in\ndepth against attacks that rely on unsafe methods such as `POST`, but not a\nrobust defence against CSRF as a category, and advises that even Strict mode\nshould not be the whole of a site's defence. Users on older or embedded\nbrowsers, OWASP adds, may get cookies that behave as if no SameSite value were\nset at all.\n\n## What it looks like in practice\n\nTake a web application at `app.example.com` where a logged-in user changes the\nemail address on their account with a form post to `/account/email`. The session\ncookie is set with `SameSite=None; Secure`, because the same dashboard is also\nembedded in a partner's portal, and None is the value that lets a browser send a\ncookie in a cross-site context. An attacker publishes a page at\n`prizes.example.net` and gets the victim to open it:\n\n```html\n\u003cform action=\"https://app.example.com/account/email\" method=\"post\"\u003e\n  \u003cinput type=\"hidden\" name=\"email\" value=\"mallory@example.net\"\u003e\n\u003c/form\u003e\n\u003cscript\u003edocument.forms[0].submit();\u003c/script\u003e\n```\n\nThe browser submits the form as soon as the page loads, and since the cookie\nallows it, the session goes along:\n\n```http\nPOST /account/email HTTP/1.1\nHost: app.example.com\nOrigin: https://prizes.example.net\nSec-Fetch-Site: cross-site\nContent-Type: application/x-www-form-urlencoded\nCookie: session=...\n\nemail=mallory%40example.net\n```\n\nTo the server this is a logged-in user changing their address. If nothing else\nis checked, the address changes, and a password reset sent to the new one hands\nthe account to the attacker.\n\nTwo headers in that request belong to the browser, not to the attacker. The\nFetch Standard lists `Origin` among the forbidden request headers, along with\nevery header whose name starts with `Sec-`, so a script on the page cannot set\nor change them. `Origin` names the origin that sent the request, and the Fetch\nMetadata draft defines four values for `Sec-Fetch-Site`: `cross-site`,\n`same-site`, `same-origin`, and `none` for a navigation the user started, by\ntyping an address or choosing a bookmark. A check can lean on both, and still\nfall back to a token for browsers that send neither. A sketch in Python:\n\n```python\nimport hmac\nimport secrets\n\nSAFE_METHODS = {\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\"}\nOUR_ORIGIN = \"https://app.example.com\"\n\n\ndef new_csrf_token(session: dict) -\u003e str:\n    session[\"csrf_token\"] = secrets.token_urlsafe(32)\n    return session[\"csrf_token\"]\n\n\ndef csrf_ok(method: str, headers: dict, form: dict, session: dict) -\u003e bool:\n    if method in SAFE_METHODS:\n        return True\n    if headers.get(\"Sec-Fetch-Site\") == \"cross-site\":\n        return False\n    origin = headers.get(\"Origin\")\n    if origin is not None and origin != OUR_ORIGIN:\n        return False\n    expected = session.get(\"csrf_token\", \"\").encode()\n    sent = form.get(\"csrf_token\", \"\").encode()\n    return bool(expected) and hmac.compare_digest(sent, expected)\n```\n\nThe token comes from `secrets.token_urlsafe(32)`. Python's documentation says\nthe `secrets` module draws on the most secure source of randomness the operating\nsystem provides, and that 32 bytes, 256 bits, is believed to be enough. The\nserver puts the token in a hidden field in every form it renders and keeps a\ncopy in the session. It never puts it in a cookie, a URL or a log, which are the\nplaces OWASP's cheat sheet rules out for a synchronizer token.\n`hmac.compare_digest` is designed not to stop at the first byte that differs, so\nthe time a comparison takes reveals nothing about how much of a guess was right.\nBoth sides are encoded to bytes first, because the function accepts text strings\nonly when they are pure ASCII. A request with no `Origin` header falls through\nto the token, and `Origin: null` fails, since only the exact origin passes.\n\nIn a real application, reach for the framework's protection before writing your\nown; that is the first item on OWASP's list. Django's middleware, for example,\nrequires both its CSRF cookie and a `csrfmiddlewaretoken` field on every method\nother than `GET`, `HEAD`, `OPTIONS` and `TRACE`, answers 403 when either is\nmissing or wrong, and checks `Origin` against the host and the\n`CSRF_TRUSTED_ORIGINS` setting. Where nothing needs to embed the application,\nthe session cookie can also go out as\n`__Host-session=...; Path=/; Secure; SameSite=Lax`. OWASP notes that a cookie\nwith the `__Host-` prefix cannot be overwritten from another subdomain.\n\nBrowser settings are a layer, not the defence. Our write-up on\n[hardening the application with nonce-based CSP](/portfolio/hardened-the-application-with-nonce-based-csp/)\nnotes that the proxy middleware sets HSTS and SameSite cookies alongside the\nContent Security Policy, and that entitlements are re-checked on the server on\nevery request, with the frontend gates treated as UX only.\n\n## Where it goes wrong\n\n**State changes behind GET.** SameSite=Lax still sends the cookie on a\ncross-site top-level navigation with a safe method, so a link the victim clicks,\nor a page that sends the whole window to\n`https://app.example.com/account/delete?confirm=yes`, arrives logged in. OWASP\ncalls this the most common way SameSite-based defences fail in practice, and\nDjango builds its protection on the same premise: `GET` and the other safe\nmethods should have no side effects. Keep `GET`, `HEAD`, `OPTIONS` and `TRACE`\nfree of side effects, and put every change behind a method your checks cover.\n\n**SameSite as the whole defence.** The cookie draft explains why Lax is not\nenough on its own: an attacker can still open a new window or trigger a\ntop-level navigation to make a request count as same-site, and prerendering can\ndo the same without the user noticing. OWASP adds that SameSite looks at the\nregistrable domain rather than the full origin. A request from any host under\nexample.com counts as same-site for `app.example.com`, so a forgotten subdomain\nthat someone takes over is already inside the fence. Treat SameSite as a second\nlayer, and decide on the server with a token or an origin check.\n\n**A token the attacker can plant.** In the naive double-submit pattern the\nserver only checks that a cookie and a form field carry the same random value.\nOWASP now marks that pattern as discouraged, because anyone who can write\ncookies on the domain, through a vulnerable sibling subdomain, a DNS takeover or\na cookie injected over plain HTTP, can set both halves. CWE's entry still lists\nthe plain double-submitted cookie among its mitigations, so the two sources\ndisagree here, and OWASP's warning is the one to follow. Keep the token in the\nserver-side session, or use OWASP's signed double-submit cookie, bound to the\nsession with an HMAC.\n\n**Cross-site scripting on the same site.** A script that runs inside your own\npages can read the token from the form and send a request that is same-origin by\nevery measure. OWASP's cheat sheet puts it plainly: XSS \"can defeat all CSRF\nmitigation techniques\". CWE and Django say the same, and CWE's best-known\nexample shows the two working together. The Samy worm used XSS to plant itself\nin a MySpace profile and add the attacker as a friend, and friends who viewed\nthe profile had their own profiles changed the same way; since no victim chose\nto make that change, CWE counts CSRF as a root cause. Treat every XSS finding as\na CSRF finding too, and fix it first.\n\n**An origin check that matches too much.** A test like\n`origin.startswith(\"https://app.example.com\")` also accepts\n`https://app.example.com.attacker.example`, the trap OWASP's cheat sheet warns\nabout. The value `null` is another. Under the Fetch Standard, a form posted from\na page whose referrer policy is `no-referrer` arrives with `Origin: null`, and\nOWASP adds that redirects across origins and sandboxed frames can produce it\ntoo. Compare the whole origin with a fixed list of exact strings, and treat a\nmissing header or `null` as unknown, never as your own origin.\n\n**Trusting the preflight too far.** A custom request header is a sound defence\nfor an API, because browsers send a preflight before any cross-origin request\nthat carries one. It only holds if the API refuses everything else. OWASP warns\nthat a JSON API which also accepts `text/plain` can be reached by a form, since\nthat is one of the three content types a simple request may use, and that a CORS\npolicy allowing credentials from every subdomain through a regular expression\nlets anyone who takes over a subdomain send the custom header. Reject content\ntypes the endpoint does not expect, and list the exact origins that may send\ncredentialed requests.\n\n**Forgetting the login form.** Login CSRF runs the other way round: the attacker\nsigns the victim in to the attacker's own account. On a shopping site, OWASP's\nexample goes, the victim then enters card details, and the attacker can later\nbuy things with them. Django's documentation names login CSRF among the attacks\nits protection covers. Protect the login form with a token tied to a\npre-session, and destroy that session and start a new one once the user has\nsigned in, as OWASP advises.\n\n**Requests built from attacker input.** Client-side CSRF happens when the\napplication's own JavaScript builds a request from input the attacker controls,\nsuch as the URL, the window name or a `postMessage`. The script adds the token\nitself and the request is same-site, so neither tokens nor SameSite stop it;\nOWASP describes it as the confused deputy coming back. Keep request targets and\nparameters out of reach of attacker-controlled input, or choose them from a\nfixed list in the code.\n\n## Further reading\n\n- [CWE-352: Cross-Site Request Forgery (CSRF)](https://cwe.mitre.org/data/definitions/352.html)\n  — the weakness entry: the composite structure, consequences, mitigations and\n  observed CVEs.\n- [OWASP Cheat Sheet Series: Cross-Site Request Forgery Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n  — tokens, Fetch Metadata, origin checks, the limits of SameSite and login\n  CSRF.\n- [W3C: Fetch Metadata Request Headers](https://www.w3.org/TR/fetch-metadata/)\n  — the `Sec-Fetch-Site` header and the four values a browser can send.\n- [IETF draft: Cookies: HTTP State Management Mechanism (draft-ietf-httpbis-rfc6265bis)](https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/)\n  — the SameSite attribute and why Lax is defence in depth rather than a cure;\n  still an Internet-Draft.\n- [Django documentation: Cross Site Request Forgery protection](https://docs.djangoproject.com/en/6.1/ref/csrf/)\n  — a framework's built-in protection, what it assumes and where subdomains get\n  round it.\n- [OWASP Top 10:2025: A01 Broken Access Control](https://owasp.org/Top10/2025/A01_2025-Broken_Access_Control/)\n  — where CWE-352 sits in the 2025 edition.\n\n\u003chttps://engineer.company/glossary/csrf/\u003e\n","date_modified":"2026-10-30T02:51:31Z","description":"How cross-site request forgery turns a logged-in browser against the site that trusts it, why SameSite cookies are not enough, and the checks that hold.","formats":{"gemtext":"https://engineer.company/glossary/csrf/index.gmi","gopher":"https://engineer.company/glossary/csrf/gophermap","html":"https://engineer.company/glossary/csrf/","json":"https://engineer.company/glossary/csrf/index.json","markdown":"https://engineer.company/glossary/csrf/index.md","pdf":"https://engineer.company/glossary/csrf/index.pdf"},"kind":"page","language":"en","title":"What is CSRF?","url":"https://engineer.company/glossary/csrf/","version":1}