Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF tokens - how to implement properly?

Tags:

security

php

csrf

I've just setup a simple CSRF protection in my application. It creates a unique crumb which are validated against a session value upon submitting a form.

Unfortunately this means now that I can't keep multiple instances (tabs in the browser) of my application open simultaneously as the CSRF crumbs collide with each other.

Should I create an individual token for each actual form or use a mutual, shared crumb for all my forms? What are common sense here?

like image 414
Industrial Avatar asked Sep 15 '11 15:09

Industrial


People also ask

How CSRF token is passed?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client.

What's the most suitable solution to CSRF?

Token Based Mitigation. The synchronizer token pattern is one of the most popular and recommended methods to mitigate CSRF.


1 Answers

You can do either. It depends on the level of security you want.

The OWASP Enterprise Security API (ESAPI) uses the single token per user session method. That is probably a pretty effective method assuming you have no XSS holes and you have reasonably short session timeouts. If you allow sessions to stay alive for days or weeks, then this is not a good approach.

Personally, I do not find it difficult to use a different token for each instance of each form. I store a structure in the user's session with key-value pairs. The key for each item is the ID of the form, the value is another structure that contain the token and an expiry date for that token. Typically I will only allow a token to live for 10-20 minutes, then it expires. For longer forms I may give it a long expiry time.

If you want to be able to support the same form in multiple browser tabs in the same session, then my method becomes a little trickery but could still be easily done by having unique form IDs.

like image 64
Jason Dean Avatar answered Oct 08 '22 23:10

Jason Dean