Solved

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

Posted on 2011-09-29
2
223 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 110

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

Technology Partners: 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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses four methods for overlaying images in a container on a web page
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 look for a specific file type in a local or remote server directory using PHP.

623 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