Cross-Site Request Forgery
CSRF attacks do not target data theft but state-changing requests. With a little of social engineering (such as sharing a link via email or chat) the attacker may trick users to execute unwanted web application actions such as changing account's recovery email.
Let's say that
foo.com uses HTTP
GET requests to set the account's recovery
GET https://foo.com/account/[email protected]
A simple attack scenario may look like
- Victim is authenticated at https://foo.com
- Attacker sends a chat message to the Victim with a link
- Victim's account recovery email address is changed to
[email protected]given Attacker full control over it.
Changing the HTTP verb from
POST (or any other) won't solve the
issue as secret cookies, URL rewriting or HTTPS won't do it either.
The attack is possible because server does not distinguish between requests made during a legit user session workflow (navigation) and "malicious" ones.
As said before CSRF targets state-changing requests, what for Web Applications
most of the time means
POST requests issued by form submission.
In this scenario, when first requesting the page which renders the form, the server computes a nonce (an arbitrary number intended to be used once). This token is then included into the form as a field (most of the time this field is hidden but it is not mandatory).
Then, when the form is submitted the hidden field is sent along with other user input and. The server should then validated whether the token is part the request data and it is valid.
Such nonce/token should obey to the following requirements:
- Unique per user session
- Large random value
- Generated by a cryptographically secure random number generator
Note: Although HTTP
GET requests are not expected to change state (said to
be idempotent), due to bad programming practices they can in fact modify
resources and because of that they should be also targeted by CSRF attacks.
When dealing with APIs,
DELETE are other two common targets of CSRF
Doing all this by hand is not a good idea as it is error prone.
Most Web Application Frameworks already offer it out-of-the-box and you're advised to enable it or, if you're not using a Framework to adopt one.
OWASP has a detailed Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet which you're recommended to read.