packetcode logo
Preventing Session Hijacking in PHP

Preventing Session Hijacking in PHP

12192 views 2 years ago Tutorials PHP

One of the most common web security threat is session hijacking. Here the attacker steals the cookie used to authenticate the user from remote server and creates a false identity to take over the user session. As the hacked session appears valid, it is very hard to detect the attack, so proper pre-emptive steps should be take keeps the sessions safe.

What is the need for sessions?

When internet was born, HTTP communications were designed to be stateless; that is, a connection between two entities exists only for the brief period of time required for a request to be sent to the server, and the resulting response passed back to the client. Once this transfer has been completed, the two entities are no more aware of each other than they had been before the original connection was established. The problem with this system is that, as the web began to be used for transactions and far beyond those, it needs to hold some data across pages.

Sessions were developed as a way to resolve this disconnect. A session is a package of information relating to an ongoing transaction. This package is typically stored on the server as a temporary file and frequently used across pages keeping the data persistent. Sessions give lot of power to developers to enhance the web capabilities.

Threats of sessions

Along with the power of sessions comes an almost equally powerful threat of abuse. There are two general ways in which sessions can be abused. The first is session hijacking, and the other is session fixation.

Session Hijacking

Because the messages being passed back and forth while a session is in effect contain a key that provides access to stored information about a user (like, conceivably, authentication status and even credit card number), anyone who intercepts the messages can use that key to impersonate the legitimate user, in effect hijacking that user’s identity. So empowered, the abuser can do anything the legitimate user could do. Here are few methods which hackers follow to hijack the session

Network Eavesdropping - Here the attacker reads all the messages passing through the public networks and then they filter the data which contain session id or login details.
Unwitting Exposure - PHP’s transparent session ID feature, which appends the current session ID to all relative URIs in the response (for browsers that don’t have cookies enabled), make it easy for hacker to read the session id and associated data.
Forwarding, Proxies, and Phishing - Here the hacker tricks the user that he is connecting to secure server but in fact to a false resource and grabs the user entered data.
Reverse Proxies - In a reverse proxy attack, an abuser modifies the content of a request in transit, keeping the session cookie intact in each direction.

Session Fixation

Session fixation is in a sense the opposite of session hijacking; instead of trying to take over an unknown valid session, it tries to force the creation of a known valid session. This technique again takes advantage of the special vulnerability of storing the session ID in a $_GET variable.

Preventing Session Abuse

There are a variety of recommendations for preventing session abuse, ranging from the complex but absolutely effective, to the easy but only mildly effective.

Use Secure Sockets Layer

The primary recommendation for preventing session abuse is this: if a connection is worth protecting with a password, then it is worth protecting with SSL or TLS.

SSL encrypts the value of the session cookie as it passes back and forth from client to server, SSL keeps the session ID out of the hands of anyone listening in at any network hop between client and server and back again. By positively authenticating the server with a trusted signature, SSL can prevent a malicious proxy from getting away with identity fraud. Even if the proxy were to submit its own self-signed and fraudulent certificate, the trust mechanism of the user’s browser should pop up a notice that that certificate has not been recognized, warning the user to abort the transaction.

SSL becomes overkill for small websites, especially for websites that seem not to deal with extremely valuable data.

Use Cookies

Always use the following ini_set() directives at the start of your scripts, in order to override any global settings in php.ini:

ini_set( 'session.use_only_cookies', TRUE );				
ini_set( 'session.use_trans_sid', FALSE );

The session.use_only_cookies setting forces PHP to manage the session ID with a cookie only, so that your script never considers $_GET['PHPSESSID'] to be valid. This automatically overrides the use of transparent session IDs. But we also explicitly turn off session.use_trans_sid, to avoid leaking the session ID in all URIs returned in the first response, before PHP discovers whether the browser is capable of using a session cookie or not.This technique protects users from accidentally revealing their session IDs, but it is still subject to DNS and proxy attacks.

Use Session Timeouts

The lifetime of a session cookie defaults to 0, that is, to the period when the browser is open. Its advisable to set the session lifetime to a small microtime like including an instruction like ini_set( 'session.cookie_lifetime', 1200 ) in your scripts. This sets the lifetime of a session cookie to 1,200 seconds, or 20 minutes (you may also set it globally in php.ini). This setting forces the session cookie to expire after 20 minutes, at which point that session ID becomes invalid. When a session times out in a relatively short time like 20 minutes, a human attacker may have a hard time hijacking the session if all she can work from are server or proxy logs.

Conservatively controlling session lifetime protects a session from attacks that are unlikely to occur within its life span (those occasioned, for example, by a human attacker’s reading of network logs). However, if a user takes a long time to complete a form, the session (and the already-entered form data) are likely to be lost. So you will need to decide whether this potential inconvenience to your users is worthwhile.

Use Session Regenerate ID

Whenever a user changes her status, either by logging out or by moving from a secure area to an insecure one, we should regenerate a new session ID so as to invalidate the previous one. The point isn’t to destroy the existing $_SESSION data, rather, the goal of generating a fresh session ID is to remove the possibility, however slight, that an attacker with knowledge of the low-security session might be able to perform high-security tasks. An example fragment from an HTTPS login script shows how to regenerate the session ID:

	// regenerate session on successful login
	if ( !empty( $_POST['password'] ) && $_POST['password'] === $password ) 		
	 // if authenticated, generate a new random session ID

	 // set session to authenticated
	  $_SESSION['auth'] = TRUE;

	 // redirect to make the new session ID live

	 header( 'Location: ' . $_SERVER['SCRIPT_NAME'] );
	// take some action

In this fragment of an entire login script, you compare the user’s password input against a preconfigured password. If this is successful, you execute the session_regenerate_id() function, which generates a new session ID and sends it as a cookie to the browser. To make this happen immediately, you reload the script into the browser before the script takes any other actions.

Wrap up

Session hijacking is a serious threat, it has to handled by using a secure socket layer for advanced application which involve transactions or by using simple techniques like using cookies, session timeouts and regenerate id etc as explained above

im krishna Teja, im a computer science engineer by qualification, a physics teacher by profession and a programmer by interest. I'm an expert in building visually stunning web apps using javascript, ...