Understanding and Detecting CSRF Vulnerabilities

What is CSRF?

Cross-Site Request Forgery (CSRF) is a web-based attack vector that forces authenticated users to submit unwanted requests to a web application. The attack exploits the trust that a web application has in the user's browser by leveraging active sessions and authentication credentials. When successful, attackers can perform unauthorized operations such as changing account passwords, transferring funds, or modifying user data without the victim's knowledge.

Attack Mechanism

The CSRF attack flow operates as follows:

  1. A user authenticates with a legitimate web application (Site A), and the server returns a session cookie to the browser
  2. The user remains logged into Site A while simultaneously browsing an attacker-controlled website (Site B)
  3. Site B contains malicious code that triggers automatic requests to Site A
  4. The user's browser automatically includes the valid session cookie with these requests
  5. Site A processes the forged requests using the authanticated user's credentials, believing they originated from the legitimate user

In simpler terms, CSRF attacks manipulate URLs to execute unauthorized actions using the victim's active session credentials.

Discovery Tools

  • Burp Suite
  • Acunetix Web Vulnerability Scanner
  • IBM AppScan
  • Netsparker
  • OWASP CSRFTester
  • Custom CSRF request builders

Practical Laboratory Examples

Low Security Level

In the DVWA environment at the low difficulty setting, the password change functionality accepts parameters directly through the query string. The application performs only basic validation by checking weather the two password fields match.

Constructing a malicious request follows this pattern:

http://127.0.0.1/dvwa/vulnerabilities/csrf/?password_new=hacked123&password_conf=hacked123&Change=Change#

The vulnerability exists because the application trusts requests without validating the origin. Successful execution returns "Password Changed."

Backend implementation reveals the flaw:

<?php 

if( isset( $_GET[ 'Change' ] ) ) {
    $pass_new  = $_GET[ 'password_new' ];
    $pass_conf = $_GET[ 'password_conf' ];

    if( $pass_new == $pass_conf ) {
        $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 );

        $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . ";";
        $result = mysqli_query($GLOBALS["___mysqli_ston"],  $insert ) or die( '' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '' );

        echo "Password Changed.";
    }
    else {
        echo "Passwords did not match.";
    }

    ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}

?>

The vulnerability manifests at line 9 where only password matching validation occurs, with no origin verification whatsoever.

Medium Security Level

At the medium security tier, the application implements Referer header validation. Direct URL manipulation now fails with the message "That request didn't look correct."

The application validates that the Referer header contains the server name:

if( stripos( $_SERVER[ 'HTTP_REFERER' ] ,$_SERVER[ 'SERVER_NAME' ]) !== false ) {

The stripos() function performs case-insensitive substring matching, checking whether the server name appears anywhere in the Referer header. String positions begin at 0, not 1.

To bypass this protection, capture a legitimate request's Referer header and replay it with the attack request:

Referer: http://127.0.0.1/dvwa/vulnerabilities/csrf/?password_new=legitimate&password_conf=legitimate&Change=Change

By preserving the original Referer header during the attack, the request passes validation and executes successfully.

High Security Level

The high difficulty level introduces anti-CSRF tokens. Each password change request requires a unique, randomly generated token that the server issues dynamically.

Request structure includes the token parameter:

GET /dvwa/vulnerabilities/csrf/?password_new=admin1&password_conf=admin1&Change=Change&user_token=1e457f530db4c98d317a676e042319ad HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0
Cookie: security=high; PHPSESSID=1vp4qsnhuarsp59enbrv5gtio4

The token mechanism requires attackers to obtain a valid token before each attack attempt. Successfully exploiting this configuration requires chaining with other vulnerabilities such as Cross-Site Scripting (XSS) to extract tokens programmatically.

Detecting CSRF Vulnerabilities

Black Box Testing

For applications without source code access:

  1. Identify state-changing functionality (password modifications, data submissions, account updates)
  2. Capture requests using a proxy tool
  3. Examine whether anti-CSRF tokens or custom headers are absent
  4. Remove session identifiers and replay requests to verify if they execute independently
  5. Compare responses—with and without Referer headers—to identify potential vulnerabilities

White Box Testing

Source code review approaches:

  1. Search for anti-CSRF token validation routines
  2. Verify Referer header checking implementations
  3. Confirm SameSite cookie attributes are configured
  4. Examine authorization logic for state-changing operations

Prevention Strategies

Primary Mitigations

  1. Implement Anti-CSRF Tokens: Generate unique, random tokens for each user session and validate them on server-side operations
  2. Validate Referer Headers: Verify requests originate from expected domains
  3. Use SameSite Cookies: Configure cookie attributes to prevent cross-origin transmission
  4. Employ Same-Origin Policy: Utilize CORS headers appropriately

Secondary Mitigations

  1. Require Re-authentication: Implement step-verification for sensitive operations
  2. Use POST Methods: Prefer POST over GET for state-changing operations
  3. Implement CAPTCHAs: Add verification challenges for critical actions
  4. Add Custom Headers: Require headers that browsers cannot forge automatically

Security Considerations

Web applications must assume that incoming requests may originate from malicious sources. Any functionality that alters state requires proper validation regardless of apparent request origin. Defense-in-depth approaches combining multiple mtiigation strategies provide stronger protection than single-layer solutions.

Modern web frameworks often include built-in CSRF protection mechanisms. When implementing custom solutions, ensure comprehensive coverage across all state-changing endpoints.

Tags: csrf Web Security Vulnerability Assessment Penetration Testing OWASP

Posted on Fri, 26 Jun 2026 16:34:07 +0000 by phpfreak