Passed
Pull Request — master (#19669)
by
unknown
09:49
created

Security   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 660
Duplicated Lines 0 %

Test Coverage

Coverage 52.58%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 190
c 1
b 0
f 0
dl 0
loc 660
ccs 102
cts 194
cp 0.5258
rs 2
wmc 86

19 Methods

Rating   Name   Duplication   Size   Complexity  
A decryptByPassword() 0 3 1
A shouldUseLibreSSL() 0 11 4
A encryptByPassword() 0 3 1
A encryptByKey() 0 3 1
A decryptByKey() 0 3 1
A generatePasswordHash() 0 19 5
A compareString() 0 24 5
A hashData() 0 8 2
B decrypt() 0 33 6
C hkdf() 0 41 13
B validatePassword() 0 24 8
A generateRandomKey() 0 11 3
A generateRandomString() 0 12 3
A maskToken() 0 5 1
A generateSalt() 0 15 3
C pbkdf2() 0 47 17
A unmaskToken() 0 10 2
A encrypt() 0 36 6
A validateData() 0 19 4

How to fix   Complexity   

Complex Class

Complex classes like Security often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Security, and based on these observations, apply Extract Interface, too.

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