{"id":13631239,"url":"https://github.com/pillarjs/understanding-csrf","last_synced_at":"2025-04-09T20:16:53.096Z","repository":{"id":43819942,"uuid":"30104929","full_name":"pillarjs/understanding-csrf","owner":"pillarjs","description":"What are CSRF tokens and how do they work?","archived":false,"fork":false,"pushed_at":"2021-04-17T08:06:55.000Z","size":18,"stargazers_count":1414,"open_issues_count":11,"forks_count":119,"subscribers_count":33,"default_branch":"master","last_synced_at":"2025-04-09T20:16:47.952Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pillarjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-01-31T06:45:56.000Z","updated_at":"2025-04-09T17:23:13.000Z","dependencies_parsed_at":"2022-07-15T20:46:46.024Z","dependency_job_id":null,"html_url":"https://github.com/pillarjs/understanding-csrf","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pillarjs%2Funderstanding-csrf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pillarjs%2Funderstanding-csrf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pillarjs%2Funderstanding-csrf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pillarjs%2Funderstanding-csrf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pillarjs","download_url":"https://codeload.github.com/pillarjs/understanding-csrf/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248103859,"owners_count":21048245,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T22:02:16.974Z","updated_at":"2025-04-09T20:16:53.069Z","avatar_url":"https://github.com/pillarjs.png","language":null,"funding_links":[],"categories":["Others","tech","Others (1002)"],"sub_categories":[],"readme":"\n# Understanding CSRF\n\nThe Express team's [csrf](https://github.com/pillarjs/csrf) and [csurf](https://github.com/expressjs/csurf) modules\nfrequently have issues popping up concerned about our usage of cryptographic functions.\nThese concerns are unwarranted due to a misunderstanding of how CSRF tokens work.\nSo here's a quick run down!\n\nRead this and still have questions? Want to tell us we're wrong? Open an issue!\n\n## How does a CSRF attack work?\n\nOn their own (phishing site), an attacker could create an AJAX button or form that creates a request against your site:\n\n```html\n\u003cform action=\"https://my.site.com/me/something-destructive\" method=\"POST\"\u003e\n  \u003cbutton type=\"submit\"\u003eClick here for free money!\u003c/button\u003e\n\u003c/form\u003e\n```\n\nThis is worse with AJAX as the attacker could use other methods like `DELETE` as well as read the result.\nThis is particularly important when the user has some sort of session with very personal details on your site.\nIf this is in the context of a technologically illiterate user,\nthere might be some inputs for credit card and social security info.\n\n## How to mitigate CSRF attacks?\n\n### Use only JSON APIs\n\nAJAX calls use JavaScript and are CORS-restricted.\nThere is no way for a simple `\u003cform\u003e` to send `JSON`,\nso by accepting only JSON,\nyou eliminate the possibility of the above form.\n\n### Disable CORS\n\nThe first way to mitigate CSRF attacks is to disable cross-origin requests.\nIf you're going to allow CORS,\nonly allow it on `OPTIONS, HEAD, GET` as they are not supposed to have side-effects.\n\nUnfortunately, this does not block the above request as it does not use JavaScript (so CORS is not applicable).\n\n### Check the referrer header\n\nUnfortunately, checking the referrer header is a pain in the ass,\nbut you could always block requests whose referrer headers are not from your site.\nThis really isn't worth the trouble.\n\nFor example, you could not load sessions if the referrer header is not your server.\n\n### GET should not have side effects\n\nMake sure that none of your `GET` requests change any relevant data in your database.\nThis is a very novice mistake to make and makes your app susceptible to more than just CSRF attacks.\n\n### Avoid using POST\n\nBecause `\u003cform\u003e`s can only `GET` and `POST`,\nby using other methods like `PUT`, `PATCH`, and `DELETE`,\nan attacker has fewer methods to attack your site.\n\n### Don't use method override!\n\nMany applications use [method-override](https://github.com/expressjs/method-override) to use\n`PUT`, `PATCH`, and `DELETE` requests over a regular form.\nThis, however, converts requests that were previously invulnerable vulnerable!\n\nDon't use `method-override` in your apps - just use AJAX!\n\n### Don't support old browsers\n\nOld browsers do not support CORS or security policies.\nBy disabling support for older browsers\n(which more technologically-illiterate people use, who are more (easily) attacked),\nyou minimize CSRF attack vectors.\n\n### CSRF Tokens\n\nAlas, the final solution is using CSRF tokens.\nHow do CSRF tokens work?\n\n1. Server sends the client a token.\n2. Client submits a form with the token.\n3. The server rejects the request if the token is invalid.\n\nAn attacker would have to somehow get the CSRF token from your site,\nand they would have to use JavaScript to do so.\nThus, if your site does not support CORS,\nthen there's no way for the attacker to get the CSRF token,\neliminating the threat.\n\n__Make sure CSRF tokens can not be accessed with AJAX!__\nDon't create a `/csrf` route just to grab a token,\nand especially don't support CORS on that route!\n\nThe token just needs to be \"unguessable\",\nmaking it difficult for an attacker to successfully guess within a couple of tries.\nIt does not have to be cryptographically secure.\nAn attack is one or two clicks by an unbeknownst user,\nnot a brute force attack by a server.\n\n## BREACH attack\n\nThis is where the salt comes along.\nThe BREACH attack is pretty simple: if the server sends the same or very similar response over `HTTPS+gzip` multiple times,\nan attacker could guess the contents of response body (making HTTPS utterly useless).\nSolution? Make each response a tiny bit different.\n\nThus, CSRF tokens are generated on a per-request basis and different every time.\nBut the server needs to know that any token included with a request is valid.\nThus:\n\n1. Cryptographically secure CSRF tokens are now the CSRF \"secret\", (supposedly) only known by the server.\n2. CSRF tokens are now a hash of the secret and a salt.\n\nRead more here:\n\n- [BREACH][1]\n- [CRIME](http://en.wikipedia.org/wiki/CRIME)\n- [Defending against the BREACH Attack](https://community.qualys.com/blogs/securitylabs/2013/08/07/defending-against-the-breach-attack)\n\n[1]: http://en.wikipedia.org/wiki/BREACH_(security_exploit)\n\nNote that CSRF doesn't _solve_ the BREACH attack,\nbut the module simply randomizes requests to mitigate the BREACH attack for you.\n\n## The salt doesn't have to be cryptographically secure\n\n__Because the client knows the salt!!!__\nThe server will send `\u003csalt\u003e;\u003ctoken\u003e` and the client will return the same value to the server on a request.\nThe server will then check to make sure `\u003csecret\u003e+\u003csalt\u003e=\u003ctoken\u003e`.\nThe salt must be sent with the token,\notherwise the server can't verify the authenticity of the token.\n\nThis is the simplest cryptographic method.\nThere are more methods, but they are more complex and not worth the trouble.\n\n## Creating tokens must be fast\n\n__Because they are created on every request!__\nDoing something as simple as `Math.random().toString(36).slice(2)` is sufficient as well as extremely performant!\nYou don't need OpenSSL to create cryptographically secure tokens on every request.\n\n## The secret doesn't have to be secret\n\nBut it is.\nIf you're using a database-backed session store,\nthe client will never know the secret as it's stored on your DB.\nIf you're using cookie sessions,\nthe secret will be stored as a cookie and sent to the client.\nThus, __make sure cookie sessions use `httpOnly` so the client can't read the secret via client-side JavaScript!__\n\n## When you're using CSRF tokens incorrectly\n\n### Adding them to JSON AJAX calls\n\nAs noted above, if you don't support CORS and your APIs are strictly JSON,\nthere is absolutely no point in adding CSRF tokens to your AJAX calls.\n\n### Exposing your CSRF token via AJAX\n\nDon't ever create a `GET /csrf` route in your app\nand especially don't enable CORS on it.\nDon't send CSRF tokens with API response bodies.\n\n## Conclusion\n\nAs the web moves towards JSON APIs and browsers become more secure with more security policies,\nCSRF is becoming less of a concern.\nBlock older browsers from accessing your site and change as many of your APIs to be JSON APIs,\nand you basically no longer need CSRF tokens.\nBut to be safe, you should still enable them whenever possible and especially when it's non-trivial to implement.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpillarjs%2Funderstanding-csrf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpillarjs%2Funderstanding-csrf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpillarjs%2Funderstanding-csrf/lists"}