Tuesday, February 5, 2013

How to prevent session hijacking on PHP

Using SSL is the best solution to encrypt all http requests, but when it's not a possibility, you can store IP's address along with other details (name, username, email, password...) of authenticate users by adding this line :

$_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];

and then you check if session available,and  if IP address don't match you call function that delete the current session and ask user to login in again due to a server problem or technical error.
here check code :
if ($_SESSION['ip'] != $_SERVER['REMOTE_ADDR']) user_hijack();

function user_hijack(){
session_start();
session = array();
session_destroy(); // DESTROY SESSION
header(location: login.php); // REDIRECT USER TO LOGIN PAGE
}

also you can store a copy of  uer agent to detect users that share the ip address on a home or on their work.

Use this following line :
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
and here the code to check the current User agent :
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT'];) user_hijack();

Resume:

Dis-allow multiple sessions under the same account, making sure you aren't checking this soely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth

Using Relation based hyperlinks Generates a link ( eg. http://mysite.com/secure.php?token=2349df98sdf98a9asdf8fas98df8 ) The link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page redirection the randomly generated token corresponds to a requested page.

  • Upon reload, several checks are done. 
  • Originating IP Address
  • HTTP_USER_AGENT 
  • Session Token 
  • you get the point. 


Short Life-span session authentication cookie. a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.
Disqus Comments