PHP session var enough for user auth?

前端 未结 5 954
心在旅途
心在旅途 2021-02-06 15:21

Scenario:

  • After a user has logged in, a session variable is set confirming their login.
  • At the top of every page, login session variable is confirmed vali
5条回答
  •  误落风尘
    2021-02-06 15:51

    It is enough to store just user login (or user id) in the session.

    To prevent session fixation/hijacking everything you need is just to implement simple algorythm (pseudocode):

    if (!isset($_SESSION['hash']) {
        $_SESSION['hash'] = md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua');
    } else if ($_SESSION['hash'] != md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua')) {
        session_regenerate_id();
        $_SESSION = array();
        $_SESSION['hash'] = md5(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua');
    }
    

    You could move the hash calculation into some function to prevent of duplication, i've just shown a sketch of possible protection.

    This is how I implemented this kind of protection in my kohana session class:

    abstract class Session extends Kohana_Session
    {
        public function read($id = null)
        {
            parent::read($id);
    
            $hash = $this->calculateHash();
            $sessionHash = $this->get('session_fixation');
    
            if (!$sessionHash) {
                $this->set('session_fixation', $hash);
            } elseif ($sessionHash != $hash) {
                $this->regenerate();
                $_SESSION = array();
                $this->set('session_fixation', $hash);
            }
        }
    
        private function calculateHash()
        {
            $ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
            $ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no ua';
            $charset = !empty($_SERVER['HTTP_ACCEPT_CHARSET']) ? $_SERVER['HTTP_ACCEPT_CHARSET'] : 'no charset';
            $ip = substr($ip, 0, strrpos($ip, '.') - 1);
            return md5($ua . $ip . $charset);
        }
    }
    

提交回复
热议问题