A8 – Preventing CSRF

When Web applications don't use a per-session or per-operation token or if the token is not correctly implemented, they may be vulnerable to cross-site request forgery and an attacker may force authenticated users to do unwanted operations.

CSRF is the eighth most critical vulnerability in Web applications nowadays, according to OWASP, and we will see how to prevent it in our applications in this recipe.

How to do it...

  1. The first and the most practical solution for CSRF is to implement a unique, per-operation token, so every time the user tries and executes an action, a new token is generated and verified server-side.
  2. The unique token should not be easily guessable by an attacker; so they can't include it in the CSRF page. Random generation is a fine choice here.
  3. Include the token to be sent in every form that could be a target for CSRF attacks. "Add to cart" requests, password change forms, e-mail, contact, or shipping information management and money transfer in banking sites are good examples.
  4. The token should be sent to the server in every request; this can be done in the URL, as any other variable or as a hidden field, which is recommended.
  5. The use of a CAPTCHA control is also a way of preventing CSRF.
  6. Also, it is a good practice to ask for reauthentication in some critical operations, such as money transfers in banking applications.

How it works...

Preventing CSRF is all about ensuring that the authenticated user is the one requesting the operation. Due to the way browsers and web applications work, the best choice is to use a token to validate operations or, when possible, a CAPTCHA control.

As attackers are going to try to break the token generation or validation systems, it is very important to generate them securely, in a way that attackers cannot guess them, and make them unique for each user and each operation because reusing them voids their purpose.

CAPTCHA controls and reauthentication are at some point, intrusive and annoying for users, but if the criticality of the operation is worth it, they may be willing to accept them in exchange for an extra level of security.

See also

There are programming libraries that may help in the implementation of CSRF protections, saving tons of work of developers. One such example is the CSRF Guard from OWASP: https://www.owasp.org/index.php/CSRFGuard.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.249.210