PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/demo/yii/base/CSecurityManager.php

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