How to implement a secure session management system in PHP (and generally)?

Developers, especially unexperienced PHP developers, have a tendency to not care much care about security-related issues. This is true for the problem of secure sessions, too - and the reason why attackers of a certain website or service can easily hijack sessions to get access to data, which they should not have access to. Because HTTP is a stateless protocol, sessions are required to identify a certain client on multiple requests. In PHP this identification is done via "session IDs", which are exchanged by the client and the webserver on each request (the session ID may be stored as a Cookie, in the URL or hidden field). The server stores the session ID locally to identify a certain client if the session ID is available in a certain request. If an attacker is able to steal the session ID of a certain client, the server will "think", that the attacker is the client. As a result, the attacker will be able to do everything, the client is allowed to do. How do I implement a session management system in PHP (and generally), which is more secure and more protected against "session hijacking" attempts?
1 answer

Implementing secure a secure session management system: A solution approach (implemented in PHP)

The following four problems can be identifiyed when using native PHP sessions (and these can be partly solved):

Problem 1: The session ID is the only thing, which is being used to identify a client
Solution 1: Use additional information about your client, to improve chances, that the identifiyed client is honestly the correct one (e.g. Client IP Adresss (be aware of proxies), Client User Agent, ...)

Problem 2: The process of generating client IPs can be reproduced by an attacker
Solution 2: Use a secure mechanism to generate your session IDs, which is not reproducible

Problem 3: Sessions exist longer than they should (which makes attackes easier)
Solution 3: Instant destruction of session ID if the server suspects that there might be something going wrong

Problem 4: Sessions IDs may be stolen using malicious JavaScript
Solution 4: Use only session cookies and make your cookie HTTP-only

The following PHP is a solution approach to make a secure session management in PHP:

/*
* This file is for generating save sessions.
*/
final class Session {

/**
* Secure start of a session.
*
* @return type
*/
public static function startSession() {

session_name("unique_session_id_name");

// try to start the session
$ok = @session_start();

// no session existing, make a new session
if (!$ok) {
// replace the Session ID
self::session_regenerate_save_id();
// start session
session_start();
}

// make the session cookie secure: HTTPonly and if possible HTTPS
$force_ssl_cookie = false;

$currentCookieParams = session_get_cookie_params();
$sidvalue = session_id();
setcookie(
"sess-aphk-".APP_ID,//name
$sidvalue,//value
0,//expires at end of session
$currentCookieParams['path'],//path
$currentCookieParams['domain'],//domain
$force_ssl_cookie,
true
);

// If the session was already existing, we must have set the client ip
if (isset($_SESSION["client_ip"])) {

// If this client ip does not match the ip of the current client, this might be an attack --> destroy session
if (self::getSessionClientIP() === $_SESSION["client_ip"] && self::getSessionClientAgent() === $_SESSION['client_agent']) {
if(self::checkStillActive()) {
return true;
}
} else {
self::destroy_session_absolute();
header('Location: '.$_SERVER['REQUEST_URI']);
die;
}

} else {
// if we have to create a new session, we do it in a secure, self-defined way
self::destroy_session_absolute();
self::session_regenerate_save_id();
session_start();
self::setSessionClientIP();
self::setSessionClientAgent();
$_SESSION['last_activity'] = time();
}
}

// creates a new, secure session id (MUST be called BEFORE session_start())
public static function session_regenerate_save_id() {
$hash_time = md5(microtime());
$hash_ip = md5($_SERVER["REMOTE_ADDR"]);
$hash_space = sha1(disk_free_space(getcwd()));
$session_id = sha1($hash_time . $hash_ip . $hash_space);
session_id($session_id);
}

// sets the session IP of the current client
private static function setSessionClientIP() {

if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$_SESSION["client_ip"] = md5($_SERVER["HTTP_X_FORWARDED_FOR"]);
} else {
$_SESSION["client_ip"] = md5($_SERVER["REMOTE_ADDR"]);
}
}

// retrieves the client IP of the session owner
private static function getSessionClientIP() {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
return md5($_SERVER["HTTP_X_FORWARDED_FOR"]);
} else {
return md5($_SERVER["REMOTE_ADDR"]);
}
}

private static function setSessionClientAgent() {
$_SESSION['client_agent'] = md5($_SERVER['HTTP_USER_AGENT']);
}

private static function getSessionClientAgent() {
return md5($_SERVER['HTTP_USER_AGENT']);
}

// secure, instant session destruction
public static function destroy_session_absolute() {
session_name("sess-aphk-".APP_ID);
if(session_id()) {
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), "", time() - 42000, "/");
}
session_destroy();
}
}

// retrieve the current session id
public static function get_current_session_id() {
session_name("sess-aphk-".APP_ID);
return session_id();
}

public static function checkStillActive() {
// make sure that a user was not inactive for too long
if(intval($_SESSION['last_activity']) < time()-1200) { //have we expired?
self::destroy_session_absolute();
header('Location: '.$_SERVER['REQUEST_URI']);
die;
} else { //if we haven't expired:
$_SESSION['last_activity'] = time(); //this was the moment of last activity.
return true;
}
}
}