CSRF Anti-Form Spoofing Token Generation

A common method used by attackers is a spoofed form submission. There are various ways to spoof forms, the easiest of which is to simply copy a target form and execute it from a different location. Spoofing a form makes it possible for an attacker to remove all client-side restrictions imposed upon the form in order to submit any and all manner of data to your application. Code explanation below. The code should be inserted in the main form PHP file.

<?php session_start();                                // Initialize session
session_regenerate_id(true);                        // Replace current session ID with a new one
//Form Spoofing Protection
if (isset($_POST['Submit'])) {
if (isset($_SESSION['token']) && ($_POST['token'] == $_SESSION['token'])) {}}
//Token is good - process data

$token = hash('sha256', uniqid(mt_rand(), true));    //Hash and encrypt token
$_SESSION['token'] = $token;                        //Store token in variable

<input type="hidden" name="token" value="<?php echo $token; ?>"/>

<input type="submit" value="Submit" id="Submit" name="Submit"/>
</fieldset>
</form>


Code used to prevent spoofing-  $_SESSION[‘token’] = md5(time());

Token should be created at the start of page and store in on Session, and also will be posted as a hidden field on the form. When visitor submits the form, then the token value stored at session will be matched with hidden Form’s value to ensure that its coming from that page.

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

// token not found

}else {//continue submission of form}

The above code checks whether the form is submitted from the same location and thus prevents SPOOFING FORM SUBMISSIONS.

Another option if previous code does not work properly:

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {

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

        echo 'Form spoofing error!';
    } else {
        //Continue with validation ect
        echo 'alls good!';
    }
}
//set after any checks on previous values
$_SESSION['token_key'] = sha1(microtime(true));
$_SESSION['token'] = sha1(microtime(true)+1);
?>
<form method="POST" action="">
    <input type="hidden" name="<?php echo $_SESSION['token_key'];?>" value="<?php echo $_SESSION['token'];?>" />
    <p><input type="text" name="yada" size="20">
    <input type="submit" value="Submit" name="B1"></p>
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>