Monday, May 14, 2018

Cross-site Request Forgery protection in web applications via Double Submit Cookies Patterns

What is Double submit cookies?

A double submit cookie is defined as sending a random value in both a cookie and as a request parameter, with the server verifying if the cookie value and request value match.

Simply what it means is setting a cookie with a generated token in server side so that attacker cannot generate a valid token.

Let's implement this, first follow the steps in this article https://theekshanasl.blogspot.com/2018/05/cross-site-request-forgery-protection_14.html

then set a cookie when the token is generated as below.


<?php 
session_start();
$s_id = session_id();
if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
    $token = $_SESSION['token'];

    setcookie("csr_token", $token, time() + (440), "/", "localhost", false, true);
}
setcookie("s_id", $s_id, time() + (1440), "/", "localhost", false, true);
?>

and finally, change login.php file to get the cookie value "csr_token" to a variable and check in the if condition like below.



<?php 
session_start();
$uname=$_POST['uname'];
$password=$_POST['password'];
$userSession=$_COOKIE['s_id'];
$user_token=$_COOKIE['csr_token'];
$csr=$_POST['csr'];
if(empty($uname) || empty($password)){
    echo "Please fill all the required fields\n";
}else{
    
    if($uname="admin" && $password="admin" && $userSession=session_id() && $csr=$_SESSION['token'] && $csr=$user_token){
        echo "Login successful, Hello admin";
    }else{
        echo "Login un-successful";
    }
}
?>

Complete source code: https://github.com/theekshanasl/SSS/tree/master/Assignment%202

0 comments:

Post a Comment