Security.php 28 KB

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