Security.php 32 KB

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