Security::compareString()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 12.4085

Importance

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