🏠 Home

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:

  1. synchronizer token pattern or double submit cookies
  2. 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.

  1. Generate CSRF token per user session/each request
  2. When user sends a request to the server, validate the token along with the one from user session

Make sure 2 things:

  1. CSRF tokens are
  • unique per session
  • secret
  • unpredictable
  1. 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).

  1. Generate a cryptographically strong value and send this random value in both:
  • cookie
  • request parameter (ie. hidden form value or request param/header)
  1. 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 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.