PHP Sessions and Data Persistence Preventing Session Hijacking - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Sessions and Data Persistence Preventing Session Hijacking - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, June 13, 2019

PHP Sessions and Data Persistence Preventing Session Hijacking

PHP Sessions and Data Persistence




Preventing Session Hijacking


Problem

You want make sure an attacker can’t access another user’s session.

Solution

Allow passing of session IDs via cookies only, and generate an additional session token that is passed via URLs. Only requests that contain a valid session ID and a valid session token may access the session:

         ini_set('session.use_only_cookies', true);
         session_start();

         $salt = 'YourSpecialValueHere';
         $tokenstr = strval(date('W')) . $salt;
         $token = md5($tokenstr);

         if (!isset($_REQUEST['token']) || $_REQUEST['token'] != $token) {
              // prompt for login
              exit;
         }

         $_SESSION['token'] = $token;
         output_add_rewrite_var('token', $token);

Discussion

This example creates an auto-shifting token by joining the current week number with a salt string of your choice. With this technique, tokens will be valid for a reasonable period of time without being fixed. The salt prevents someone from calculating their own MD5 hash of a date far in the future and using it to extend a session. Without knowing the particular salt you’ve chosen, someone can’t easily produce a valid token.

We then check for the token in the request, and if it’s not found, we prompt for a new login. If it is found, it needs to be added to generated links. output_add_re write_var() does this easily.

Note that this mechanism won’t defeat an attacker who can sniff all of the traffic between a user and your server (for example, on an unencrypted WiFi network). Running your site over SSL is the best way to prevent that kind of attack.


No comments:

Post a Comment

Post Top Ad