How do CSRF tokens work?

So CSRF works because the web app stores a cookie in your browser and then the browser will automatically add that cookie to any request you make to that web app, but then, how do CSRF tokens work? They are generated server side and then what? They are not stored in your browser like cookies because then they wouldn’t actually protect against the attack. Why is it that they are being only to requests being made directly from withing the web app but are not added to requests made by the malicious site you created containing the HTML code that makes the request to the web app you are testing?

1 Like

There are mostly two cases:

  • anti-CSRF tokens in forms: this is just a hidden field with a server-generated random value. The token is submitted with the form like any other form field. The value is stored in the session server-side so the server can verify the submitted token, which will change with every request.

  • anti-CSRF tokens submitted using an HTTP header (X-CSRF-Token and the likes): in this case the request is not generated directly by the browser in response to a navigation event, but by the app itself using javascript (fetch() or XMLHttpRequest()). In many cases the value is sent by the server through a <meta> tag which is read by the app. In other cases the value is obtained from a cookie. Sometimes the server will validate the value against a value stored in the session. Sometimes it will simply check that the CSRF token matches the corresponding cookie. Sometime it doesn’t event check the value and simply relies on the fact that specifying a custom header requires preflight.

In the first case, the problem for an attacker is obtaining a valid anti-CSRF token. It requires reading the form, which is normally not possible due to the Same Origin Policy (SOP).

In the second case, the main problem is specifying a custom header, which is also disallowed by SOP.

4 Likes

Oh, much simpler than I would have imagined :stuck_out_tongue: Thank you for the great response!

CSRF token is tied to a non-session cookie

The attacker can log in to the application using their own account, obtain a valid token and associated cookie, leverage the cookie-setting behavior to place their cookie into the victim’s browser, and feed their token to the victim in their CSRF attack.