PageRenderTime 71ms CodeModel.GetById 39ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/base/CSecurityManager.php

https://bitbucket.org/syed_webt/yii_syed
PHP | 328 lines | 162 code | 23 blank | 143 comment | 15 complexity | 4d47d451d57b941bae330fb5f3d4b7b5 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, BSD-2-Clause
  1. <?php
  2. /**
  3. * This file contains classes implementing security manager feature.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CSecurityManager provides private keys, hashing and encryption functions.
  12. *
  13. * CSecurityManager is used by Yii components and applications for security-related purpose.
  14. * For example, it is used in cookie validation feature to prevent cookie data
  15. * from being tampered.
  16. *
  17. * CSecurityManager is mainly used to protect data from being tampered and viewed.
  18. * It can generate HMAC and encrypt the data. The private key used to generate HMAC
  19. * is set by {@link setValidationKey ValidationKey}. The key used to encrypt data is
  20. * specified by {@link setEncryptionKey EncryptionKey}. If the above keys are not
  21. * explicitly set, random keys will be generated and used.
  22. *
  23. * To protected data with HMAC, call {@link hashData()}; and to check if the data
  24. * is tampered, call {@link validateData()}, which will return the real data if
  25. * it is not tampered. The algorithm used to generated HMAC is specified by
  26. * {@link validation}.
  27. *
  28. * To encrypt and decrypt data, call {@link encrypt()} and {@link decrypt()}
  29. * respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt
  30. * extension must be installed and loaded.
  31. *
  32. * CSecurityManager is a core application component that can be accessed via
  33. * {@link CApplication::getSecurityManager()}.
  34. *
  35. * @property string $validationKey The private key used to generate HMAC.
  36. * If the key is not explicitly set, a random one is generated and returned.
  37. * @property string $encryptionKey The private key used to encrypt/decrypt data.
  38. * If the key is not explicitly set, a random one is generated and returned.
  39. * @property string $validation
  40. *
  41. * @author Qiang Xue <qiang.xue@gmail.com>
  42. * @package system.base
  43. * @since 1.0
  44. */
  45. class CSecurityManager extends CApplicationComponent
  46. {
  47. const STATE_VALIDATION_KEY='Yii.CSecurityManager.validationkey';
  48. const STATE_ENCRYPTION_KEY='Yii.CSecurityManager.encryptionkey';
  49. /**
  50. * @var string the name of the hashing algorithm to be used by {@link computeHMAC}.
  51. * See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
  52. * hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
  53. *
  54. * Defaults to 'sha1', meaning using SHA1 hash algorithm.
  55. * @since 1.1.3
  56. */
  57. public $hashAlgorithm='sha1';
  58. /**
  59. * @var mixed the name of the crypt algorithm to be used by {@link encrypt} and {@link decrypt}.
  60. * This will be passed as the first parameter to {@link http://php.net/manual/en/function.mcrypt-module-open.php mcrypt_module_open}.
  61. *
  62. * This property can also be configured as an array. In this case, the array elements will be passed in order
  63. * as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
  64. *
  65. * Defaults to 'des', meaning using DES crypt algorithm.
  66. * @since 1.1.3
  67. */
  68. public $cryptAlgorithm='des';
  69. private $_validationKey;
  70. private $_encryptionKey;
  71. private $_mbstring;
  72. public function init()
  73. {
  74. parent::init();
  75. $this->_mbstring=extension_loaded('mbstring');
  76. }
  77. /**
  78. * @return string a randomly generated private key
  79. */
  80. protected function generateRandomKey()
  81. {
  82. return sprintf('%08x%08x%08x%08x',mt_rand(),mt_rand(),mt_rand(),mt_rand());
  83. }
  84. /**
  85. * @return string the private key used to generate HMAC.
  86. * If the key is not explicitly set, a random one is generated and returned.
  87. */
  88. public function getValidationKey()
  89. {
  90. if($this->_validationKey!==null)
  91. return $this->_validationKey;
  92. else
  93. {
  94. if(($key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
  95. $this->setValidationKey($key);
  96. else
  97. {
  98. $key=$this->generateRandomKey();
  99. $this->setValidationKey($key);
  100. Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
  101. }
  102. return $this->_validationKey;
  103. }
  104. }
  105. /**
  106. * @param string $value the key used to generate HMAC
  107. * @throws CException if the key is empty
  108. */
  109. public function setValidationKey($value)
  110. {
  111. if(!empty($value))
  112. $this->_validationKey=$value;
  113. else
  114. throw new CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
  115. }
  116. /**
  117. * @return string the private key used to encrypt/decrypt data.
  118. * If the key is not explicitly set, a random one is generated and returned.
  119. */
  120. public function getEncryptionKey()
  121. {
  122. if($this->_encryptionKey!==null)
  123. return $this->_encryptionKey;
  124. else
  125. {
  126. if(($key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
  127. $this->setEncryptionKey($key);
  128. else
  129. {
  130. $key=$this->generateRandomKey();
  131. $this->setEncryptionKey($key);
  132. Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
  133. }
  134. return $this->_encryptionKey;
  135. }
  136. }
  137. /**
  138. * @param string $value the key used to encrypt/decrypt data.
  139. * @throws CException if the key is empty
  140. */
  141. public function setEncryptionKey($value)
  142. {
  143. if(!empty($value))
  144. $this->_encryptionKey=$value;
  145. else
  146. throw new CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
  147. }
  148. /**
  149. * This method has been deprecated since version 1.1.3.
  150. * Please use {@link hashAlgorithm} instead.
  151. * @return string
  152. */
  153. public function getValidation()
  154. {
  155. return $this->hashAlgorithm;
  156. }
  157. /**
  158. * This method has been deprecated since version 1.1.3.
  159. * Please use {@link hashAlgorithm} instead.
  160. * @param string $value -
  161. */
  162. public function setValidation($value)
  163. {
  164. $this->hashAlgorithm=$value;
  165. }
  166. /**
  167. * Encrypts data.
  168. * @param string $data data to be encrypted.
  169. * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
  170. * @return string the encrypted data
  171. * @throws CException if PHP Mcrypt extension is not loaded
  172. */
  173. public function encrypt($data,$key=null)
  174. {
  175. $module=$this->openCryptModule();
  176. $key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
  177. srand();
  178. $iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
  179. mcrypt_generic_init($module,$key,$iv);
  180. $encrypted=$iv.mcrypt_generic($module,$data);
  181. mcrypt_generic_deinit($module);
  182. mcrypt_module_close($module);
  183. return $encrypted;
  184. }
  185. /**
  186. * Decrypts data
  187. * @param string $data data to be decrypted.
  188. * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
  189. * @return string the decrypted data
  190. * @throws CException if PHP Mcrypt extension is not loaded
  191. */
  192. public function decrypt($data,$key=null)
  193. {
  194. $module=$this->openCryptModule();
  195. $key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
  196. $ivSize=mcrypt_enc_get_iv_size($module);
  197. $iv=$this->substr($data,0,$ivSize);
  198. mcrypt_generic_init($module,$key,$iv);
  199. $decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
  200. mcrypt_generic_deinit($module);
  201. mcrypt_module_close($module);
  202. return rtrim($decrypted,"\0");
  203. }
  204. /**
  205. * Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
  206. * @return resource the mycrypt module handle.
  207. * @since 1.1.3
  208. */
  209. protected function openCryptModule()
  210. {
  211. if(extension_loaded('mcrypt'))
  212. {
  213. if(is_array($this->cryptAlgorithm))
  214. $module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
  215. else
  216. $module=@mcrypt_module_open($this->cryptAlgorithm,'', MCRYPT_MODE_CBC,'');
  217. if($module===false)
  218. throw new CException(Yii::t('yii','Failed to initialize the mcrypt module.'));
  219. return $module;
  220. }
  221. else
  222. throw new CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
  223. }
  224. /**
  225. * Prefixes data with an HMAC.
  226. * @param string $data data to be hashed.
  227. * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
  228. * @return string data prefixed with HMAC
  229. */
  230. public function hashData($data,$key=null)
  231. {
  232. return $this->computeHMAC($data,$key).$data;
  233. }
  234. /**
  235. * Validates if data is tampered.
  236. * @param string $data data to be validated. The data must be previously
  237. * generated using {@link hashData()}.
  238. * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
  239. * @return string the real data with HMAC stripped off. False if the data
  240. * is tampered.
  241. */
  242. public function validateData($data,$key=null)
  243. {
  244. $len=$this->strlen($this->computeHMAC('test'));
  245. if($this->strlen($data)>=$len)
  246. {
  247. $hmac=$this->substr($data,0,$len);
  248. $data2=$this->substr($data,$len,$this->strlen($data));
  249. return $hmac===$this->computeHMAC($data2,$key)?$data2:false;
  250. }
  251. else
  252. return false;
  253. }
  254. /**
  255. * Computes the HMAC for the data with {@link getValidationKey ValidationKey}.
  256. * @param string $data data to be generated HMAC
  257. * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
  258. * @return string the HMAC for the data
  259. */
  260. protected function computeHMAC($data,$key=null)
  261. {
  262. if($key===null)
  263. $key=$this->getValidationKey();
  264. if(function_exists('hash_hmac'))
  265. return hash_hmac($this->hashAlgorithm, $data, $key);
  266. if(!strcasecmp($this->hashAlgorithm,'sha1'))
  267. {
  268. $pack='H40';
  269. $func='sha1';
  270. }
  271. else
  272. {
  273. $pack='H32';
  274. $func='md5';
  275. }
  276. if($this->strlen($key) > 64)
  277. $key=pack($pack, $func($key));
  278. if($this->strlen($key) < 64)
  279. $key=str_pad($key, 64, chr(0));
  280. $key=$this->substr($key,0,64);
  281. return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
  282. }
  283. /**
  284. * Returns the length of the given string.
  285. * If available uses the multibyte string function mb_strlen.
  286. * @param string $string the string being measured for length
  287. * @return integer the length of the string
  288. */
  289. private function strlen($string)
  290. {
  291. return $this->_mbstring ? mb_strlen($string,'8bit') : strlen($string);
  292. }
  293. /**
  294. * Returns the portion of string specified by the start and length parameters.
  295. * If available uses the multibyte string function mb_substr
  296. * @param string $string the input string. Must be one character or longer.
  297. * @param integer $start the starting position
  298. * @param integer $length the desired portion length
  299. * @return string the extracted part of string, or FALSE on failure or an empty string.
  300. */
  301. private function substr($string,$start,$length)
  302. {
  303. return $this->_mbstring ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
  304. }
  305. }