How to integrate these pieces of code to protect against session hijacking

85 Views Asked by At

I'm using these docs to integrate a certain level of protection against session hijacking (bottom of page). While I can understand the basics of what the article explains, I'm still new to all this and I'm just not able to pin-point what I should do.

I get how this would work:

<?php

session_start();

if (isset($_SESSION['HTTP_USER_AGENT']))
{
    if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
    {
        /* Prompt for password */
        exit;
    }
}
else
{
    $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}

?>

... and I kinda understand how this can make the above more secure:

<?php

$string = $_SERVER['HTTP_USER_AGENT'];
$string .= 'SHIFLETT';

/* Add any other data that is consistent */

$fingerprint = md5($string);

?>

However, I'm stuck at combining the two into one working script. The docs state:

we should pass this fingerprint as a URL variable.

What does that mean? Do I need to pass the fingerprint in the URL and then use $_GET on each page? Anyone who can help me combining these two snippets of code into one file that I can include in all my PHP files?

1

There are 1 best solutions below

0
On

yes, you'd need to add this token to any urls and then check it on every page.

Basically what you're trying to accomplish is what cryptographers call a NONCE (number used once). The idea is to generate the NONCE using the params and then validate that the params haven't been tampered with.

Ideally this should be a hash salted with something random and used once. There are many libraries that will take care of it for you. Remember that hashes are not symmetric, i.e you can't un-hash request variables to see that it's the same thing.

What you can do is take a hash of the parameters and compare the hashes. It's important to remember about salts, because without them you'd be susceptible to rainbow tables.

Also if you use $_REQUEST rather than $_GET you can reuse the same logic for both $_POST and $_GET

You can take a look at this library for example, http://fullthrottledevelopment.com/php-nonce-library you can also borrow the nonce generating code from Wordpress