Security.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use yii\helpers\StringHelper;
  9. use Yii;
  10. /**
  11. * Security provides a set of methods to handle common security-related tasks.
  12. *
  13. * In particular, Security supports the following features:
  14. *
  15. * - Encryption/decryption: [[encryptByKey()]], [[decryptByKey()]], [[encryptByPassword()]] and [[decryptByPassword()]]
  16. * - Key derivation using standard algorithms: [[pbkdf2()]] and [[hkdf()]]
  17. * - Data tampering prevention: [[hashData()]] and [[validateData()]]
  18. * - Password validation: [[generatePasswordHash()]] and [[validatePassword()]]
  19. *
  20. * > Note: this class requires 'OpenSSL' PHP extension for random key/string generation on Windows and
  21. * for encryption/decryption on all platforms. For the highest security level PHP version >= 5.5.0 is recommended.
  22. *
  23. * For more details and usage information on Security, see the [guide article on security](guide:security-overview).
  24. *
  25. * @author Qiang Xue <qiang.xue@gmail.com>
  26. * @author Tom Worster <fsb@thefsb.org>
  27. * @author Klimov Paul <klimov.paul@gmail.com>
  28. * @since 2.0
  29. */
  30. class Security extends Component
  31. {
  32. /**
  33. * @var string The cipher to use for encryption and decryption.
  34. */
  35. public $cipher = 'AES-128-CBC';
  36. /**
  37. * @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher.
  38. *
  39. * In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()).
  40. * The value is an array of two integers, the first is the cipher's block size in bytes and the second is
  41. * the key size in bytes.
  42. *
  43. * > Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode.
  44. *
  45. * > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key
  46. * derivation salt.
  47. */
  48. public $allowedCiphers = [
  49. 'AES-128-CBC' => [16, 16],
  50. 'AES-192-CBC' => [16, 24],
  51. 'AES-256-CBC' => [16, 32],
  52. ];
  53. /**
  54. * @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
  55. * @see [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
  56. */
  57. public $kdfHash = 'sha256';
  58. /**
  59. * @var string Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
  60. * @see [hash_algos()](http://php.net/manual/en/function.hash-algos.php)
  61. */
  62. public $macHash = 'sha256';
  63. /**
  64. * @var string HKDF info value for derivation of message authentication key.
  65. * @see hkdf()
  66. */
  67. public $authKeyInfo = 'AuthorizationKey';
  68. /**
  69. * @var int derivation iterations count.
  70. * Set as high as possible to hinder dictionary password attacks.
  71. */
  72. public $derivationIterations = 100000;
  73. /**
  74. * @var string strategy, which should be used to generate password hash.
  75. * Available strategies:
  76. * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
  77. * This option is recommended, but it requires PHP version >= 5.5.0
  78. * - 'crypt' - use PHP `crypt()` function.
  79. * @deprecated since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
  80. * uses `password_hash()` when available or `crypt()` when not.
  81. */
  82. public $passwordHashStrategy;
  83. /**
  84. * @var int Default cost used for password hashing.
  85. * Allowed value is between 4 and 31.
  86. * @see generatePasswordHash()
  87. * @since 2.0.6
  88. */
  89. public $passwordHashCost = 13;
  90. /**
  91. * Encrypts data using a password.
  92. * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
  93. * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to
  94. * encrypt fast using a cryptographic key rather than a password. Key derivation time is
  95. * determined by [[$derivationIterations]], which should be set as high as possible.
  96. * The encrypted data includes a keyed message authentication code (MAC) so there is no need
  97. * to hash input or output data.
  98. * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
  99. * poor-quality or compromised passwords.
  100. * @param string $data the data to encrypt
  101. * @param string $password the password to use for encryption
  102. * @return string the encrypted data
  103. * @see decryptByPassword()
  104. * @see encryptByKey()
  105. */
  106. public function encryptByPassword($data, $password)
  107. {
  108. return $this->encrypt($data, true, $password, null);
  109. }
  110. /**
  111. * Encrypts data using a cryptographic key.
  112. * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
  113. * which is very fast relative to [[encryptByPassword()]]. The input key must be properly
  114. * random -- use [[generateRandomKey()]] to generate keys.
  115. * The encrypted data includes a keyed message authentication code (MAC) so there is no need
  116. * to hash input or output data.
  117. * @param string $data the data to encrypt
  118. * @param string $inputKey the input to use for encryption and authentication
  119. * @param string $info optional context and application specific information, see [[hkdf()]]
  120. * @return string the encrypted data
  121. * @see decryptByKey()
  122. * @see encryptByPassword()
  123. */
  124. public function encryptByKey($data, $inputKey, $info = null)
  125. {
  126. return $this->encrypt($data, false, $inputKey, $info);
  127. }
  128. /**
  129. * Verifies and decrypts data encrypted with [[encryptByPassword()]].
  130. * @param string $data the encrypted data to decrypt
  131. * @param string $password the password to use for decryption
  132. * @return bool|string the decrypted data or false on authentication failure
  133. * @see encryptByPassword()
  134. */
  135. public function decryptByPassword($data, $password)
  136. {
  137. return $this->decrypt($data, true, $password, null);
  138. }
  139. /**
  140. * Verifies and decrypts data encrypted with [[encryptByKey()]].
  141. * @param string $data the encrypted data to decrypt
  142. * @param string $inputKey the input to use for encryption and authentication
  143. * @param string $info optional context and application specific information, see [[hkdf()]]
  144. * @return bool|string the decrypted data or false on authentication failure
  145. * @see encryptByKey()
  146. */
  147. public function decryptByKey($data, $inputKey, $info = null)
  148. {
  149. return $this->decrypt($data, false, $inputKey, $info);
  150. }
  151. /**
  152. * Encrypts data.
  153. *
  154. * @param string $data data to be encrypted
  155. * @param bool $passwordBased set true to use password-based key derivation
  156. * @param string $secret the encryption password or key
  157. * @param string $info context/application specific information, e.g. a user ID
  158. * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
  159. *
  160. * @return string the encrypted data
  161. * @throws InvalidConfigException on OpenSSL not loaded
  162. * @throws Exception on OpenSSL error
  163. * @see decrypt()
  164. */
  165. protected function encrypt($data, $passwordBased, $secret, $info)
  166. {
  167. if (!extension_loaded('openssl')) {
  168. throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
  169. }
  170. if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
  171. throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
  172. }
  173. list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
  174. $keySalt = $this->generateRandomKey($keySize);
  175. if ($passwordBased) {
  176. $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
  177. } else {
  178. $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
  179. }
  180. $iv = $this->generateRandomKey($blockSize);
  181. $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
  182. if ($encrypted === false) {
  183. throw new \yii\base\Exception('OpenSSL failure on encryption: ' . openssl_error_string());
  184. }
  185. $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
  186. $hashed = $this->hashData($iv . $encrypted, $authKey);
  187. /*
  188. * Output: [keySalt][MAC][IV][ciphertext]
  189. * - keySalt is KEY_SIZE bytes long
  190. * - MAC: message authentication code, length same as the output of MAC_HASH
  191. * - IV: initialization vector, length $blockSize
  192. */
  193. return $keySalt . $hashed;
  194. }
  195. /**
  196. * Decrypts data.
  197. *
  198. * @param string $data encrypted data to be decrypted.
  199. * @param bool $passwordBased set true to use password-based key derivation
  200. * @param string $secret the decryption password or key
  201. * @param string $info context/application specific information, @see encrypt()
  202. *
  203. * @return bool|string the decrypted data or false on authentication failure
  204. * @throws InvalidConfigException on OpenSSL not loaded
  205. * @throws Exception on OpenSSL error
  206. * @see encrypt()
  207. */
  208. protected function decrypt($data, $passwordBased, $secret, $info)
  209. {
  210. if (!extension_loaded('openssl')) {
  211. throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
  212. }
  213. if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
  214. throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
  215. }
  216. list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
  217. $keySalt = StringHelper::byteSubstr($data, 0, $keySize);
  218. if ($passwordBased) {
  219. $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
  220. } else {
  221. $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
  222. }
  223. $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
  224. $data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey);
  225. if ($data === false) {
  226. return false;
  227. }
  228. $iv = StringHelper::byteSubstr($data, 0, $blockSize);
  229. $encrypted = StringHelper::byteSubstr($data, $blockSize, null);
  230. $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
  231. if ($decrypted === false) {
  232. throw new \yii\base\Exception('OpenSSL failure on decryption: ' . openssl_error_string());
  233. }
  234. return $decrypted;
  235. }
  236. /**
  237. * Derives a key from the given input key using the standard HKDF algorithm.
  238. * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
  239. * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
  240. * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
  241. * @param string $inputKey the source key
  242. * @param string $salt the random salt
  243. * @param string $info optional info to bind the derived key material to application-
  244. * and context-specific information, e.g. a user ID or API version, see
  245. * [RFC 5869](https://tools.ietf.org/html/rfc5869)
  246. * @param int $length length of the output key in bytes. If 0, the output key is
  247. * the length of the hash algorithm output.
  248. * @throws InvalidParamException when HMAC generation fails.
  249. * @return string the derived key
  250. */
  251. public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
  252. {
  253. $test = @hash_hmac($algo, '', '', true);
  254. if (!$test) {
  255. throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
  256. }
  257. $hashLength = StringHelper::byteLength($test);
  258. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  259. $length = (int) $length;
  260. }
  261. if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
  262. throw new InvalidParamException('Invalid length');
  263. }
  264. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  265. if ($salt === null) {
  266. $salt = str_repeat("\0", $hashLength);
  267. }
  268. $prKey = hash_hmac($algo, $inputKey, $salt, true);
  269. $hmac = '';
  270. $outputKey = '';
  271. for ($i = 1; $i <= $blocks; $i++) {
  272. $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
  273. $outputKey .= $hmac;
  274. }
  275. if ($length !== 0) {
  276. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  277. }
  278. return $outputKey;
  279. }
  280. /**
  281. * Derives a key from the given password using the standard PBKDF2 algorithm.
  282. * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
  283. * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
  284. * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
  285. * @param string $password the source password
  286. * @param string $salt the random salt
  287. * @param int $iterations the number of iterations of the hash algorithm. Set as high as
  288. * possible to hinder dictionary password attacks.
  289. * @param int $length length of the output key in bytes. If 0, the output key is
  290. * the length of the hash algorithm output.
  291. * @return string the derived key
  292. * @throws InvalidParamException when hash generation fails due to invalid params given.
  293. */
  294. public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
  295. {
  296. if (function_exists('hash_pbkdf2')) {
  297. $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
  298. if ($outputKey === false) {
  299. throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
  300. }
  301. return $outputKey;
  302. }
  303. // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
  304. $test = @hash_hmac($algo, '', '', true);
  305. if (!$test) {
  306. throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
  307. }
  308. if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
  309. $iterations = (int) $iterations;
  310. }
  311. if (!is_int($iterations) || $iterations < 1) {
  312. throw new InvalidParamException('Invalid iterations');
  313. }
  314. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  315. $length = (int) $length;
  316. }
  317. if (!is_int($length) || $length < 0) {
  318. throw new InvalidParamException('Invalid length');
  319. }
  320. $hashLength = StringHelper::byteLength($test);
  321. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  322. $outputKey = '';
  323. for ($j = 1; $j <= $blocks; $j++) {
  324. $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
  325. $xorsum = $hmac;
  326. for ($i = 1; $i < $iterations; $i++) {
  327. $hmac = hash_hmac($algo, $hmac, $password, true);
  328. $xorsum ^= $hmac;
  329. }
  330. $outputKey .= $xorsum;
  331. }
  332. if ($length !== 0) {
  333. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  334. }
  335. return $outputKey;
  336. }
  337. /**
  338. * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
  339. * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
  340. * as those methods perform the task.
  341. * @param string $data the data to be protected
  342. * @param string $key the secret key to be used for generating hash. Should be a secure
  343. * cryptographic key.
  344. * @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase
  345. * hex digits will be generated.
  346. * @return string the data prefixed with the keyed hash
  347. * @throws InvalidConfigException when HMAC generation fails.
  348. * @see validateData()
  349. * @see generateRandomKey()
  350. * @see hkdf()
  351. * @see pbkdf2()
  352. */
  353. public function hashData($data, $key, $rawHash = false)
  354. {
  355. $hash = hash_hmac($this->macHash, $data, $key, $rawHash);
  356. if (!$hash) {
  357. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  358. }
  359. return $hash . $data;
  360. }
  361. /**
  362. * Validates if the given data is tampered.
  363. * @param string $data the data to be validated. The data must be previously
  364. * generated by [[hashData()]].
  365. * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
  366. * function to see the supported hashing algorithms on your system. This must be the same
  367. * as the value passed to [[hashData()]] when generating the hash for the data.
  368. * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]].
  369. * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
  370. * of lowercase hex digits only.
  371. * hex digits will be generated.
  372. * @return string the real data with the hash stripped off. False if the data is tampered.
  373. * @throws InvalidConfigException when HMAC generation fails.
  374. * @see hashData()
  375. */
  376. public function validateData($data, $key, $rawHash = false)
  377. {
  378. $test = @hash_hmac($this->macHash, '', '', $rawHash);
  379. if (!$test) {
  380. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  381. }
  382. $hashLength = StringHelper::byteLength($test);
  383. if (StringHelper::byteLength($data) >= $hashLength) {
  384. $hash = StringHelper::byteSubstr($data, 0, $hashLength);
  385. $pureData = StringHelper::byteSubstr($data, $hashLength, null);
  386. $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
  387. if ($this->compareString($hash, $calculatedHash)) {
  388. return $pureData;
  389. }
  390. }
  391. return false;
  392. }
  393. private $_useLibreSSL;
  394. private $_randomFile;
  395. /**
  396. * Generates specified number of random bytes.
  397. * Note that output may not be ASCII.
  398. * @see generateRandomString() if you need a string.
  399. *
  400. * @param int $length the number of bytes to generate
  401. * @return string the generated random bytes
  402. * @throws InvalidParamException if wrong length is specified
  403. * @throws Exception on failure.
  404. */
  405. public function generateRandomKey($length = 32)
  406. {
  407. if (!is_int($length)) {
  408. throw new InvalidParamException('First parameter ($length) must be an integer');
  409. }
  410. if ($length < 1) {
  411. throw new InvalidParamException('First parameter ($length) must be greater than 0');
  412. }
  413. // always use random_bytes() if it is available
  414. if (function_exists('random_bytes')) {
  415. return random_bytes($length);
  416. }
  417. // The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
  418. // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
  419. // https://bugs.php.net/bug.php?id=71143
  420. if ($this->_useLibreSSL === null) {
  421. $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
  422. && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
  423. && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
  424. }
  425. // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
  426. // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
  427. if ($this->_useLibreSSL
  428. || (
  429. DIRECTORY_SEPARATOR !== '/'
  430. && substr_compare(PHP_OS, 'win', 0, 3, true) === 0
  431. && function_exists('openssl_random_pseudo_bytes')
  432. )
  433. ) {
  434. $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
  435. if ($cryptoStrong === false) {
  436. throw new Exception(
  437. 'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
  438. );
  439. }
  440. if ($key !== false && StringHelper::byteLength($key) === $length) {
  441. return $key;
  442. }
  443. }
  444. // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
  445. // CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
  446. if (function_exists('mcrypt_create_iv')) {
  447. $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  448. if (StringHelper::byteLength($key) === $length) {
  449. return $key;
  450. }
  451. }
  452. // If not on Windows, try to open a random device.
  453. if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') {
  454. // urandom is a symlink to random on FreeBSD.
  455. $device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
  456. // Check random device for special character device protection mode. Use lstat()
  457. // instead of stat() in case an attacker arranges a symlink to a fake device.
  458. $lstat = @lstat($device);
  459. if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) {
  460. $this->_randomFile = fopen($device, 'rb') ?: null;
  461. if (is_resource($this->_randomFile)) {
  462. // Reduce PHP stream buffer from default 8192 bytes to optimize data
  463. // transfer from the random device for smaller values of $length.
  464. // This also helps to keep future randoms out of user memory space.
  465. $bufferSize = 8;
  466. if (function_exists('stream_set_read_buffer')) {
  467. stream_set_read_buffer($this->_randomFile, $bufferSize);
  468. }
  469. // stream_set_read_buffer() isn't implemented on HHVM
  470. if (function_exists('stream_set_chunk_size')) {
  471. stream_set_chunk_size($this->_randomFile, $bufferSize);
  472. }
  473. }
  474. }
  475. }
  476. if (is_resource($this->_randomFile)) {
  477. $buffer = '';
  478. $stillNeed = $length;
  479. while ($stillNeed > 0) {
  480. $someBytes = fread($this->_randomFile, $stillNeed);
  481. if ($someBytes === false) {
  482. break;
  483. }
  484. $buffer .= $someBytes;
  485. $stillNeed -= StringHelper::byteLength($someBytes);
  486. if ($stillNeed === 0) {
  487. // Leaving file pointer open in order to make next generation faster by reusing it.
  488. return $buffer;
  489. }
  490. }
  491. fclose($this->_randomFile);
  492. $this->_randomFile = null;
  493. }
  494. throw new Exception('Unable to generate a random key');
  495. }
  496. /**
  497. * Generates a random string of specified length.
  498. * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
  499. *
  500. * @param int $length the length of the key in characters
  501. * @return string the generated random key
  502. * @throws Exception on failure.
  503. */
  504. public function generateRandomString($length = 32)
  505. {
  506. if (!is_int($length)) {
  507. throw new InvalidParamException('First parameter ($length) must be an integer');
  508. }
  509. if ($length < 1) {
  510. throw new InvalidParamException('First parameter ($length) must be greater than 0');
  511. }
  512. $bytes = $this->generateRandomKey($length);
  513. // '=' character(s) returned by base64_encode() are always discarded because
  514. // they are guaranteed to be after position $length in the base64_encode() output.
  515. return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
  516. }
  517. /**
  518. * Generates a secure hash from a password and a random salt.
  519. *
  520. * The generated hash can be stored in database.
  521. * Later when a password needs to be validated, the hash can be fetched and passed
  522. * to [[validatePassword()]]. For example,
  523. *
  524. * ```php
  525. * // generates the hash (usually done during user registration or when the password is changed)
  526. * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
  527. * // ...save $hash in database...
  528. *
  529. * // during login, validate if the password entered is correct using $hash fetched from database
  530. * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
  531. * // password is good
  532. * } else {
  533. * // password is bad
  534. * }
  535. * ```
  536. *
  537. * @param string $password The password to be hashed.
  538. * @param int $cost Cost parameter used by the Blowfish hash algorithm.
  539. * The higher the value of cost,
  540. * the longer it takes to generate the hash and to verify a password against it. Higher cost
  541. * therefore slows down a brute-force attack. For best protection against brute-force attacks,
  542. * set it to the highest value that is tolerable on production servers. The time taken to
  543. * compute the hash doubles for every increment by one of $cost.
  544. * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
  545. * the output is always 60 ASCII characters, when set to 'password_hash' the output length
  546. * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
  547. * @throws Exception on bad password parameter or cost parameter.
  548. * @see validatePassword()
  549. */
  550. public function generatePasswordHash($password, $cost = null)
  551. {
  552. if ($cost === null) {
  553. $cost = $this->passwordHashCost;
  554. }
  555. if (function_exists('password_hash')) {
  556. /** @noinspection PhpUndefinedConstantInspection */
  557. return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
  558. }
  559. $salt = $this->generateSalt($cost);
  560. $hash = crypt($password, $salt);
  561. // strlen() is safe since crypt() returns only ascii
  562. if (!is_string($hash) || strlen($hash) !== 60) {
  563. throw new Exception('Unknown error occurred while generating hash.');
  564. }
  565. return $hash;
  566. }
  567. /**
  568. * Verifies a password against a hash.
  569. * @param string $password The password to verify.
  570. * @param string $hash The hash to verify the password against.
  571. * @return bool whether the password is correct.
  572. * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
  573. * @see generatePasswordHash()
  574. */
  575. public function validatePassword($password, $hash)
  576. {
  577. if (!is_string($password) || $password === '') {
  578. throw new InvalidParamException('Password must be a string and cannot be empty.');
  579. }
  580. if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
  581. || $matches[1] < 4
  582. || $matches[1] > 30
  583. ) {
  584. throw new InvalidParamException('Hash is invalid.');
  585. }
  586. if (function_exists('password_verify')) {
  587. return password_verify($password, $hash);
  588. }
  589. $test = crypt($password, $hash);
  590. $n = strlen($test);
  591. if ($n !== 60) {
  592. return false;
  593. }
  594. return $this->compareString($test, $hash);
  595. }
  596. /**
  597. * Generates a salt that can be used to generate a password hash.
  598. *
  599. * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
  600. * requires, for the Blowfish hash algorithm, a salt string in a specific format:
  601. * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
  602. * from the alphabet "./0-9A-Za-z".
  603. *
  604. * @param int $cost the cost parameter
  605. * @return string the random salt value.
  606. * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
  607. */
  608. protected function generateSalt($cost = 13)
  609. {
  610. $cost = (int) $cost;
  611. if ($cost < 4 || $cost > 31) {
  612. throw new InvalidParamException('Cost must be between 4 and 31.');
  613. }
  614. // Get a 20-byte random string
  615. $rand = $this->generateRandomKey(20);
  616. // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
  617. $salt = sprintf("$2y$%02d$", $cost);
  618. // Append the random salt data in the required base64 format.
  619. $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
  620. return $salt;
  621. }
  622. /**
  623. * Performs string comparison using timing attack resistant approach.
  624. * @see http://codereview.stackexchange.com/questions/13512
  625. * @param string $expected string to compare.
  626. * @param string $actual user-supplied string.
  627. * @return bool whether strings are equal.
  628. */
  629. public function compareString($expected, $actual)
  630. {
  631. $expected .= "\0";
  632. $actual .= "\0";
  633. $expectedLength = StringHelper::byteLength($expected);
  634. $actualLength = StringHelper::byteLength($actual);
  635. $diff = $expectedLength - $actualLength;
  636. for ($i = 0; $i < $actualLength; $i++) {
  637. $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
  638. }
  639. return $diff === 0;
  640. }
  641. }