Security.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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;
  9. use yii\helpers\StringHelper;
  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()](https://secure.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()](https://secure.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 as byte string
  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 as byte string
  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|null $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 as byte string
  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|null $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 InvalidArgumentException 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. if (function_exists('hash_hkdf')) {
  254. $outputKey = hash_hkdf($algo, $inputKey, $length, $info, $salt);
  255. if ($outputKey === false) {
  256. throw new InvalidArgumentException('Invalid parameters to hash_hkdf()');
  257. }
  258. return $outputKey;
  259. }
  260. $test = @hash_hmac($algo, '', '', true);
  261. if (!$test) {
  262. throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo);
  263. }
  264. $hashLength = StringHelper::byteLength($test);
  265. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  266. $length = (int) $length;
  267. }
  268. if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
  269. throw new InvalidArgumentException('Invalid length');
  270. }
  271. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  272. if ($salt === null) {
  273. $salt = str_repeat("\0", $hashLength);
  274. }
  275. $prKey = hash_hmac($algo, $inputKey, $salt, true);
  276. $hmac = '';
  277. $outputKey = '';
  278. for ($i = 1; $i <= $blocks; $i++) {
  279. $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
  280. $outputKey .= $hmac;
  281. }
  282. if ($length !== 0) {
  283. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  284. }
  285. return $outputKey;
  286. }
  287. /**
  288. * Derives a key from the given password using the standard PBKDF2 algorithm.
  289. * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
  290. * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
  291. * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
  292. * @param string $password the source password
  293. * @param string $salt the random salt
  294. * @param int $iterations the number of iterations of the hash algorithm. Set as high as
  295. * possible to hinder dictionary password attacks.
  296. * @param int $length length of the output key in bytes. If 0, the output key is
  297. * the length of the hash algorithm output.
  298. * @return string the derived key
  299. * @throws InvalidArgumentException when hash generation fails due to invalid params given.
  300. */
  301. public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
  302. {
  303. if (function_exists('hash_pbkdf2')) {
  304. $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
  305. if ($outputKey === false) {
  306. throw new InvalidArgumentException('Invalid parameters to hash_pbkdf2()');
  307. }
  308. return $outputKey;
  309. }
  310. // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
  311. $test = @hash_hmac($algo, '', '', true);
  312. if (!$test) {
  313. throw new InvalidArgumentException('Failed to generate HMAC with hash algorithm: ' . $algo);
  314. }
  315. if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
  316. $iterations = (int) $iterations;
  317. }
  318. if (!is_int($iterations) || $iterations < 1) {
  319. throw new InvalidArgumentException('Invalid iterations');
  320. }
  321. if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
  322. $length = (int) $length;
  323. }
  324. if (!is_int($length) || $length < 0) {
  325. throw new InvalidArgumentException('Invalid length');
  326. }
  327. $hashLength = StringHelper::byteLength($test);
  328. $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
  329. $outputKey = '';
  330. for ($j = 1; $j <= $blocks; $j++) {
  331. $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
  332. $xorsum = $hmac;
  333. for ($i = 1; $i < $iterations; $i++) {
  334. $hmac = hash_hmac($algo, $hmac, $password, true);
  335. $xorsum ^= $hmac;
  336. }
  337. $outputKey .= $xorsum;
  338. }
  339. if ($length !== 0) {
  340. $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
  341. }
  342. return $outputKey;
  343. }
  344. /**
  345. * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
  346. * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
  347. * as those methods perform the task.
  348. * @param string $data the data to be protected
  349. * @param string $key the secret key to be used for generating hash. Should be a secure
  350. * cryptographic key.
  351. * @param bool $rawHash whether the generated hash value is in raw binary format. If false, lowercase
  352. * hex digits will be generated.
  353. * @return string the data prefixed with the keyed hash
  354. * @throws InvalidConfigException when HMAC generation fails.
  355. * @see validateData()
  356. * @see generateRandomKey()
  357. * @see hkdf()
  358. * @see pbkdf2()
  359. */
  360. public function hashData($data, $key, $rawHash = false)
  361. {
  362. $hash = hash_hmac($this->macHash, $data, $key, $rawHash);
  363. if (!$hash) {
  364. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  365. }
  366. return $hash . $data;
  367. }
  368. /**
  369. * Validates if the given data is tampered.
  370. * @param string $data the data to be validated. The data must be previously
  371. * generated by [[hashData()]].
  372. * @param string $key the secret key that was previously used to generate the hash for the data in [[hashData()]].
  373. * function to see the supported hashing algorithms on your system. This must be the same
  374. * as the value passed to [[hashData()]] when generating the hash for the data.
  375. * @param bool $rawHash this should take the same value as when you generate the data using [[hashData()]].
  376. * It indicates whether the hash value in the data is in binary format. If false, it means the hash value consists
  377. * of lowercase hex digits only.
  378. * hex digits will be generated.
  379. * @return string|false the real data with the hash stripped off. False if the data is tampered.
  380. * @throws InvalidConfigException when HMAC generation fails.
  381. * @see hashData()
  382. */
  383. public function validateData($data, $key, $rawHash = false)
  384. {
  385. $test = @hash_hmac($this->macHash, '', '', $rawHash);
  386. if (!$test) {
  387. throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
  388. }
  389. $hashLength = StringHelper::byteLength($test);
  390. if (StringHelper::byteLength($data) >= $hashLength) {
  391. $hash = StringHelper::byteSubstr($data, 0, $hashLength);
  392. $pureData = StringHelper::byteSubstr($data, $hashLength, null);
  393. $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
  394. if ($this->compareString($hash, $calculatedHash)) {
  395. return $pureData;
  396. }
  397. }
  398. return false;
  399. }
  400. private $_useLibreSSL;
  401. private $_randomFile;
  402. /**
  403. * Generates specified number of random bytes.
  404. * Note that output may not be ASCII.
  405. * @see generateRandomString() if you need a string.
  406. *
  407. * @param int $length the number of bytes to generate
  408. * @return string the generated random bytes
  409. * @throws InvalidArgumentException if wrong length is specified
  410. * @throws Exception on failure.
  411. */
  412. public function generateRandomKey($length = 32)
  413. {
  414. if (!is_int($length)) {
  415. throw new InvalidArgumentException('First parameter ($length) must be an integer');
  416. }
  417. if ($length < 1) {
  418. throw new InvalidArgumentException('First parameter ($length) must be greater than 0');
  419. }
  420. // always use random_bytes() if it is available
  421. if (function_exists('random_bytes')) {
  422. return random_bytes($length);
  423. }
  424. // The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
  425. // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
  426. // https://bugs.php.net/bug.php?id=71143
  427. if ($this->_useLibreSSL === null) {
  428. $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
  429. && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
  430. && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
  431. }
  432. // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
  433. // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
  434. if (function_exists('openssl_random_pseudo_bytes')
  435. && ($this->_useLibreSSL
  436. || (
  437. DIRECTORY_SEPARATOR !== '/'
  438. && substr_compare(PHP_OS, 'win', 0, 3, true) === 0
  439. ))
  440. ) {
  441. $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
  442. if ($cryptoStrong === false) {
  443. throw new Exception(
  444. 'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
  445. );
  446. }
  447. if ($key !== false && StringHelper::byteLength($key) === $length) {
  448. return $key;
  449. }
  450. }
  451. // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
  452. // CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
  453. if (function_exists('mcrypt_create_iv')) {
  454. $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
  455. if (StringHelper::byteLength($key) === $length) {
  456. return $key;
  457. }
  458. }
  459. // If not on Windows, try to open a random device.
  460. if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') {
  461. // urandom is a symlink to random on FreeBSD.
  462. $device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
  463. // Check random device for special character device protection mode. Use lstat()
  464. // instead of stat() in case an attacker arranges a symlink to a fake device.
  465. $lstat = @lstat($device);
  466. if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) {
  467. $this->_randomFile = fopen($device, 'rb') ?: null;
  468. if (is_resource($this->_randomFile)) {
  469. // Reduce PHP stream buffer from default 8192 bytes to optimize data
  470. // transfer from the random device for smaller values of $length.
  471. // This also helps to keep future randoms out of user memory space.
  472. $bufferSize = 8;
  473. if (function_exists('stream_set_read_buffer')) {
  474. stream_set_read_buffer($this->_randomFile, $bufferSize);
  475. }
  476. // stream_set_read_buffer() isn't implemented on HHVM
  477. if (function_exists('stream_set_chunk_size')) {
  478. stream_set_chunk_size($this->_randomFile, $bufferSize);
  479. }
  480. }
  481. }
  482. }
  483. if (is_resource($this->_randomFile)) {
  484. $buffer = '';
  485. $stillNeed = $length;
  486. while ($stillNeed > 0) {
  487. $someBytes = fread($this->_randomFile, $stillNeed);
  488. if ($someBytes === false) {
  489. break;
  490. }
  491. $buffer .= $someBytes;
  492. $stillNeed -= StringHelper::byteLength($someBytes);
  493. if ($stillNeed === 0) {
  494. // Leaving file pointer open in order to make next generation faster by reusing it.
  495. return $buffer;
  496. }
  497. }
  498. fclose($this->_randomFile);
  499. $this->_randomFile = null;
  500. }
  501. throw new Exception('Unable to generate a random key');
  502. }
  503. /**
  504. * Generates a random string of specified length.
  505. * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
  506. *
  507. * @param int $length the length of the key in characters
  508. * @return string the generated random key
  509. * @throws Exception on failure.
  510. */
  511. public function generateRandomString($length = 32)
  512. {
  513. if (!is_int($length)) {
  514. throw new InvalidArgumentException('First parameter ($length) must be an integer');
  515. }
  516. if ($length < 1) {
  517. throw new InvalidArgumentException('First parameter ($length) must be greater than 0');
  518. }
  519. $bytes = $this->generateRandomKey($length);
  520. return substr(StringHelper::base64UrlEncode($bytes), 0, $length);
  521. }
  522. /**
  523. * Generates a secure hash from a password and a random salt.
  524. *
  525. * The generated hash can be stored in database.
  526. * Later when a password needs to be validated, the hash can be fetched and passed
  527. * to [[validatePassword()]]. For example,
  528. *
  529. * ```php
  530. * // generates the hash (usually done during user registration or when the password is changed)
  531. * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
  532. * // ...save $hash in database...
  533. *
  534. * // during login, validate if the password entered is correct using $hash fetched from database
  535. * if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
  536. * // password is good
  537. * } else {
  538. * // password is bad
  539. * }
  540. * ```
  541. *
  542. * @param string $password The password to be hashed.
  543. * @param int $cost Cost parameter used by the Blowfish hash algorithm.
  544. * The higher the value of cost,
  545. * the longer it takes to generate the hash and to verify a password against it. Higher cost
  546. * therefore slows down a brute-force attack. For best protection against brute-force attacks,
  547. * set it to the highest value that is tolerable on production servers. The time taken to
  548. * compute the hash doubles for every increment by one of $cost.
  549. * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
  550. * the output is always 60 ASCII characters, when set to 'password_hash' the output length
  551. * might increase in future versions of PHP (https://secure.php.net/manual/en/function.password-hash.php)
  552. * @throws Exception on bad password parameter or cost parameter.
  553. * @see validatePassword()
  554. */
  555. public function generatePasswordHash($password, $cost = null)
  556. {
  557. if ($cost === null) {
  558. $cost = $this->passwordHashCost;
  559. }
  560. if (function_exists('password_hash')) {
  561. /* @noinspection PhpUndefinedConstantInspection */
  562. return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
  563. }
  564. $salt = $this->generateSalt($cost);
  565. $hash = crypt($password, $salt);
  566. // strlen() is safe since crypt() returns only ascii
  567. if (!is_string($hash) || strlen($hash) !== 60) {
  568. throw new Exception('Unknown error occurred while generating hash.');
  569. }
  570. return $hash;
  571. }
  572. /**
  573. * Verifies a password against a hash.
  574. * @param string $password The password to verify.
  575. * @param string $hash The hash to verify the password against.
  576. * @return bool whether the password is correct.
  577. * @throws InvalidArgumentException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
  578. * @see generatePasswordHash()
  579. */
  580. public function validatePassword($password, $hash)
  581. {
  582. if (!is_string($password) || $password === '') {
  583. throw new InvalidArgumentException('Password must be a string and cannot be empty.');
  584. }
  585. if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
  586. || $matches[1] < 4
  587. || $matches[1] > 30
  588. ) {
  589. throw new InvalidArgumentException('Hash is invalid.');
  590. }
  591. if (function_exists('password_verify')) {
  592. return password_verify($password, $hash);
  593. }
  594. $test = crypt($password, $hash);
  595. $n = strlen($test);
  596. if ($n !== 60) {
  597. return false;
  598. }
  599. return $this->compareString($test, $hash);
  600. }
  601. /**
  602. * Generates a salt that can be used to generate a password hash.
  603. *
  604. * The PHP [crypt()](https://secure.php.net/manual/en/function.crypt.php) built-in function
  605. * requires, for the Blowfish hash algorithm, a salt string in a specific format:
  606. * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
  607. * from the alphabet "./0-9A-Za-z".
  608. *
  609. * @param int $cost the cost parameter
  610. * @return string the random salt value.
  611. * @throws InvalidArgumentException if the cost parameter is out of the range of 4 to 31.
  612. */
  613. protected function generateSalt($cost = 13)
  614. {
  615. $cost = (int) $cost;
  616. if ($cost < 4 || $cost > 31) {
  617. throw new InvalidArgumentException('Cost must be between 4 and 31.');
  618. }
  619. // Get a 20-byte random string
  620. $rand = $this->generateRandomKey(20);
  621. // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
  622. $salt = sprintf('$2y$%02d$', $cost);
  623. // Append the random salt data in the required base64 format.
  624. $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
  625. return $salt;
  626. }
  627. /**
  628. * Performs string comparison using timing attack resistant approach.
  629. * @see http://codereview.stackexchange.com/questions/13512
  630. * @param string $expected string to compare.
  631. * @param string $actual user-supplied string.
  632. * @return bool whether strings are equal.
  633. */
  634. public function compareString($expected, $actual)
  635. {
  636. if (!is_string($expected)) {
  637. throw new InvalidArgumentException('Expected expected value to be a string, ' . gettype($expected) . ' given.');
  638. }
  639. if (!is_string($actual)) {
  640. throw new InvalidArgumentException('Expected actual value to be a string, ' . gettype($actual) . ' given.');
  641. }
  642. if (function_exists('hash_equals')) {
  643. return hash_equals($expected, $actual);
  644. }
  645. $expected .= "\0";
  646. $actual .= "\0";
  647. $expectedLength = StringHelper::byteLength($expected);
  648. $actualLength = StringHelper::byteLength($actual);
  649. $diff = $expectedLength - $actualLength;
  650. for ($i = 0; $i < $actualLength; $i++) {
  651. $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
  652. }
  653. return $diff === 0;
  654. }
  655. /**
  656. * Masks a token to make it uncompressible.
  657. * Applies a random mask to the token and prepends the mask used to the result making the string always unique.
  658. * Used to mitigate BREACH attack by randomizing how token is outputted on each request.
  659. * @param string $token An unmasked token.
  660. * @return string A masked token.
  661. * @since 2.0.12
  662. */
  663. public function maskToken($token)
  664. {
  665. // The number of bytes in a mask is always equal to the number of bytes in a token.
  666. $mask = $this->generateRandomKey(StringHelper::byteLength($token));
  667. return StringHelper::base64UrlEncode($mask . ($mask ^ $token));
  668. }
  669. /**
  670. * Unmasks a token previously masked by `maskToken`.
  671. * @param string $maskedToken A masked token.
  672. * @return string An unmasked token, or an empty string in case of token format is invalid.
  673. * @since 2.0.12
  674. */
  675. public function unmaskToken($maskedToken)
  676. {
  677. $decoded = StringHelper::base64UrlDecode($maskedToken);
  678. $length = StringHelper::byteLength($decoded) / 2;
  679. // Check if the masked token has an even length.
  680. if (!is_int($length)) {
  681. return '';
  682. }
  683. return StringHelper::byteSubstr($decoded, $length, $length) ^ StringHelper::byteSubstr($decoded, 0, $length);
  684. }
  685. }