There are three common methods used to obtain a valid session identifier:
-
Prediction It refers to guessing a valid session identifier. The session identifier is extremely random, and this is unlikely to be the weakest point in your implementation.
-
Capture Capturing a valid session identifier is the most common type of session attack, and there are numerous approaches like GET, cookies.
-
Fixation Fixation is the simplest method of obtaining a valid session identifier. While it's not very difficult to defend against, if your session mechanism consists of nothing more than
session_start()
, you are vulnerable.
Session hijacking refers to all attacks that attempt to gain access to another user's session. Like session fixation, if your session mechanism consists of session_start()
then your are vulnerable.
Strong Session ID
Standard session IDs generated by PHP are not random. They are predictable under certain circumstances making it vulnerable resulting session hijacking.
Generate random data for SID using following configurations.
session.entropy_file = /dev/urandom //specifies the random number generator to read from
session.entropy_lenght = 32 //the number of bytes to read
Also its good idea to change the hash algorith. By deafult, PHP uses the obsolete MD5.
session.hash_function = sha512
Use Cookies
Exchanging session ID through the URL is a major security risk resulting session fixation abuse. Following there configuration can help to prevent such abuse.
session.use_only_cookies = 1 // tells PHP to set a cookie with a session ID when session started
session.use_cookies = 1 // tells PHP to only accept session IDs comming from a cookie, not from URL
session.use_trans_sid = 0 // prevents PHP from automatically inserting the session ID into links.
Secure Session Cookies
To protect session ID, set the following configurations-
session.cookie_httponly = 1 // makes sure the session cookie is not accessible via JavaScript and prevent xss
session.cookie_secure = 1 // (HTTPS only) makes sure the cookie will only be transmitted over a HTTPS connection.
Regenerating the Session ID
It is a good practice to generate new session ID once user logs in which will help to prevent session fixation attacks.
session_regenerate_id(true) // the argument tells PHP to delete the old session.
Limit Session Lifetime
Though session cookies are destroyed when the users cloes the browser, it's good approach to set limit on the lifetime of the session.
Save session created time
$_SESSION['creation_time'] = time();
Check if session has expired
$max_lifetime_seconds = 3600;
$session_lifetime_seconds = time() - $_SESSION['creation_time'];
if ($session_lifetime_seconds > $max_lifetime_seconds) {
// terminate session
}
Create php function to manage session ID. Click here for example.