Understanding CSRF Vulnerability and Ways to Mitigate it in Web Security

Understanding CSRF Vulnerability and Ways to Mitigate it in Web Security

Understanding CSRF Vulnerability and Ways to Mitigate it in Web Security

With the increasing dependency on the internet and web-based applications, it is crucial to ensure the security of the data and transactions performed through these applications. Cross-Site Request Forgery (CSRF) is one such vulnerability that can compromise the security of web applications. In this blog post, we will discuss what CSRF vulnerability is, how it can affect web applications, and the ways to mitigate it, using PHP as an example.

What is CSRF Vulnerability?

CSRF, also known as session riding or one-click attack, is a type of security vulnerability that allows attackers to perform actions on behalf of authenticated users without their consent. In a CSRF attack, the attacker tricks the victim into executing unwanted actions, leading to potential unauthorized access, data manipulation, or even financial loss.

How CSRF Attacks Work?

Let’s understand how CSRF attacks work using a simple PHP example. Consider a scenario where a web application has a feature to update the user’s email address by making a POST request to the server.

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["email"])) {
    // Update the user's email address in the database
    $email = $_POST["email"];
    // ...
}

// ...
?>

<form action="update_email.php" method="POST">
    <input type="text" name="email" placeholder="Enter new email">
    <button type="submit">Update Email</button>
</form>

In this example, the user needs to provide a new email address and click the “Update Email” button to trigger the form submission. The server receives the POST request, validates the input, and updates the user’s email address in the database.

Now, imagine an attacker creates a malicious website containing the following HTML code:

<!DOCTYPE html>
<html>
<body>
    <h1>Click here to receive a free gift!</h1>
    <img src="http://bank.com/transfer?amount=100000&to=attacker_account" alt="Free gift">
</body>
</html>

The attacker tricks the victim into visiting their malicious website while logged into the target web application. As soon as the victim’s browser loads the attacker’s website, the hidden <img> tag sends a GET request to transfer a large amount of money to the attacker’s account.

Since the victim is authenticated with the target web application, the server considers the request valid and carries out the transaction, without the victim’s consent. This is how a CSRF attack exploits the lack of proper verification of the request’s source and integrity.

Mitigating CSRF Vulnerability

Now that we understand how CSRF attacks work, let’s discuss some effective ways to mitigate this vulnerability in web applications using PHP.

1. Synchronizer Token Pattern

The Synchronizer Token Pattern (STP) is one of the most widely used techniques to prevent CSRF attacks. It involves generating and validating a unique token for each user session that is submitted with every request. Here’s how it can be implemented in PHP:

<?php
session_start();

// Generate a CSRF token and store it in the session
if (!isset($_SESSION["csrf_token"])) {
    $_SESSION["csrf_token"] = bin2hex(openssl_random_pseudo_bytes(16));
}

// Verify the CSRF token on form submission
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["email"]) && isset($_POST["csrf_token"])) {
    if ($_POST["csrf_token"] !== $_SESSION["csrf_token"]) {
        // Handle CSRF token validation failure
        exit("Invalid CSRF token");
    }

    // Update the user's email address in the database
    $email = $_POST["email"];
    // ...
}

// ...
?>

<form action="update_email.php" method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION["csrf_token"]; ?>">
    <input type="text" name="email" placeholder="Enter new email">
    <button type="submit">Update Email</button>
</form>

In this code snippet, a CSRF token is generated and stored in the user’s session. On form submission, the token is retrieved from the session and compared with the token received in the request. If the tokens don’t match, the request is considered invalid.

Another technique to mitigate CSRF attacks is by setting the SameSite attribute for cookies. This attribute allows servers to specify whether cookies should be sent with cross-origin requests, limiting their exposure to potential CSRF attacks.

<?php
session_start();

// Set the SameSite attribute for the session cookie
session_set_cookie_params([
    "samesite" => "strict"
]);

// ...
?>

In this code snippet, the session_set_cookie_params() function is used to set the SameSite attribute for the session cookie to “strict”. This ensures that the cookie is only sent with same-site requests, preventing its inclusion in cross-origin requests.

3. Referrer Header Validation

One additional measure to strengthen CSRF protection is validating the Referer header of incoming requests. The Referer header contains the URL of the previous page visited by the user, which can be used to verify the origin of the request.

<?php
session_start();

// Verify the Referer header on form submission
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["email"])) {
    $referer = parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST);
    $expectedHost = $_SERVER["SERVER_NAME"];

    if ($referer !== $expectedHost) {
        // Handle Referer header validation failure
        exit("Invalid Referer");
    }

    // Update the user's email address in the database
    $email = $_POST["email"];
    // ...
}

// ...
?>

<form action="update_email.php" method="POST">
    <input type="text" name="email" placeholder="Enter new email">
    <button type="submit">Update Email</button>
</form>

In this code snippet, the parse_url() function is used to extract the host name from the Referer header. This host name is then compared with the expected host (i.e., the server’s host name) to ensure that the request originated from the same server.

Conclusion

CSRF vulnerability can pose a significant risk to web applications if not properly mitigated. In this blog post, we discussed what CSRF vulnerability is, how it can be exploited, and the ways to mitigate it using PHP as an example. By implementing techniques like the Synchronizer Token Pattern, SameSite cookie attribute, and Referrer header validation, developers can enhance the security of their web applications and protect user data from CSRF attacks.

Borealis Bytes offers top-notch auditing and consulting services to help secure your application landscape. Contact us today for a free consultation and let’s discuss how we can help strengthen your application security together.

Shiva
Shiva Shiva is a senior software engineer at Borealis Bytes.
comments powered by Disqus