The vulnerability is Cross-Site Request Forgery (CSRF)
php
<?php
session_start();
$username = $_SESSION['username'] ?? 'Guest';
?><!DOCTYPE html><html><head><title>CSRF Demo</title></head><body><h1>Welcome, <?php echo $username; ?>!</h1><?php if ($username !== 'Guest'): ?><formmethod="post"action="update.php"><inputtype="text"name="username"placeholder="Enter your new username"><inputtype="submit"name="submit"value="Update"></form><?php endif; ?></body></html>
php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
// Update username in database
$_SESSION['username'] = $username;
header('Location: index.php');
exit();
}
?>
In this code, an attacker can create an HTML form on a different website and submit it to the `update.php` script, which would process the form data and update the user's information without their knowledge or consent. To fix this vulnerability, we need to add a CSRF token to the form that prevents outside requests from being submitted. Here's an example:
php
<?php
// Generate a CSRF token and add it to the session
session_start();
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
?><formmethod="post"action="update.php"><inputtype="hidden"name="csrf_token"value="<?php echo $_SESSION['csrf_token']; ?>"><inputtype="text"name="username"placeholder="Enter your username"><inputtype="password"name="password"placeholder="Enter your password"><inputtype="submit"name="submit"value="Update"></form>