Home > Software design >  Is this a correct way to validate my CSRF token?
Is this a correct way to validate my CSRF token?

Time:08-11

I want to correctly implement a CSRF token with validation into the forms of my website.

Here is how the token is generated:

$_SESSION["token"] = bin2hex(random_bytes(32));

Here is the hidden field inside of my form that changes every time the form is submitted or every time the page is refreshed:

<input type="hidden" name="token" value="<?=$_SESSION["token"]?>">

Here is an example of what is seen when the form in inspected:

<input type="hidden" name="token" value="3c33c5dc178293f9bcaff264b90836780887efe16c339d01c1cbe34bf9ecbddd">

Now when the form is submitted this is the validation I put in place for the token:

  if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //CSRF TOKEN   VALIDATION
 if (!isset($_POST['token']) || ($_POST['token'] !== $_SESSION['token'])) {
   exit;
 } 

I want to know if this validating that the ($_POST['token'] !== $_SESSION['token']) ?

Because when I change my script to this:

if($_SERVER["REQUEST_METHOD"] == "POST")
{
    //CSRF TOKEN   VALIDATION
 if (!isset($_POST['token'])) {
   exit;
 }
 

Nothing changes and the form is submitted exactly like before.

Is my original IF statement only checking if a $_POST isset?

If so, is this still a secure way to protect against CSRF attacks?

Thank you in advance!

CodePudding user response:

 if (!isset($_POST['token']) || ($_POST['token'] !== $_SESSION['token'])) {

This checks:

  • If there is a token (and fails if there isn't) and
  • If the token in the submission matches the token in the session (and fails if it isn't).

 if (!isset($_POST['token'])) {

This checks:

  • If there is a token (and fails if there isn't) and

… but doesn't care if it matches the one in the session.

This means the second version is vulnerable because an attacker making a CSRF attack could shove any old token in the form they submit and it will work so long as the user is logged in.


The first version isn't vulnerable because the attacker has no way to know what token is in the visitor's session on your site, so they can't put it in their form.

  • Related