MrFizz
MrFizz

Reputation: 41

CSRF prevention using local storage and cookie

The following talk https://youtu.be/67mezK3NzpU?t=2408 at 40:08min, Hubert mentions that the best way to prevent a CSRF attack is to do the following:

  1. Generate a random id server side - lets call this the CSRF id.
  2. Add this id to your jwt cookie. Also add a response header with the id (e.g. csrfId: xxx)
  3. Have the client save the id to local storage.
  4. On each request, the client should append a header with this id.
  5. On each request, the server should verify that the id in the received cookie matches the one in the received header.

My question is: what would stop the CSRF attacker reading the cookie manually, getting the ID and then adding that to the attack request?

Also, wont localstorage leave the ID vulnerable to a XSS + CSRF combination attack? (I'm not sure this is possible)?

Upvotes: 4

Views: 1534

Answers (1)

Kaffekoppen
Kaffekoppen

Reputation: 432

what would stop the CSRF attacker reading the cookie manually, getting the ID and then adding that to the attack request?

Setting the cookie attribute HttpOnly makes it inaccessible to Javascript. Using a custom request header prevents an attacker from adding the ID to the attack request:

«This defense relies on the same-origin policy (SOP) restriction that only JavaScript can be used to add a custom header, and only within its origin. By default, browsers do not allow JavaScript to make cross origin requests with custom headers.» -https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#use-of-custom-request-headers

Also, wont localstorage leave the ID vulnerable to a XSS + CSRF combination attack? (I'm not sure this is possible)?

CSRF protection can be bypassed if you have a XSS vulnerability, regardless of using localstorage. However, OWASP explicitly recommends not storing the CSRF token in cookies or local storage.

So I think your question is warranted, and I don't understand how that can be the best way to prevent a CSRF attack.

If I may, I recommend you check out the OWASP CSRF prevention cheatsheet if you haven't seen it already.

Upvotes: 3

Related Questions