Cross-Site Request Forgery (CSRF)
Am I Vulnerable To 'Cross-Site Request Forgery (CSRF)'?
To check whether an application is vulnerable, see if any links and forms lack an unpredictable CSRF token. Without such a token, attackers can forge malicious requests. An alternate defense is to require the user to prove they intended to submit the request, either through reauthentication, or some other proof they are a real user (e.g., a CAPTCHA).
Focus on the links and forms that invoke state-changing functions, since those are the most important CSRF targets.
You should check multistep transactions, as they are not inherently immune. Attackers can easily forge a series of requests by using multiple tags or possibly JavaScript.
Note that session cookies, source IP addresses, and other information automatically sent by the browser don’t provide any defense against CSRF since this information is also included in forged requests.
OWASP’s CSRF Tester tool can help generate test cases to demonstrate the dangers of CSRF flaws.
How Do I Prevent 'Cross-Site Request Forgery (CSRF)'?
Preventing CSRF usually requires the inclusion of an unpredictable token in each HTTP request. Such tokens should, at a minimum, be unique per user session.
- The preferred option is to include the unique token in a hidden field. This causes the value to be sent in the body of the HTTP request, avoiding its inclusion in the URL, which is more prone to exposure.
The unique token can also be included in the URL itself, or a URL parameter. However, such placement runs a greater risk that the URL will be exposed to an attacker, thus compromising the secret token.
OWASP’s CSRF Guard can automatically include such tokens in Java EE, .NET, or PHP apps. OWASP’s ESAPI includes methods developers can use to prevent CSRF vulnerabilities.
Requiring the user to reauthenticate, or prove they are a user (e.g., via a CAPTCHA) can also protect against CSRF.
Example Attack Scenarios
The application allows a user to submit a state changing request that does not include anything secret. For example:
http://example.com/app/transferFunds?amount=1500&destinationAccount=4673243243
So, the attacker constructs a request that will transfer money from the victim’s account to the attacker’s account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s control:
<img src="http://example.com/app/transferFunds?amount=1500&destinationAccount=attackersAcct#" width="0" height="0" />
If the victim visits any of the attacker’s sites while already authenticated to example.com, these forged requests will automatically include the user’s session info, authorizing the attacker’s request.