Solved

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

Posted on 2011-09-29
2
213 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
Comment Utility
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 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

743 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now