PageRenderTime 53ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/base/CSecurityManager.php

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