Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

702 lines
29KB

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