Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF prevention using local storage and cookie

Tags:

security

csrf

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)?

like image 449
MrFizz Avatar asked Oct 18 '25 20:10

MrFizz


1 Answers

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.

like image 184
Kaffekoppen Avatar answered Oct 21 '25 10:10

Kaffekoppen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!