Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

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…
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.
The viewer will learn how to dynamically set the form action using jQuery.
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 …

688 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