Make the authentication more securely

You are viewing revision #4 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#3)

Suppose a hacker has an account of your website He could set the PHPSESSID to empty After of that He login in your system The PHPSESSID remains blank and user has already logged with this session

If you use CDbHttpSession go to YiiSession table of your database and you will see a record with empty id (This is not very secured or robust).

Session id must be a random string using session_regenerate_id

So what is the problem and how can we fix it ?

using CWebUser on login action calls the login method that calls changeIdentity method. The changeIdentity calls the Yii::app()->getSession()->regenerateID(true)

In the case that you use CDbHttpSession the regenerateID method contains the follow code

public function regenerateID($deleteOldSession=false)
	{
		$oldID=session_id();
		// if no session is started, there is nothing to regenerate
		if(empty($oldID))
			return;
        ....
        

That check if session is started. But in our case, session_id returns empty string because user-hacker set the PHPSESSID to empty (although the session has been started normaly)!

So, How to fix that ?

In your protected/components create the ExCWebUser.php (or modify your own) with the below code

class ExCWebUser extends CWebUser {  

    protected function changeIdentity($id,$name,$states)
	{
        //force to regenerate the session id either exists or not or is empty!
		session_regenerate_id(true); 
		parent::changeIdentity($id,$name,$states);
	}
}

In your protected/config/main.php modify the 'user' (may session too) settings like that

'session' => array(
            'class' => 'CDbHttpSession',
            'connectionID' => 'db',
            'timeout' => 86400, //24 hours
        ),

 'user' => array(
            'class'=>'ExCWebUser', //use our WebUser class
            // enable cookie-based authentication
            'allowAutoLogin' => true,
        ),

Now if PHPSESSID is empty (or anything valid old session id) the new authentication will be created with new valid and secured session id.