Site icon Treehouse Blog

How to Create Bulletproof Sessions

In the first part of this series we went over how a cookie works and what can be done to secure them. In this section we’re going to go over ways to add additional security to the session beyond the cookie itself.

By the end of this article we will written our own wrapper class for “session_start” that protects our session from a number of attacks while taking into account some of the unique challenges presented by modern ajax-heavy websites.

Session Specific Attacks

Through the use of sessions your identity is maintained as you use a website, and just as in real life identity theft is a concern. By taking over your session an attacker would essentially become you on a website, with access to all of the actions, information and privileges that entails.

The main thing that an attacker needs to steal a session is the session ID. There are three ways an attacker normally goings about doing this, all of which can be protected against but are, by default, completely open.

Starting the Session

The default session setup is not at all secure by itself, so we’re going to create a wrapper to add the security we need. To make this code more portable we’re going to build it as a static function of a php class called SessionManager.

To begin our sessionStart function is going to set the name cookie options for the session. Like all cookies we’re going to need to make some decisions about what is going to need access to the session ID. Since these options depend on the application itself lets add arguments we can change based on our specific needs.

For security we can hardcode the “HttpOnly” argument, as session ids are often the juiciest target for cross site scripting attacks.

class SessionManager
{
   static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
   {
      // Set the cookie name before we start.
      session_name($name . '_Session');

      // Set the domain to default to the current domain.
      $domain = isset($domain) ? $domain : isset($_SERVER['SERVER_NAME']);

      // Set the default secure value to whether the site is being accessed with SSL
      $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

      // Set the cookie settings and start the session
      session_set_cookie_params($limit, $path, $domain, $secure, true);
      session_start();
   }
}

Using the new class is as easy as including it and running one line but additional options can make it more restrictive.

SessionManage::sessionStart('InstallationName');
SessionManage::sessionStart('Blog_myBlog', 0, '/myBlog/', 'www.site.com');
SessionManage::sessionStart('Accounts_Bank', 0, '/', 'accounts.bank.com', true);

Lock the Session to a Host

Now that our wrapper class is in place and functional we can start building in additional security by restricting the session to the same IP address and User Agent (or browser) as when the session was first opened. This way if the session ID is stolen or guessed the attacker still has to get ahold of the user agent (admittedly not too difficult if they got the session ID) and somehow find a way to get the same IP address.

These attacks only help if the user is not on the same network. The user agent check only adds minor security, since many attacks that compromise the cookie are going to do the same to the user agent. If an attacker is on the same network as the target there is a good chance they already have the same external IP address, as it is pretty common for a network to use private internal addresses while presenting only a single IP address to the internet. This is why it is important to evaluate the need for SSL.

We’re going to add these new checks to our class in the function preventHijacking. This function will return false on new sessions or when a session is loaded by a host with a different IP address or browser. preventHijacking will true if the session is valid and false otherwise. This means it will return false not just on malicious attempts but completely new sessions as well.

static protected function preventHijacking()
{
	if(!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
		return false;

	if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
		return false;

	if( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
		return false;

	return true;
}

Now that we have a way to identify hijacking attempts we need to set up a way to respond to them. For us this means two things- clearing out the old session data and inserting the IP address and user agent into the new session.

static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
	...
	session_start();

	if(!self::preventHijacking())
	{
		$_SESSION = array();
		$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
	}
}

Session Fixation

So far we have effectively eliminated the possibility of brute force guessing. We’ve also made it so any attempts at capturing the session ID would require the attacker to be on the same network as the user in order to take advantage of that ID, while also discussing enforcing SSL to make capturing the session more difficult through traditional means. However, what if the attacker could set the session ID themselves?

By getting the user to follow a link with a session ID in it the attacker can trick the user into starting a session with the ID of the attacker’s choosing. Rather than guess or steal an ID the attacker will have it right from the start. Many web environments, including PHP, allow session ids to be set through the URL, primarily to get around systems which do not support cookies. Just like with regular cookies the value sent by the client is the value used for the ID, so in this case the value in the URL becomes the session ID.

The solution to this is to change the session ID. How often you do this is tends to be a matter of great debate, but at the bare minimum the ID should be changed when new sessions are created and when the user changes privileges (logs in or out).

A First Attempt At Regenerating the ID

Regenerating the ID is fairly simply in php. Deceptively simple one might say. The function “session_regenerate_id” lets us tell the system to use a new ID. It can also optionally delete the old session.

// Leaves old session intact
session_regenerate_id();

// Deletes old session
session_regenerate_id(true);

If you don’t delete the old session then it is still vulnerable to hijacking and whatever access it had can be granted to an attacker. If you’re changing the session ID often without deleting the old ones you could be creating more holes by leaving a trail of old, but valid, sessions.

Regenerating the ID in the World of Ajax

If an application creates a lot of quick connections to the server some interesting things can happen. PHP, and many other languages, restricts access to the session data to one running script at a time, so if multiple requests come in that try to access the session data the second request (and any other) gets queued up. When the first request changes the ID and deletes the old session the second request still has the old session ID which no longer exists. This results in a third, new session being opened and generally means your user gets logged out.

This bug is ridiculously hard to diagnose as the timing of not just the requests but the ID regeneration has to be just right. In sites that don’t make requests to the server using javascript this type of bug may never be encountered at all, as the time between page loads is more than long enough for the browser to have updated its session info. For sites that make use of ajax techniques, however, this issue will have a chance of occurring whenever the session ID is changed.

In our final update to the SessionManager class we’re going to write a fix for this problem. Rather than delete the session immediately when we change the ID, we’re going to mark the old session as obsolete and mark it to expire in ten seconds. This way any queued up requests will still have access to the expired session but we don’t have to leave it open forever.

To accomplish this we’re going to add the regenerateSession function. This function adds the obsolete flag and expiration to the session, regenerates the ID to create the new session and saves them both. It then reopens the new session and removes the obsolete flag. Unlike our other internal functions we are leaving this one open for use outside the class so that it can be tied into login scripts.

static function regenerateSession()
{
	// If this session is obsolete it means there already is a new id
	if(isset($_SESSION['OBSOLETE']) || $_SESSION['OBSOLETE'] == true)
		return;

	// Set current session to expire in 10 seconds
	$_SESSION['OBSOLETE'] = true;
	$_SESSION['EXPIRES'] = time() + 10;

	// Create new session without destroying the old one
	session_regenerate_id(false);

	// Grab current session ID and close both sessions to allow other scripts to use them
	$newSession = session_id();
	session_write_close();

	// Set session ID to the new one, and start it back up again
	session_id($newSession);
	session_start();

	// Now we unset the obsolete and expiration values for the session we want to keep
	unset($_SESSION['OBSOLETE']);
	unset($_SESSION['EXPIRES']);
}

We need to add another function to check for the obsolete flag and to see if the session has expired.

static protected function validateSession()
{
	if( isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
		return false;

	if(isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
		return false;

	return true;
}

Finally, in the last change to our SessionManager, we need to update our SessionStart function. It needs to call the regenerateSession function on new requests and periodically after that, as well as destroy the session if it is invalid. Here is the complete SessionStart function.

static function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
{
	// Set the cookie name
	session_name($name . '_Session');

	// Set SSL level
	$https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

	// Set session cookie options
	session_set_cookie_params($limit, $path, $domain, $https, true);
	session_start();

	// Make sure the session hasn't expired, and destroy it if it has
	if(self::validateSession())
	{
		// Check to see if the session is new or a hijacking attempt
		if(!self::preventHijacking())
		{
			// Reset session data and regenerate id
			$_SESSION = array();
			$_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
			$_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
			self::regenerateSession();

		// Give a 5% chance of the session id changing on any request
		}elseif(rand(1, 100) <= 5){
			self::regenerateSession();
		}
	}else{
		$_SESSION = array();
		session_destroy();
		session_start();
	}
}

Summary

At times it amazes me how complex something as simple as an ID- what is essentially just a string of random characters- can turn out to be. While you can certainly use this class for all of your own projects here is what you need to remember when building your own session manager.

Session IDs are attacked by guessing, capturing or setting the id. You can protect against this in your own applications by …

Here is the complete Session.class.php file for your reference.

Exit mobile version