Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2011-09-29
2
Medium Priority
?
231 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 1000 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

916 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