You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

651 lines
28KB

  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. */
  78. public $passwordHashStrategy = 'crypt';
  79. /**
  80. * Encrypts data using a password.
  81. * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
  82. * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to
  83. * encrypt fast using a cryptographic key rather than a password. Key derivation time is
  84. * determined by [[$derivationIterations]], which should be set as high as possible.
  85. * The encrypted data includes a keyed message authentication code (MAC) so there is no need
  86. * to hash input or output data.
  87. * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
  88. * poor-quality or compromised passwords.
  89. * @param string $data the data to encrypt
  90. * @param string $password the password to use for encryption
  91. * @return string the encrypted data
  92. * @see decryptByPassword()
  93. * @see encryptByKey()
  94. */
  95. public function encryptByPassword($data, $password)
  96. {
  97. return $this->encrypt($data, true, $password, null);
  98. }
  99. /**
  100. * Encrypts data using a cryptograhic key.
  101. * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
  102. * which is very fast relative to [[encryptByPassword()]]. The input key must be properly
  103. * random -- use [[generateRandomKey()]] to generate keys.
  104. * The encrypted data includes a keyed message authentication code (MAC) so there is no need
  105. * to hash input or output data.
  106. * @param string $data the data to encrypt
  107. * @param string $inputKey the input to use for encryption and authentication
  108. * @param string $info optional context and application specific information, see [[hkdf()]]
  109. * @return string the encrypted data
  110. * @see decryptByPassword()
  111. * @see encryptByKey()
  112. */
  113. public function encryptByKey($data, $inputKey, $info = null)
  114. {
  115. return $this->encrypt($data, false, $inputKey, $info);
  116. }
  117. /**
  118. * Verifies and decrypts data encrypted with [[encryptByPassword()]].
  119. * @param string $data the encrypted data to decrypt
  120. * @param string $password the password to use for decryption
  121. * @return bool|string the decrypted data or false on authentication failure
  122. * @see encryptByPassword()
  123. */
  124. public function decryptByPassword($data, $password)
  125. {
  126. return $this->decrypt($data, true, $password, null);
  127. }
  128. /**
  129. * Verifies and decrypts data encrypted with [[encryptByPassword()]].
  130. * @param string $data the encrypted data to decrypt
  131. * @param string $inputKey the input to use for encryption and authentication
  132. * @param string $info optional context and application specific information, see [[hkdf()]]
  133. * @return bool|string the decrypted data or false on authentication failure
  134. * @see encryptByKey()
  135. */
  136. public function decryptByKey($data, $inputKey, $info = null)
  137. {
  138. return $this->decrypt($data, false, $inputKey, $info);
  139. }
  140. /**
  141. * Encrypts data.
  142. *
  143. * @param string $data data to be encrypted
  144. * @param boolean $passwordBased set true to use password-based key derivation
  145. * @param string $secret the encryption password or key
  146. * @param string $info context/application specific information, e.g. a user ID
  147. * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
  148. *
  149. * @return string the encrypted data
  150. * @throws InvalidConfigException on OpenSSL not loaded
  151. * @throws Exception on OpenSSL error
  152. * @see decrypt()
  153. */
  154. protected function encrypt($data, $passwordBased, $secret, $info)
  155. {
  156. if (!extension_loaded('openssl')) {
  157. throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
  158. }
  159. if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
  160. throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
  161. }
  162. list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
  163. $keySalt = $this->generateRandomKey($keySize);
  164. if ($passwordBased) {
  165. $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
  166. } else {
  167. $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
  168. }
  169. $iv = $this->generateRandomKey($blockSize);
  170. $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
  171. if ($encrypted === false) {
  172. throw new \yii\base\Exception('OpenSSL failure on encryption: ' . openssl_error_string());
  173. }
  174. $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
  175. $hashed = $this->hashData($iv . $encrypted, $authKey);
  176. /*
  177. * Output: [keySalt][MAC][IV][ciphertext]
  178. * - keySalt is KEY_SIZE bytes long
  179. * - MAC: message authentication code, length same as the output of MAC_HASH
  180. * - IV: initialization vector, length $blockSize
  181. */
  182. return $keySalt . $hashed;
  183. }
  184. /**
  185. * Decrypts data.
  186. *
  187. * @param string $data encrypted data to be decrypted.
  188. * @param boolean $passwordBased set true to use password-based key derivation
  189. * @param string $secret the decryption password or key
  190. * @param string $info context/application specific information, @see encrypt()
  191. *
  192. * @return bool|string the decrypted data or false on authentication failure
  193. * @throws InvalidConfigException on OpenSSL not loaded
  194. * @throws Exception on OpenSSL error
  195. * @see encrypt()
  196. */
  197. protected function decrypt($data, $passwordBased, $secret, $info)
  198. {
  199. if (!extension_loaded('openssl')) {
  200. throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
  201. }
  202. if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
  203. throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
  204. }
  205. list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
  206. $keySalt = StringHelper::byteSubstr($data, 0, $keySize);
  207. if ($passwordBased) {
  208. $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
  209. } else {
  210. $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
  211. }
  212. $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
  213. $data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey);
  214. if ($data === false) {
  215. return false;
  216. }
  217. $iv = StringHelper::byteSubstr($data, 0, $blockSize);
  218. $encrypted = StringHelper::byteSubstr($data, $blockSize, null);
  219. $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
  220. if ($decrypted === false) {
  221. throw new \yii\base\Exception('OpenSSL failure on decryption: ' . openssl_error_string());
  222. }
  223. return $decrypted;
  224. }
  225. /**
  226. * Derives a key from the given input key using the standard HKDF algorithm.
  227. * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
  228. * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
  229. * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
  230. * @param string $inputKey the source key
  231. * @param string $salt the random salt
  232. * @param string $info optional info to bind the derived key material to application-
  233. * and context-specific information, e.g. a user ID or API version, see
  234. * [RFC 5869](https://tools.ietf.org/html/rfc5869)
  235. * @param integer $length length of the output key in bytes. If 0, the output key is
  236. * the length of the hash algorithm output.
  237. * @throws InvalidParamException when HMAC generation fails.
  238. * @return string the derived key
  239. */
  240. public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
  241. {
  242. $test = @hash_hmac($algo, '', '', true);
  243. if (!$test) {
  244. throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
  245. }
  246. $hashLength = StringHelper::byteLength($test);
  247. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  248. $length = (int) $length;
  249. }
  250. if (!is_integer($length) || $length < 0 || $length > 255 * $hashLength) {
  251. throw new InvalidParamException('Invalid length');
  252. }
  253. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  254. if ($salt === null) {
  255. $salt = str_repeat("\0", $hashLength);
  256. }
  257. $prKey = hash_hmac($algo, $inputKey, $salt, true);
  258. $hmac = '';
  259. $outputKey = '';
  260. for ($i = 1; $i <= $blocks; $i++) {
  261. $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
  262. $outputKey .= $hmac;
  263. }
  264. if ($length !== 0) {
  265. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  266. }
  267. return $outputKey;
  268. }
  269. /**
  270. * Derives a key from the given password using the standard PBKDF2 algorithm.
  271. * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
  272. * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
  273. * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
  274. * @param string $password the source password
  275. * @param string $salt the random salt
  276. * @param integer $iterations the number of iterations of the hash algorithm. Set as high as
  277. * possible to hinder dictionary password attacks.
  278. * @param integer $length length of the output key in bytes. If 0, the output key is
  279. * the length of the hash algorithm output.
  280. * @return string the derived key
  281. * @throws InvalidParamException when hash generation fails due to invalid params given.
  282. */
  283. public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
  284. {
  285. if (function_exists('hash_pbkdf2')) {
  286. $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
  287. if ($outputKey === false) {
  288. throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
  289. }
  290. return $outputKey;
  291. }
  292. // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
  293. $test = @hash_hmac($algo, '', '', true);
  294. if (!$test) {
  295. throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
  296. }
  297. if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
  298. $iterations = (int) $iterations;
  299. }
  300. if (!is_integer($iterations) || $iterations < 1) {
  301. throw new InvalidParamException('Invalid iterations');
  302. }
  303. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  304. $length = (int) $length;
  305. }
  306. if (!is_integer($length) || $length < 0) {
  307. throw new InvalidParamException('Invalid length');
  308. }
  309. $hashLength = StringHelper::byteLength($test);
  310. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  311. $outputKey = '';
  312. for ($j = 1; $j <= $blocks; $j++) {
  313. $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
  314. $xorsum = $hmac;
  315. for ($i = 1; $i < $iterations; $i++) {
  316. $hmac = hash_hmac($algo, $hmac, $password, true);
  317. $xorsum ^= $hmac;
  318. }
  319. $outputKey .= $xorsum;
  320. }
  321. if ($length !== 0) {
  322. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  323. }
  324. return $outputKey;
  325. }
  326. /**
  327. * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
  328. * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
  329. * as those methods perform the task.
  330. * @param string $data the data to be protected
  331. * @param string $key the secret key to be used for generating hash. Should be a secure
  332. * cryptographic key.
  333. * @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
  334. * hex digits will be generated.
  335. * @return string the data prefixed with the keyed hash
  336. * @throws InvalidConfigException when HMAC generation fails.
  337. * @see validateData()
  338. * @see generateRandomKey()
  339. * @see hkdf()
  340. * @see pbkdf2()
  341. */
  342. public function hashData($data, $key, $rawHash = false)
  343. {
  344. $hash = hash_hmac($this->macHash, $data, $key, $rawHash);
  345. if (!$hash) {
  346. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  347. }
  348. return $hash . $data;
  349. }
  350. /**
  351. * Validates if the given data is tampered.
  352. * @param string $data the data to be validated. The data must be previously
  353. * generated by [[hashData()]].
  354. * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
  355. * function to see the supported hashing algorithms on your system. This must be the same
  356. * as the value passed to [[hashData()]] when generating the hash for the data.
  357. * @param boolean $rawHash this should take the same value as when you generate the data using [[hashData()]].
  358. * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
  359. * of lowercase hex digits only.
  360. * hex digits will be generated.
  361. * @return string the real data with the hash stripped off. False if the data is tampered.
  362. * @throws InvalidConfigException when HMAC generation fails.
  363. * @see hashData()
  364. */
  365. public function validateData($data, $key, $rawHash = false)
  366. {
  367. $test = @hash_hmac($this->macHash, '', '', $rawHash);
  368. if (!$test) {
  369. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  370. }
  371. $hashLength = StringHelper::byteLength($test);
  372. if (StringHelper::byteLength($data) >= $hashLength) {
  373. $hash = StringHelper::byteSubstr($data, 0, $hashLength);
  374. $pureData = StringHelper::byteSubstr($data, $hashLength, null);
  375. $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
  376. if ($this->compareString($hash, $calculatedHash)) {
  377. return $pureData;
  378. }
  379. }
  380. return false;
  381. }
  382. /**
  383. * Generates specified number of random bytes.
  384. * Note that output may not be ASCII.
  385. * @see generateRandomString() if you need a string.
  386. *
  387. * @param integer $length the number of bytes to generate
  388. * @return string the generated random bytes
  389. * @throws InvalidConfigException if OpenSSL extension is required (e.g. on Windows) but not installed.
  390. * @throws Exception on failure.
  391. */
  392. public function generateRandomKey($length = 32)
  393. {
  394. /*
  395. * Strategy
  396. *
  397. * The most common platform is Linux, on which /dev/urandom is the best choice. Many other OSs
  398. * implement a device called /dev/urandom for Linux compat and it is good too. So if there is
  399. * a /dev/urandom then it is our first choice regardless of OS.
  400. *
  401. * Nearly all other modern Unix-like systems (the BSDs, Unixes and OS X) have a /dev/random
  402. * that is a good choice. If we didn't get bytes from /dev/urandom then we try this next but
  403. * only if the system is not Linux. Do not try to read /dev/random on Linux.
  404. *
  405. * Finally, OpenSSL can supply CSPR bytes. It is our last resort. On Windows this reads from
  406. * CryptGenRandom, which is the right thing to do. On other systems that don't have a Unix-like
  407. * /dev/urandom, it will deliver bytes from its own CSPRNG that is seeded from kernel sources
  408. * of randomness. Even though it is fast, we don't generally prefer OpenSSL over /dev/urandom
  409. * because an RNG in user space memory is undesirable.
  410. *
  411. * For background, see http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
  412. */
  413. $bytes = '';
  414. // If we are on Linux or any OS that mimics the Linux /dev/urandom device, e.g. FreeBSD or OS X,
  415. // then read from /dev/urandom.
  416. if (@file_exists('/dev/urandom')) {
  417. $handle = fopen('/dev/urandom', 'r');
  418. if ($handle !== false) {
  419. $bytes .= fread($handle, $length);
  420. fclose($handle);
  421. }
  422. }
  423. if (StringHelper::byteLength($bytes) >= $length) {
  424. return StringHelper::byteSubstr($bytes, 0, $length);
  425. }
  426. // If we are not on Linux and there is a /dev/random device then we have a BSD or Unix device
  427. // that won't block. It's not safe to read from /dev/random on Linux.
  428. if (PHP_OS !== 'Linux' && @file_exists('/dev/random')) {
  429. $handle = fopen('/dev/random', 'r');
  430. if ($handle !== false) {
  431. $bytes .= fread($handle, $length);
  432. fclose($handle);
  433. }
  434. }
  435. if (StringHelper::byteLength($bytes) >= $length) {
  436. return StringHelper::byteSubstr($bytes, 0, $length);
  437. }
  438. if (!extension_loaded('openssl')) {
  439. throw new InvalidConfigException('The OpenSSL PHP extension is not installed.');
  440. }
  441. $bytes .= openssl_random_pseudo_bytes($length, $cryptoStrong);
  442. if (StringHelper::byteLength($bytes) < $length || !$cryptoStrong) {
  443. throw new Exception('Unable to generate random bytes.');
  444. }
  445. return StringHelper::byteSubstr($bytes, 0, $length);
  446. }
  447. /**
  448. * Generates a random string of specified length.
  449. * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
  450. *
  451. * @param integer $length the length of the key in characters
  452. * @return string the generated random key
  453. * @throws InvalidConfigException if OpenSSL extension is needed but not installed.
  454. * @throws Exception on failure.
  455. */
  456. public function generateRandomString($length = 32)
  457. {
  458. $bytes = $this->generateRandomKey($length);
  459. // '=' character(s) returned by base64_encode() are always discarded because
  460. // they are guaranteed to be after position $length in the base64_encode() output.
  461. return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
  462. }
  463. /**
  464. * Generates a secure hash from a password and a random salt.
  465. *
  466. * The generated hash can be stored in database.
  467. * Later when a password needs to be validated, the hash can be fetched and passed
  468. * to [[validatePassword()]]. For example,
  469. *
  470. * ~~~
  471. * // generates the hash (usually done during user registration or when the password is changed)
  472. * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
  473. * // ...save $hash in database...
  474. *
  475. * // during login, validate if the password entered is correct using $hash fetched from database
  476. * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
  477. * // password is good
  478. * } else {
  479. * // password is bad
  480. * }
  481. * ~~~
  482. *
  483. * @param string $password The password to be hashed.
  484. * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
  485. * The higher the value of cost,
  486. * the longer it takes to generate the hash and to verify a password against it. Higher cost
  487. * therefore slows down a brute-force attack. For best protection against brute for attacks,
  488. * set it to the highest value that is tolerable on production servers. The time taken to
  489. * compute the hash doubles for every increment by one of $cost.
  490. * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
  491. * the output is always 60 ASCII characters, when set to 'password_hash' the output length
  492. * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
  493. * @throws Exception on bad password parameter or cost parameter.
  494. * @throws InvalidConfigException when an unsupported password hash strategy is configured.
  495. * @see validatePassword()
  496. */
  497. public function generatePasswordHash($password, $cost = 13)
  498. {
  499. switch ($this->passwordHashStrategy) {
  500. case 'password_hash':
  501. if (!function_exists('password_hash')) {
  502. throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
  503. }
  504. /** @noinspection PhpUndefinedConstantInspection */
  505. return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
  506. case 'crypt':
  507. $salt = $this->generateSalt($cost);
  508. $hash = crypt($password, $salt);
  509. // strlen() is safe since crypt() returns only ascii
  510. if (!is_string($hash) || strlen($hash) !== 60) {
  511. throw new Exception('Unknown error occurred while generating hash.');
  512. }
  513. return $hash;
  514. default:
  515. throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
  516. }
  517. }
  518. /**
  519. * Verifies a password against a hash.
  520. * @param string $password The password to verify.
  521. * @param string $hash The hash to verify the password against.
  522. * @return boolean whether the password is correct.
  523. * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
  524. * @throws InvalidConfigException when an unsupported password hash strategy is configured.
  525. * @see generatePasswordHash()
  526. */
  527. public function validatePassword($password, $hash)
  528. {
  529. if (!is_string($password) || $password === '') {
  530. throw new InvalidParamException('Password must be a string and cannot be empty.');
  531. }
  532. if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches) || $matches[1] < 4 || $matches[1] > 30) {
  533. throw new InvalidParamException('Hash is invalid.');
  534. }
  535. switch ($this->passwordHashStrategy) {
  536. case 'password_hash':
  537. if (!function_exists('password_verify')) {
  538. throw new InvalidConfigException('Password hash key strategy "password_hash" requires PHP >= 5.5.0, either upgrade your environment or use another strategy.');
  539. }
  540. return password_verify($password, $hash);
  541. case 'crypt':
  542. $test = crypt($password, $hash);
  543. $n = strlen($test);
  544. if ($n !== 60) {
  545. return false;
  546. }
  547. return $this->compareString($test, $hash);
  548. default:
  549. throw new InvalidConfigException("Unknown password hash strategy '{$this->passwordHashStrategy}'");
  550. }
  551. }
  552. /**
  553. * Generates a salt that can be used to generate a password hash.
  554. *
  555. * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
  556. * requires, for the Blowfish hash algorithm, a salt string in a specific format:
  557. * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
  558. * from the alphabet "./0-9A-Za-z".
  559. *
  560. * @param integer $cost the cost parameter
  561. * @return string the random salt value.
  562. * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
  563. */
  564. protected function generateSalt($cost = 13)
  565. {
  566. $cost = (int) $cost;
  567. if ($cost < 4 || $cost > 31) {
  568. throw new InvalidParamException('Cost must be between 4 and 31.');
  569. }
  570. // Get a 20-byte random string
  571. $rand = $this->generateRandomKey(20);
  572. // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
  573. $salt = sprintf("$2y$%02d$", $cost);
  574. // Append the random salt data in the required base64 format.
  575. $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
  576. return $salt;
  577. }
  578. /**
  579. * Performs string comparison using timing attack resistant approach.
  580. * @see http://codereview.stackexchange.com/questions/13512
  581. * @param string $expected string to compare.
  582. * @param string $actual user-supplied string.
  583. * @return boolean whether strings are equal.
  584. */
  585. public function compareString($expected, $actual)
  586. {
  587. $expected .= "\0";
  588. $actual .= "\0";
  589. $expectedLength = StringHelper::byteLength($expected);
  590. $actualLength = StringHelper::byteLength($actual);
  591. $diff = $expectedLength - $actualLength;
  592. for ($i = 0; $i < $actualLength; $i++) {
  593. $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
  594. }
  595. return $diff === 0;
  596. }
  597. }