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

/framework/base/CSecurityManager.php

https://bitbucket.org/gencer/yii
PHP | 492 lines | 248 code | 40 blank | 204 comment | 39 complexity | aaf08b83570ee61ab7e4ee0d83dcf8a9 MD5 | raw file
Possible License(s): 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 2008-2013 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. * @deprecated in favor of {@link generateRandomString()} since 1.1.14. Never use this method.
  80. */
  81. protected function generateRandomKey()
  82. {
  83. return $this->generateRandomString(32);
  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. * @throws CException in case random string cannot be generated.
  89. */
  90. public function getValidationKey()
  91. {
  92. if($this->_validationKey!==null)
  93. return $this->_validationKey;
  94. else
  95. {
  96. if(($key=Yii::app()->getGlobalState(self::STATE_VALIDATION_KEY))!==null)
  97. $this->setValidationKey($key);
  98. else
  99. {
  100. if(($key=$this->generateRandomString(32,true))===false)
  101. if(($key=$this->generateRandomString(32,false))===false)
  102. throw new CException(Yii::t('yii',
  103. 'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
  104. $this->setValidationKey($key);
  105. Yii::app()->setGlobalState(self::STATE_VALIDATION_KEY,$key);
  106. }
  107. return $this->_validationKey;
  108. }
  109. }
  110. /**
  111. * @param string $value the key used to generate HMAC
  112. * @throws CException if the key is empty
  113. */
  114. public function setValidationKey($value)
  115. {
  116. if(!empty($value))
  117. $this->_validationKey=$value;
  118. else
  119. throw new CException(Yii::t('yii','CSecurityManager.validationKey cannot be empty.'));
  120. }
  121. /**
  122. * @return string the private key used to encrypt/decrypt data.
  123. * If the key is not explicitly set, a random one is generated and returned.
  124. * @throws CException in case random string cannot be generated.
  125. */
  126. public function getEncryptionKey()
  127. {
  128. if($this->_encryptionKey!==null)
  129. return $this->_encryptionKey;
  130. else
  131. {
  132. if(($key=Yii::app()->getGlobalState(self::STATE_ENCRYPTION_KEY))!==null)
  133. $this->setEncryptionKey($key);
  134. else
  135. {
  136. if(($key=$this->generateRandomString(32,true))===false)
  137. if(($key=$this->generateRandomString(32,false))===false)
  138. throw new CException(Yii::t('yii',
  139. 'CSecurityManager::generateRandomString() cannot generate random string in the current environment.'));
  140. $this->setEncryptionKey($key);
  141. Yii::app()->setGlobalState(self::STATE_ENCRYPTION_KEY,$key);
  142. }
  143. return $this->_encryptionKey;
  144. }
  145. }
  146. /**
  147. * @param string $value the key used to encrypt/decrypt data.
  148. * @throws CException if the key is empty
  149. */
  150. public function setEncryptionKey($value)
  151. {
  152. if(!empty($value))
  153. $this->_encryptionKey=$value;
  154. else
  155. throw new CException(Yii::t('yii','CSecurityManager.encryptionKey cannot be empty.'));
  156. }
  157. /**
  158. * This method has been deprecated since version 1.1.3.
  159. * Please use {@link hashAlgorithm} instead.
  160. * @return string -
  161. * @deprecated
  162. */
  163. public function getValidation()
  164. {
  165. return $this->hashAlgorithm;
  166. }
  167. /**
  168. * This method has been deprecated since version 1.1.3.
  169. * Please use {@link hashAlgorithm} instead.
  170. * @param string $value -
  171. * @deprecated
  172. */
  173. public function setValidation($value)
  174. {
  175. $this->hashAlgorithm=$value;
  176. }
  177. /**
  178. * Encrypts data.
  179. * @param string $data data to be encrypted.
  180. * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
  181. * @return string the encrypted data
  182. * @throws CException if PHP Mcrypt extension is not loaded
  183. */
  184. public function encrypt($data,$key=null)
  185. {
  186. $module=$this->openCryptModule();
  187. $key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
  188. srand();
  189. $iv=mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
  190. mcrypt_generic_init($module,$key,$iv);
  191. $encrypted=$iv.mcrypt_generic($module,$data);
  192. mcrypt_generic_deinit($module);
  193. mcrypt_module_close($module);
  194. return $encrypted;
  195. }
  196. /**
  197. * Decrypts data
  198. * @param string $data data to be decrypted.
  199. * @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
  200. * @return string the decrypted data
  201. * @throws CException if PHP Mcrypt extension is not loaded
  202. */
  203. public function decrypt($data,$key=null)
  204. {
  205. $module=$this->openCryptModule();
  206. $key=$this->substr($key===null ? md5($this->getEncryptionKey()) : $key,0,mcrypt_enc_get_key_size($module));
  207. $ivSize=mcrypt_enc_get_iv_size($module);
  208. $iv=$this->substr($data,0,$ivSize);
  209. mcrypt_generic_init($module,$key,$iv);
  210. $decrypted=mdecrypt_generic($module,$this->substr($data,$ivSize,$this->strlen($data)));
  211. mcrypt_generic_deinit($module);
  212. mcrypt_module_close($module);
  213. return rtrim($decrypted,"\0");
  214. }
  215. /**
  216. * Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
  217. * @throws CException if failed to initialize the mcrypt module or PHP mcrypt extension
  218. * @return resource the mycrypt module handle.
  219. * @since 1.1.3
  220. */
  221. protected function openCryptModule()
  222. {
  223. if(extension_loaded('mcrypt'))
  224. {
  225. if(is_array($this->cryptAlgorithm))
  226. $module=@call_user_func_array('mcrypt_module_open',$this->cryptAlgorithm);
  227. else
  228. $module=@mcrypt_module_open($this->cryptAlgorithm,'', MCRYPT_MODE_CBC,'');
  229. if($module===false)
  230. throw new CException(Yii::t('yii','Failed to initialize the mcrypt module.'));
  231. return $module;
  232. }
  233. else
  234. throw new CException(Yii::t('yii','CSecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
  235. }
  236. /**
  237. * Prefixes data with an HMAC.
  238. * @param string $data data to be hashed.
  239. * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
  240. * @return string data prefixed with HMAC
  241. */
  242. public function hashData($data,$key=null)
  243. {
  244. return $this->computeHMAC($data,$key).$data;
  245. }
  246. /**
  247. * Validates if data is tampered.
  248. * @param string $data data to be validated. The data must be previously
  249. * generated using {@link hashData()}.
  250. * @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
  251. * @return string the real data with HMAC stripped off. False if the data
  252. * is tampered.
  253. */
  254. public function validateData($data,$key=null)
  255. {
  256. $len=$this->strlen($this->computeHMAC('test'));
  257. if($this->strlen($data)>=$len)
  258. {
  259. $hmac=$this->substr($data,0,$len);
  260. $data2=$this->substr($data,$len,$this->strlen($data));
  261. return $hmac===$this->computeHMAC($data2,$key)?$data2:false;
  262. }
  263. else
  264. return false;
  265. }
  266. /**
  267. * Computes the HMAC for the data with {@link getValidationKey validationKey}. This method has been made public
  268. * since 1.1.14.
  269. * @param string $data data to be generated HMAC.
  270. * @param string|null $key the private key to be used for generating HMAC. Defaults to null, meaning using
  271. * {@link validationKey} value.
  272. * @param string|null $hashAlgorithm the name of the hashing algorithm to be used.
  273. * See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
  274. * hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
  275. * Defaults to null, meaning using {@link hashAlgorithm} value.
  276. * @return string the HMAC for the data.
  277. * @throws CException on unsupported hash algorithm given.
  278. */
  279. public function computeHMAC($data,$key=null,$hashAlgorithm=null)
  280. {
  281. if($key===null)
  282. $key=$this->getValidationKey();
  283. if($hashAlgorithm===null)
  284. $hashAlgorithm=$this->hashAlgorithm;
  285. if(function_exists('hash_hmac'))
  286. return hash_hmac($hashAlgorithm,$data,$key);
  287. if(0===strcasecmp($hashAlgorithm,'sha1'))
  288. {
  289. $pack='H40';
  290. $func='sha1';
  291. }
  292. elseif(0===strcasecmp($hashAlgorithm,'md5'))
  293. {
  294. $pack='H32';
  295. $func='md5';
  296. }
  297. else
  298. {
  299. throw new CException(Yii::t('yii','Only SHA1 and MD5 hashing algorithms are supported when using PHP 5.1.1 or below.'));
  300. }
  301. if($this->strlen($key)>64)
  302. $key=pack($pack,$func($key));
  303. if($this->strlen($key)<64)
  304. $key=str_pad($key,64,chr(0));
  305. $key=$this->substr($key,0,64);
  306. return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
  307. }
  308. /**
  309. * Generate a random ASCII string. Generates only [0-9a-zA-z_~] characters which are all
  310. * transparent in raw URL encoding.
  311. * @param integer $length length of the generated string in characters.
  312. * @param boolean $cryptographicallyStrong set this to require cryptographically strong randomness.
  313. * @return string|boolean random string or false in case it cannot be generated.
  314. * @since 1.1.14
  315. */
  316. public function generateRandomString($length,$cryptographicallyStrong=true)
  317. {
  318. if(($randomBytes=$this->generateRandomBytes($length+2,$cryptographicallyStrong))!==false)
  319. return strtr($this->substr(base64_encode($randomBytes),0,$length),array('+'=>'_','/'=>'~'));
  320. return false;
  321. }
  322. /**
  323. * Generates a string of random bytes.
  324. * @param integer $length number of random bytes to be generated.
  325. * @param boolean $cryptographicallyStrong whether to fail if a cryptographically strong
  326. * result cannot be generated. The method attempts to read from a cryptographically strong
  327. * pseudorandom number generator (CS-PRNG), see
  328. * {@link https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Requirements Wikipedia}.
  329. * However, in some runtime environments, PHP has no access to a CS-PRNG, in which case
  330. * the method returns false if $cryptographicallyStrong is true. When $cryptographicallyStrong is false,
  331. * the method always returns a pseudorandom result but may fall back to using {@link generatePseudoRandomBlock}.
  332. * This method does not guarantee that entropy, from sources external to the CS-PRNG, was mixed into
  333. * the CS-PRNG state between each successive call. The caller can therefore expect non-blocking
  334. * behavior, unlike, for example, reading from /dev/random on Linux, see
  335. * {@link http://eprint.iacr.org/2006/086.pdf Gutterman et al 2006}.
  336. * @return boolean|string generated random binary string or false on failure.
  337. * @since 1.1.14
  338. */
  339. public function generateRandomBytes($length,$cryptographicallyStrong=true)
  340. {
  341. $bytes='';
  342. if(function_exists('openssl_random_pseudo_bytes'))
  343. {
  344. $bytes=openssl_random_pseudo_bytes($length,$strong);
  345. if($this->strlen($bytes)>=$length && ($strong || !$cryptographicallyStrong))
  346. return $this->substr($bytes,0,$length);
  347. }
  348. if(function_exists('mcrypt_create_iv') &&
  349. ($bytes=mcrypt_create_iv($length, MCRYPT_DEV_URANDOM))!==false &&
  350. $this->strlen($bytes)>=$length)
  351. {
  352. return $this->substr($bytes,0,$length);
  353. }
  354. if(($file=@fopen('/dev/urandom','rb'))!==false &&
  355. ($bytes=@fread($file,$length))!==false &&
  356. (fclose($file) || true) &&
  357. $this->strlen($bytes)>=$length)
  358. {
  359. return $this->substr($bytes,0,$length);
  360. }
  361. $i=0;
  362. while($this->strlen($bytes)<$length &&
  363. ($byte=$this->generateSessionRandomBlock())!==false &&
  364. ++$i<3)
  365. {
  366. $bytes.=$byte;
  367. }
  368. if($this->strlen($bytes)>=$length)
  369. return $this->substr($bytes,0,$length);
  370. if ($cryptographicallyStrong)
  371. return false;
  372. while($this->strlen($bytes)<$length)
  373. $bytes.=$this->generatePseudoRandomBlock();
  374. return $this->substr($bytes,0,$length);
  375. }
  376. /**
  377. * Generate a pseudo random block of data using several sources. On some systems this may be a bit
  378. * better than PHP's {@link mt_rand} built-in function, which is not really random.
  379. * @return string of 64 pseudo random bytes.
  380. * @since 1.1.14
  381. */
  382. public function generatePseudoRandomBlock()
  383. {
  384. $bytes='';
  385. if (function_exists('openssl_random_pseudo_bytes')
  386. && ($bytes=openssl_random_pseudo_bytes(512))!==false
  387. && $this->strlen($bytes)>=512)
  388. {
  389. return $this->substr($bytes,0,512);
  390. }
  391. for($i=0;$i<32;++$i)
  392. $bytes.=pack('S',mt_rand(0,0xffff));
  393. // On UNIX and UNIX-like operating systems the numerical values in `ps`, `uptime` and `iostat`
  394. // ought to be fairly unpredictable. Gather the non-zero digits from those.
  395. foreach(array('ps','uptime','iostat') as $command) {
  396. @exec($command,$commandResult,$retVal);
  397. if(is_array($commandResult) && !empty($commandResult) && $retVal==0)
  398. $bytes.=preg_replace('/[^1-9]/','',implode('',$commandResult));
  399. }
  400. // Gather the current time's microsecond part. Note: this is only a source of entropy on
  401. // the first call! If multiple calls are made, the entropy is only as much as the
  402. // randomness in the time between calls.
  403. $bytes.=$this->substr(microtime(),2,6);
  404. // Concatenate everything gathered, mix it with sha512. hash() is part of PHP core and
  405. // enabled by default but it can be disabled at compile time but we ignore that possibility here.
  406. return hash('sha512',$bytes,true);
  407. }
  408. /**
  409. * Get random bytes from the system entropy source via PHP session manager.
  410. * @return boolean|string 20-byte random binary string or false on error.
  411. * @since 1.1.14
  412. */
  413. public function generateSessionRandomBlock()
  414. {
  415. ini_set('session.entropy_length',20);
  416. if(ini_get('session.entropy_length')!=20)
  417. return false;
  418. // These calls are (supposed to be, according to PHP manual) safe even if
  419. // there is already an active session for the calling script.
  420. @session_start();
  421. @session_regenerate_id();
  422. $bytes=session_id();
  423. if(!$bytes)
  424. return false;
  425. // $bytes has 20 bytes of entropy but the session manager converts the binary
  426. // random bytes into something readable. We have to convert that back.
  427. // SHA-1 should do it without losing entropy.
  428. return sha1($bytes,true);
  429. }
  430. /**
  431. * Returns the length of the given string.
  432. * If available uses the multibyte string function mb_strlen.
  433. * @param string $string the string being measured for length
  434. * @return integer the length of the string
  435. */
  436. private function strlen($string)
  437. {
  438. return $this->_mbstring ? mb_strlen($string,'8bit') : strlen($string);
  439. }
  440. /**
  441. * Returns the portion of string specified by the start and length parameters.
  442. * If available uses the multibyte string function mb_substr
  443. * @param string $string the input string. Must be one character or longer.
  444. * @param integer $start the starting position
  445. * @param integer $length the desired portion length
  446. * @return string the extracted part of string, or FALSE on failure or an empty string.
  447. */
  448. private function substr($string,$start,$length)
  449. {
  450. return $this->_mbstring ? mb_substr($string,$start,$length,'8bit') : substr($string,$start,$length);
  451. }
  452. }