Description
When browsers automatically send credentials such as cookies, allowing password changes, deletions or updates without CSRF protection may let an attacker send unwanted requests with the user’s permissions.
Potential impact
Account settings, data or permissions may be changed against the user’s wishes.
Remediation
Restrict state changes to POST/PUT/DELETE and validate a CSRF token bound to the server session. Changing the HTTP method alone does not prevent CSRF.
Examples
These excerpts change an authenticated user's password. The server session supplies $userId, and the server generates the password hash $hash. The excerpts omit session initialization, error handling, and the implementation of the application's checkToken() function.
Before
<?php
if (isset($_GET['Change'])) {
$stmt = $db->prepare('UPDATE users SET password = ? WHERE user_id = ?');
$stmt->bind_param('si', $hash, $userId);
$stmt->execute();
}
After
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit;
}
checkToken($_POST['user_token'] ?? '', $_SESSION['session_token'], 'index.php');
$stmt = $db->prepare('UPDATE users SET password = ? WHERE user_id = ?');
$stmt->bind_param('si', $hash, $userId);
$stmt->execute();
The handler accepts only POST requests. Implement checkToken() so it stops processing before the password update if the submitted token is missing or does not match the session token.