Solved

PHP - Sessions for keeping tracked of Logged In - Security???

Posted on 2011-09-29
2
217 Views
Last Modified: 2012-05-12
I have been reading up on PHP Session Fixation and Hijacking.  I have built a small PHP script to do logins to protrect a members only area.  Basically once a user has successfully logged in (verification done in mysql database), I set a session variable that says logged in is true and another session variable for access level.

At the top of my pages is use:
session_start();
if(!isset($_SESSION['init']))
{
      session_regenerate_id();
      $_SESSION['init'] = true;
}

Do I need to do anything else to help prevent session hijacking/fixation?
0
Comment
Question by:keith1001
2 Comments
 
LVL 14

Accepted Solution

by:
Kalpan earned 250 total points
ID: 36814273
Please refer the attached code for session fixation which is good to prevent session hijacking


static public function SessionFixation()
	{
		#Accept only server generated SIDs
		$err=0;
		if (!isset($_SESSION['SERVER_GENERATED_SID']))
		{
			echo "FAILED: SERVER_GENERATED_SID<br />";
	    	$err ++;
		}
		else 
		{
			//echo "OK: SERVER_GENERATED_SID [".$_SESSION['SERVER_GENERATED_SID']."]<br />";
		}
		#Destroy session if Referrer is suspicious
		if(isset($_SERVER['HTTP_REFERER'])){
			
			
			if (strpos($_SERVER['HTTP_REFERER'], __CMS_REFERER) < 0) {
			
				//echo "FAILED: HTTP_REFERER [".$_SERVER['HTTP_REFERER']." => ".__CMS_REFERER."]<br />";
				$err ++;
			}
			else 
			{
				//echo "OK: HTTP_REFERER : ".$_SERVER['HTTP_REFERER']."<br />";
			}
		}
		#Verify that additional information is consistent throughout session
		if(!isset($_SESSION['PREV_REMOTEADDR']))
		{
			session_register('PREV_REMOTEADDR');
			$_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'];
		}
		if($_SERVER['REMOTE_ADDR'] != $_SESSION['PREV_REMOTEADDR']) {
			echo "FAILED: PREV_REMOTEADDR [PREV:".$_SESSION['PREV_REMOTEADDR']." CURR: ".$_SERVER['REMOTE_ADDR']."]<br />";
			session_register('PREV_REMOTEADDR');
			$_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR'];
			$err ++;
		}
		else 
		{
			//echo "OK: PREV_REMOTEADDR: ".$_SESSION['PREV_REMOTEADDR']."<br />";
		}
		
		#User Agent
		if(!isset($_SESSION['PREV_USERAGENT']))
		{
			session_register('SERVER_GENERATED_SID');
			session_register('PREV_USERAGENT');
			$_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT'];
		}
		
		
		if ($_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT']) {
			//echo "FAILED: PREV_USERAGENT [PREV:".$_SESSION['PREV_USERAGENT']." CURR: ".$_SERVER['HTTP_USER_AGENT']."]<br />";
			session_register('PREV_USERAGENT');
			$_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT'];
			$err ++;
		}
		else 
		{
			//echo "OK: PREV_USERAGENT: ".$_SESSION['PREV_USERAGENT']."<br />";
		}
		
			
		if($err >=1)
		{
			session_destroy(); // destroy all data in session
			session_regenerate_id(); // generate a new session identifier
			session_register('SERVER_GENERATED_SID');
			$_SESSION['SERVER_GENERATED_SID'] = true;
			return false;   
		}
		else 
		{
			return true;
		}
	}

Open in new window

0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 36814295
You can see the general design patterns used for PHP authentication in this article
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

If you combine the concepts there with the idea of a secure cookie (see code snippet), you will probably frustrate any potential session hijackers.
<?php // RAY_cookie_safety.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO ENCODE INFORMATION IN A COOKIE
// TO REDUCE THE RISK OF COOKIE TAMPERING


// A DATA DELIMITER
$dlm = '|';

// YOUR OWN SECRET CODE
$secret_code = 'MY SECRET';

// A DATA STRING THAT WE WANT TO STORE (MIGHT BE A DB KEY)
$cookie_value = 'MARY HAD A LITTLE LAMB';

// ENCODE THE DATA STRING TOGETHER WITH OUR SECRET
$cookie_code = md5($cookie_value . $secret_code);

// CONSTRUCT THE COOKIE STRING WITH THE CLEAR TEXT AND THE CODED STRING
$safe_cookie_value = $cookie_value . $dlm . $cookie_code;

// SET THE COOKIE LIKE "MARY HAD A LITTLE LAMB|cf783c37f18d007d23483b11759ec181"
setcookie('safe_cookie', $safe_cookie_value);



// WHEN STORED, THE COOKIE WILL BE URL-ENCODED SO IT WILL LOOK SOMETHING LIKE THIS ON THE BROWSER
// MARY+HAD+A+LITTLE+LAMB%7Ccf783c37f18d007d23483b11759ec181
// IT WILL BE URL-DECODED BEFORE IT IS PRESENTED TO PHP



// HOW TO TEST THE COOKIE
if (isset($_COOKIE["safe_cookie"]))
{
    // BREAK THE COOKIE VALUE APART AT THE DELIMITER
    $array = explode($dlm, $_COOKIE["safe_cookie"]);

    // ENCODE THE DATA STRING TOGETHER WITH OUT SECRET
    $cookie_test = md5($array[0] . $secret_code);

    // IF THE MD5 CODES DO NOT MATCH, THE COOKIE IS NO LONGER INTACT
    if ($cookie_test == $array[1])
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS INTACT";
    }
    else
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS CORRUPT";
    }
}
else
{
    die('COOKIE IS SET - REFRESH THE BROWSER WINDOW NOW');
}




// MUNG THE COOKIE TO DEMONSTRATE WHAT HAPPENS WITH A CORRUPT COOKIE
$_COOKIE["safe_cookie"] = str_replace('MARY', 'FRED', $_COOKIE["safe_cookie"]);

// HOW TO TEST THE COOKIE
if (isset($_COOKIE["safe_cookie"]))
{
    // BREAK THE COOKIE VALUE APART AT THE DELIMITER
    $array = explode($dlm, $_COOKIE["safe_cookie"]);

    // ENCODE THE DATA STRING TOGETHER WITH OUT SECRET
    $cookie_test = md5($array[0] . $secret_code);

    // IF THE MD5 CODES DO NOT MATCH, THE COOKIE IS NO LONGER INTACT
    if ($cookie_test == $array[1])
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS INTACT";
    }
    else
    {
        echo"<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS CORRUPT";
    }
}

Open in new window

0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question