871
and also as a cookie value. When a POST request is sent to the site, the request should only be
considered valid if the form value and the cookie value are the same. Because of the same-origin
policy, an attacker cannot read or modify the value stored in the cookie. To successfully submit a
form on behalf of the user, the attacker would have to correctly guess the pseudorandom value.
If the pseudorandom value is cryptographically strong, this will be prohibitively difficult. This
technique requires Javascript, so it may not work for browsers that have Javascript disabled.
[REF-331]
Phase: Architecture and Design
Do not use the GET method for any request that triggers a state change.
Phase: Implementation
Check the HTTP Referer header to see if the request originated from an expected page. This
could break legitimate functionality, because users or proxies may have disabled sending the
Referer for privacy reasons.
Demonstrative Examples
Example 1:
This example PHP code attempts to secure the form submission process by validating that the
user submitting the form has a valid session. A CSRF attack would not be prevented by this
countermeasure because the attacker forges a request through the user's web browser in which a
valid session already exists.
The following HTML is intended to allow a user to update a profile.
Example Language: HTML (Bad)
<form action="/url/profile.php" method="post">
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>
<br/>
<input type="text" name="email"/>
<input type="submit" name="submit" value="Update"/>
</form>
profile.php contains the following code.
Example Language: PHP (Bad)
// initiate the session in order to validate sessions
session_start();
//if the session is registered to a valid user then allow update
if (! session_is_registered("username")) {
echo "invalid session detected!";
// Redirect user to login page
[...]
exit;
}
// The user session is valid, so process the request
// and update the information
update_profile();
function update_profile {
// read in the data from $POST and send an update
// to the database
SendUpdateToDatabase($_SESSION['username'], $_POST['email']);
[...]
echo "Your profile has been successfully updated.";
}
This code may look protected since it checks for a valid session. However, CSRF attacks can be
staged from virtually any tag or HTML construct, including image tags, links, embed or object tags,
or other attributes that load background images.
CWE Version 4.14
CWE-352: Cross-Site Request Forgery (CSRF)
CWE-352: Cross-Site Request Forgery (CSRF)