会话和cookie在PHP中的角色

时间:2011-11-14 15:05:02

标签: php security

我在php中设计角色的方式如下。当用户登录代码时,检查用户是否是主持人。

如果他是一个简单的用户,他会获得一个不需要https的cookie。除此以外, 如果他是主持人,我会分配一个这样的特殊会议:

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

     //generate pass for the database && session
    $pass=microtime().Moderator::generate_salt(30);
    //Insert pass
    Moderator::insert_moderator($pass);

    //Encrypt the pass and give it back to the users session ID
    $_SESSION["mod"]=$mod->encrypt_pass($pass);

上面的代码占用了主持人登录的登录时间,附加随机盐,并根据会话开始或结束时插入或更新主持人传递(在这种情况下,这是第一次,mod被分配了他登录时会话。)

另请注意,这是我使用的加密和dycryption算法:

       public function encrypt_pass($session_id)
   {
       $session_id=strip_tags($session_id);
       $session_id=trim($session_id);
       //inititialization vector is being created.- a seed for random encryption and decryption
       srand((double)microtime()*10000);
       //opens an ecryption algorithm for use.
       $this->td=mcrypt_module_open(MCRYPT_RIJNDAEL_256,'',MCRYPT_MODE_CFB,'');
       //creates an IV for out encryption. Two parameters: size of IV ti create and method used to create IV
       $this->iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_RAND);
       //get maximum size the algorithm will take.
       $this->ks=mcrypt_enc_get_key_size($this->td);
       //here teh key is created 
       $this->keys=substr(sha1(Moderator::generate_salt()),0, $this->ks);
       //initialize the algorithm engine using , IV, and key we selected
        mcrypt_generic_init($this->td,$this->keys,$this->iv);
       //Two parameters, the algorithm resource and the data we actually want to encrypt. returns an incrypted value
       $this->ciphertext=mcrypt_generic($this->td,$session_id);
       //clean up!! parameter is -- algorithm resource
       mcrypt_generic_deinit($this->td);
       //end clean up!!
       mcrypt_module_close($this->td);
       //Goes to the moderators session $_SESSION['$ciphertext'] 
       return $this->ciphertext;
   }

   public function decrypt_pass($session_id)
   {
       $session_id=strip_tags($session_id);
       $session_id=trim($session_id);

       mcrypt_generic_init($this->td, $this->keys,$this->iv);
       $plaintext=mdecrypt_generic($this->td,$session_id);
       mcrypt_generic_deinit($this->td);
       mcrypt_module_close($this->td);
   }

这可以防止我进行会话固定/劫持,对于黑客来说,抓住主持人会话ID会非常困难,即使他这么做,主持人再次发出请求时,密码也会重置,如果他关闭会话结束的浏览器。这使得黑客有一个很小的时间框架来获取密码并假装成为主持人。

问题:这是否足以应对会话劫持/录制或我是否应该添加其他预防措施?

请注意,我使用此算法的方式确实会减慢请求和响应。但主持人数量有限,不超过10人。

代码会根据主持人的每个请求自行更新

1 个答案:

答案 0 :(得分:0)

您的算法的弱点在于您无论如何都无法识别特定用户。你只是把时间和一些随意的盐放在一起。 为防止会话/ cookie劫持,您需要尽可能多地将加密字符串放入加密字符串中。例如,客户端的操作系统,用户代理,浏览器版本,IP,转发IP等等。在这种情况下,您将解密已发送给用户的字符串,假设只有您可以对其进行解密,因为只有您拥有AES密钥,并且将验证您已插入到加密字符串中的所有参数。甚至一个因素验证失败意味着可能有人劫持了会话,你需要销毁它。

我建议你在http://www.hardened-php.net/suhosin/看看Suhosin。这是一个PHP插件,可以为您完成上述所有操作。它透明,重量轻。 当使用Suhosin时,请注意通过javascript设置cookie,因为javascript设置了未加密的cookie,虽然服务器无法读取它。

相关问题