What is CSRF?
CSRF stands for Cross-Site Request Forgery. It is an attack that makes authenticated user do unwanted actions on a site. So trick user in submitting malicious request.
An example would be sending a link to user to trick user into transferring funds.
How can CSRF get worst? Stored CSRF flaws
An attacker can store CSRF attack on the site. They can be achieved through:
- store IMG tag that accepts HTML
- store IFRAME tag that accepts HTML
- cross-site scripting attack
How to mitigate CSRF?
We need to implement the following 2 requirements:
- synchronizer token pattern or double submit cookies
- At least one of:
- SameSite Cookie attribute for session cookies without specific domain
- UI based protection (ie. CAPTCHA)
- Custom request headers
- Verify origin with standard headers
However, even if you implement these, Cross-Site Scripting (XSS) can still break them through.
Synchronizer token pattern
Use this when you can maintain CSRF token on the server.
- Generate CSRF token per user session/each request
- When user sends a request to the server, validate the token along with the one from user session
Make sure 2 things:
- CSRF tokens are
- unique per session
- secret
- unpredictable
- Don’t leak the CSRF token
- don’t send them through cookies
- don’t leak them in server logs or in URL
- add them in hidden fields, headers
Note, adding CSRF tokens in custom request headers is more secure.
Double submit cookies
Use this when you can’t maintain CSRF token on the server. (stateless)
The concept is simple, we compare the value in CSRF cookie & the CSRF header of the request (or param).
- Generate a cryptographically strong value and send this random value in both:
- cookie
- request parameter (ie. hidden form value or request param/header)
- When user makes a request, see if they match
You can improve this have the token in encrypted cookie or HMAC the token with a server-side secret.
SameSite Cookie attribute
SameSite attribute help mitigates CSRF attacks.
- Strict: Prevents cookie being send by browser to target for all cross-site request
- Lax: Prevents cookie for CSRF-prone request methods like POST
- None: Cookies will be sent and we must set
Secure
attribute otherwise, cookie will be blocked.