-1

I am trying to pass data in a form that has code that checks for csrf attacks first and then sends dat using php, but the code always tells me that there is an attack even though there is not attack The code always just executes the error message and the rest of the code is not considered.

php code:

    <?php 
$csrf_avoid= bin2hex(random_bytes(20));
 $_SESSION['auth_token'] = $csrf_avoid;                   
if (isset($_POST["save_entry"])) {
                             
if ($_POST["auth_token"] !== $csrf_avoid) {
// show an error message
echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
                          // return 405 http status code
 exit();
  }
 else{                                                
// do anything here there is no csrf attacks                                                
 }                  
 }              
?>

html

<input type="hidden" name="auth_token" value="<?php echo $csrf_avoid;?>">
  • You generate random bytes and expect the submitted value to match, that does not make sense, when you submit a new value will be generated. You need to check the session – Lk77 Jan 17 '23 at 08:31
  • Could you please correct my code because I am very stuck – amntago shifeg Jan 17 '23 at 08:35

1 Answers1

-1

first of, don't generate a token every time, and check the session when submitting :

if(!isset($_SESSION['auth_token'])) {
    $csrf_avoid = bin2hex(random_bytes(20));
    $_SESSION['auth_token'] = $csrf_avoid;     
}
                
if (isset($_POST["save_entry"])) {
    //check the session                          
    if ($_SESSION['auth_token'] !== $csrf_avoid) {
        // show an error message
        echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
        // return 405 http status code
        exit();
    }
    else {                                                
        // do anything here there is no csrf attacks

        // you could regenerate token on submit, so the current one becomes invalid
        $csrf_avoid = bin2hex(random_bytes(20));
        $_SESSION['auth_token'] = $csrf_avoid;                                                  
    }                  
}

Also change your input to :

<input type="hidden" name="auth_token" value="<?php echo $_SESSION['auth_token'];?>">
Lk77
  • 2,203
  • 1
  • 10
  • 15