I have always wondered how to build secure sessions. I read some interesting things today and thought I'd put together a little function so as to avoid these issues:
- session fixation
- CSRF attacks
Tell me what you think, as I'm very unsure whether this will secure scripts or not:
class Session { public function start($domain) { session_start(); // In order to avoid CSRF, we check for the REFERER. If the request doesn't come from our own site, then we delete the session to logout the user // and avoid any unwanted action the user would have performed while logged in. // Note that if $_GET['logout'] is set in the URL, the user will also be logged out. if (strpos($_SERVER['HTTP_REFERER'], 'http://' . $domain) !== 0 || isset($_GET['logout']) || // It is unlikely that a user will use the same session with two different IPs or browsers. // This would a sign that someone is attempting session fixation, session theft or something similar // So we destroy the session and regenerate a new one so as to avoid session fixation. $_SERVER['REMOTE_ADDR'] !== $_SESSION['PREV_REMOTEADDR'] || $_SERVER['HTTP_USER_AGENT'] !== $_SESSION['PREV_USERAGENT']) { session_destroy(); session_regenerate_id(); } // We set the first browser and IP used by the user so as to perform the check explained just above if(!isset($_SESSION['PREV_USERAGENT'])) $_SESSION['PREV_USERAGENT'] = $_SERVER['HTTP_USER_AGENT']; if(!isset($_SESSION['PREV_REMOTEADDR'])) $_SESSION['PREV_REMOTEADDR'] = $_SERVER['REMOTE_ADDR']; if(!isset($_SESSION['token'])) $_SESSION['token'] = uniqid(md5(microtime()), true); // The token is a value that should be included in a hidden field for each form submitted through the site // in order to avoid CSRF attacks. if ($_POST['token'] !== $_SESSION['token']) { exit(); } } }Thanks, best regards,
CK