Cross-Site Request Forgery

suggest change

Problem

Cross-Site Request Forgery or CSRF can force an end user to unknowingly generate malicious requests to a web server. This attack vector can be exploited in both POST and GET requests. Suppose /delete.php?accnt=12 deletes the account given in the accnt parameter of a GET request. If an authenticated user loads the following markup in any other application

<img src="http://domain.com/delete.php?accnt=12" width="0" height="0" border="0">

the account would be deleted.

Solution

A common solution to this problem is the use of CSRF tokens. CSRF tokens are embedded into requests so that a web application can trust that a request came from an expected source as part of the application’s normal workflow. First the user performs some action, such as viewing a form, that triggers the creation of a unique token. A sample form implementing this might look like

<form method="get" action="/delete.php">
  <input type="text" name="accnt" placeholder="accnt number" />
  <input type="hidden" name="csrf_token" value="<randomToken>" />
  <input type="submit" />
</form>

The token can then be validated by the server against the user session after form submission to eliminate malicious requests.

Sample code

Here is sample code for a basic implementation:

/* Code to generate a CSRF token and store the same */
...
<?php
  session_start();
  function generate_token() {
    // Check if a token is present for the current session
    if(!isset($_SESSION["csrf_token"])) {
        // No token present, generate a new one
        $token = bin2hex(random_bytes(32));
        $_SESSION["csrf_token"] = $token;
    } else {
        // Reuse the token
        $token = $_SESSION["csrf_token"];
    }
    return $token;
  }
?>
<body>
  <form method="get" action="/delete.php">
    <input type="text" name="accnt" placeholder="accnt number" />
    <input type="hidden" name="csrf_token" value="<?php echo generate_token();?>" />
    <input type="submit" />
  </form>
</body>
...
/* Code to validate token and drop malicious requests */
...
<?php
  session_start();
  if (empty($_GET["csrf_token"]) || empty($_SESSION["csrf_token"]) || !hash_equals($_SESSION["csrf_token"], $_GET["csrf_token"])) {
    // Reset token
    unset($_SESSION["csrf_token"]);
    die("CSRF token validation failed");
  }
?>
...

Many libraries and frameworks already implement CSRF validation. This sample is only a starting point. Regenerate the token when the privilege level changes so a stolen or fixed token cannot be reused. random_bytes() requires PHP 7 or later. bin2hex() keeps the token printable; raw binary from random_bytes() is not safe in an HTML attribute.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents