PHP code for preventing session hijacking

Session security is a sophisticated topic, and it’s no surprise that sessions are a frequent target of attack. Most session attacks involve impersonation, where the attacker attempts to gain access to another user’s session by posing as that user.

The most crucial piece of information for an attacker is the session identifier, because this is required for any impersonation attack. There are three common methods used to obtain a valid session identifier:

  • Prediction
  • Capture
  • Fixation

The hacker may get session id of our browser in someway, and then using this session id they can continue our session in their browser.

So this session hijacking will allow the hacker to use our login restricted web pages without knowing our login credential.

Say for example, the hacker can read your emails from their browser itself if they just know session id of your browser.

Find below the sample code written in PHP for preventing session hijacking.

function prevent_session_hijacking()
{
//code for preventing session hijacking
session_start();

//Regenerate SessionID for avoiding Sesssion Fixation

if (!isset($_SESSION[‘initiated’]))

{
session_regenerate_id();
$_SESSION[‘initiated’] = true;

}

//for preventing session hijacking.
if (isset($_SESSION[‘HTTP_USER_AGENT’]))

{
if ($_SESSION[‘HTTP_USER_AGENT’] != md5($_SERVER[‘HTTP_USER_AGENT’]))

{
exit;

}

}

else

{
$_SESSION[‘HTTP_USER_AGENT’] = md5($_SERVER[‘HTTP_USER_AGENT’]);
}

}

  • session_regenerate_id — Update the current session id with a newly generated one
  • MD5-Message-Digest Algorithm
Posted in Php Tagged with: ,