0
votes

I'm trying to prevent cross site request forgery attacks (CRFS).
Below is my token generator code on login.php.
Is this secure enough to validate the csrf token of the form against the session token?

if(empty($_SESSION['key'])){
    $_SESSION['key'] = bin2hex(random_bytes(32));
}
$csrf = hash_hmac('sha256','secured:login',$_SESSION['key']);

Here is my form code on login.php -

<form action="<?php echo htmlspecialchars('log/logscript.php');?>" method="post" class="login_form">
    <input type="hidden" name="csrf" id="csrf" value="<?php echo $csrf;?>">
    <input type="submit" class="btn btn-login btn-block" name="submit" id="submit" value="Login">
</form>

And here is my AJAX code -

$(".login_form").submit(function(e) {
        e.preventDefault();
        var 
            sk = "<?php $csrf;?>",
            fk = $("#csrf").val(),
            t = $("#submit").val();
        $.ajax({
            url: "log/logscript.php",
            type: "post",
            data: {
                sk: sk,
                fk: fk,
                submit: t
            },
            success: function(e) {
                $(".form-msg").html(e)
            }
        });
    });

And here is my code on log/logscript.php -

session_start();
if(isset($_POST['submit'])){
    $x = $_POST['sk'];
    if(hash_equals($x,$_POST['fk'])){
        echo 'success';
    }else {
        echo 'failed';
    }
}
1
What is your question? - GrumpyCrouton
is that secured enough to validate the csrf token of form with the session token? - DarkByte
Update your question - GrumpyCrouton
isn't it enough? - DarkByte
I'm voting to close this question as off-topic because it is asking for a code review (and this thus too broad / opinion based). It could probably be adjusted to be on topic for the code review stackexchange. - Quentin

1 Answers

-1
votes

This is what you need.. This code is from Stackoverflow.com. It is what I used for most of projects.

<?php
 session_start();
 $token= md5(uniqid());
 $_SESSION['update_token']= $token;
 session_write_close();
?>
<html>
<body>
<form method="post" action="update.php">
 <input type="hidden" name="token" value="<?php echo $token; ?>" />
Do you really want to delete?
<input type="submit" value=" Yes " />
<input type="button" value=" No " onclick="history.go(-1);" />
</form>
</body>
</html>

 save.php

<?php
 session_start();
 $token = $_SESSION['update_token'];
 unset($_SESSION['update_token']);
 session_write_close();
 if ($token && $_POST['token']==$token) {
   // update the record
 } else {
   // there is CSRF attack.
 }
?>

In addition also ensure that you regenerate session id as soon as your login user is authenticated.

//Regenerate Session Id to ensure that Session Fixation Attack is not Possible...

session_regenerate_id();