PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Wednesday, December 19, 2012

Avoid two users trying to access with same session cookie data?

How would you avoid two users trying to access with the same session cookie data?

This is same as asking how would you avoid Session Fixation or Session Hijacking.



Solution:
  1. Regenerate the Session Id on each user request i.e.  call session_regenerate_id() at the beginning of each request.
  2. Fix the active time of a session. If a user is logged in from time more than time out value, automatically log off the User.
  3. Check the 'browser fingerprint' on each request. This is a hash, stored in a $_SESSION variable, comprising some combination of the user-agent header, client IP address, a salt value, and/or other information. 
  4. Check referrer: this does not work for all systems, but if we know that users of this site must be coming from some known domain we can discard sessions tied to users from elsewhere.







Below is a sample code to implement this.


$timeout = 3 * 60; // 3 minutes
$fingerprint = md5('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT']);
session_start();
if ( (isset($_SESSION['last_active']) && (time() > ($_SESSION['last_active']+$timeout))) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint) || isset($_GET['logout']) ) 
{ 
         do_logout();
}
session_regenerate_id();
$_SESSION['last_active'] = time();
$_SESSION['fingerprint'] = $fingerprint;




No comments:

Post a Comment