Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF protection: do we have to generate a token for every form?

Tags:

security

csrf

Do we have to generate a token, for every form in a website? I mean, every-time to generate different token for every requested form? If not, why?

like image 674
Centurion Avatar asked Dec 28 '11 12:12

Centurion


People also ask

When should CSRF token be generated?

For additional safety, the field containing the CSRF token should be placed as early as possible within the HTML document, ideally before any non-hidden input fields and before any locations where user-controllable data is embedded within the HTML.

Are CSRF tokens single use?

Synchronizer Token Pattern CSRF tokens should be generated on the server-side. They can be generated once per user session or for each request.

Can CSRF tokens be reused?

edited. We recently had a pentest running and one security flaw that was reported is that CSRF-Tokens can be reused over multiple requests.

How is CSRF token created?

A CSRF Token is a secret, unique and unpredictable value a server-side application generates in order to protect CSRF vulnerable resources. The tokens are generated and submitted by the server-side application in a subsequent HTTP request made by the client.


2 Answers

In general, it suffices to have just one token per session, a so called per-session token:

In general, developers need only generate this token once for the current session. After initial generation of this token, the value is stored in the session and is utilized for each subsequent request until the session expires.

If you want to further enhance the security, you can use one token per each form/URL (per-form token) to mitigate the impact when one token leaks (e. g. XSS) as an attacker would only be able to successfully attack that specific form/URL.

But using per-request tokens, i. e. tokens that change with each request, rather cuts the usability of the website as it restricts parallel browsing:

To further enhance the security of this proposed design, consider randomizing the CSRF token […] for each request. Implementing this approach results in the generation of per-request tokens as opposed to per-session tokens. Note, however, that this may result in usability concerns. For example, the "Back" button browser capability is often hindered as the previous page may contain a token that is no longer valid. Interaction with this previous page will result in a CSRF false positive security event at the server.

So I recommend you to use either per-session tokens or per-form tokens.

like image 57
Gumbo Avatar answered Oct 06 '22 00:10

Gumbo


No, you just need to generate a token on a per-session basis.

Tokens are very unlikely to be leaked accidentally by users and generating a token per form makes things very complicated if a user is browsing the site in two different tabs/windows at once.

like image 33
Quentin Avatar answered Oct 06 '22 02:10

Quentin