Completed
Push — security-urandom ( 65ea50 )
by Carsten
06:32
created

Security   D

Complexity

Total Complexity 104

Size/Duplication

Total Lines 701
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 51.37%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 104
c 4
b 3
f 0
lcom 1
cbo 5
dl 0
loc 701
ccs 131
cts 255
cp 0.5137
rs 4.4444

16 Methods

Rating   Name   Duplication   Size   Complexity  
A encryptByPassword() 0 4 1
A encryptByKey() 0 4 1
B decrypt() 0 34 6
A decryptByPassword() 0 4 1
A decryptByKey() 0 4 1
B encrypt() 0 36 5
C hkdf() 0 32 11
C pbkdf2() 0 46 16
A hashData() 0 8 2
A validateData() 0 19 4
F generateRandomKey() 0 126 35
A generateRandomString() 0 15 3
B generatePasswordHash() 0 20 5
C validatePassword() 0 25 8
A generateSalt() 0 16 3
A compareString() 0 12 2

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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use yii\helpers\StringHelper;
11
use Yii;
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
 * @author Qiang Xue <[email protected]>
27
 * @author Tom Worster <[email protected]>
28
 * @author Klimov Paul <[email protected]>
29
 * @since 2.0
30
 */
31
class Security extends Component
32
{
33
    /**
34
     * @var string The cipher to use for encryption and decryption.
35
     */
36
    public $cipher = 'AES-128-CBC';
37
    /**
38
     * @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher.
39
     *
40
     * In each element, the key is one of the ciphers supported by OpenSSL (@see openssl_get_cipher_methods()).
41
     * The value is an array of two integers, the first is the cipher's block size in bytes and the second is
42
     * the key size in bytes.
43
     *
44
     * > Warning: All OpenSSL ciphers that we recommend are in the default value, i.e. AES in CBC mode.
45
     *
46
     * > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key
47
     * derivation salt.
48
     */
49
    public $allowedCiphers = [
50
        'AES-128-CBC' => [16, 16],
51
        'AES-192-CBC' => [16, 24],
52
        'AES-256-CBC' => [16, 32],
53
    ];
54
    /**
55
     * @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
56
     * @see hash_algos()
57
     */
58
    public $kdfHash = 'sha256';
59
    /**
60
     * @var string Hash algorithm for message authentication. Recommend sha256, sha384 or sha512.
61
     * @see hash_algos()
62
     */
63
    public $macHash = 'sha256';
64
    /**
65
     * @var string HKDF info value for derivation of message authentication key.
66
     * @see hkdf()
67
     */
68
    public $authKeyInfo = 'AuthorizationKey';
69
    /**
70
     * @var integer derivation iterations count.
71
     * Set as high as possible to hinder dictionary password attacks.
72
     */
73
    public $derivationIterations = 100000;
74
    /**
75
     * @var string strategy, which should be used to generate password hash.
76
     * Available strategies:
77
     * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
78
     *   This option is recommended, but it requires PHP version >= 5.5.0
79
     * - 'crypt' - use PHP `crypt()` function.
80
     * @deprecated Since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
81
     * uses `password_hash()` when available or `crypt()` when not.
82
     */
83
    public $passwordHashStrategy;
84
    /**
85
     * @var integer Default cost used for password hashing.
86
     * Allowed value is between 4 and 31.
87
     * @see generatePasswordHash()
88
     * @since 2.0.6
89
     */
90
    public $passwordHashCost = 13;
91
92
    /**
93
     * @var resource|string|null Identifies the random source of the last successful call of [[generateRandomKey]].
94
     * Caches the file pointer to /dev/urandom if it was fopened.
95
     */
96
    private $_randomSource;
97
98
    /**
99
     * Encrypts data using a password.
100
     * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
101
     * which is deliberately slow to protect against dictionary attacks. Use [[encryptByKey()]] to
102
     * encrypt fast using a cryptographic key rather than a password. Key derivation time is
103
     * determined by [[$derivationIterations]], which should be set as high as possible.
104
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
105
     * to hash input or output data.
106
     * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
107
     * poor-quality or compromised passwords.
108
     * @param string $data the data to encrypt
109
     * @param string $password the password to use for encryption
110
     * @return string the encrypted data
111
     * @see decryptByPassword()
112
     * @see encryptByKey()
113
     */
114 1
    public function encryptByPassword($data, $password)
115
    {
116 1
        return $this->encrypt($data, true, $password, null);
117
    }
118
119
    /**
120
     * Encrypts data using a cryptographic key.
121
     * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
122
     * which is very fast relative to [[encryptByPassword()]]. The input key must be properly
123
     * random -- use [[generateRandomKey()]] to generate keys.
124
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
125
     * to hash input or output data.
126
     * @param string $data the data to encrypt
127
     * @param string $inputKey the input to use for encryption and authentication
128
     * @param string $info optional context and application specific information, see [[hkdf()]]
129
     * @return string the encrypted data
130
     * @see decryptByKey()
131
     * @see encryptByPassword()
132
     */
133 1
    public function encryptByKey($data, $inputKey, $info = null)
134
    {
135 1
        return $this->encrypt($data, false, $inputKey, $info);
136
    }
137
138
    /**
139
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
140
     * @param string $data the encrypted data to decrypt
141
     * @param string $password the password to use for decryption
142
     * @return bool|string the decrypted data or false on authentication failure
143
     * @see encryptByPassword()
144
     */
145 10
    public function decryptByPassword($data, $password)
146
    {
147 10
        return $this->decrypt($data, true, $password, null);
148
    }
149
150
    /**
151
     * Verifies and decrypts data encrypted with [[encryptByPassword()]].
152
     * @param string $data the encrypted data to decrypt
153
     * @param string $inputKey the input to use for encryption and authentication
154
     * @param string $info optional context and application specific information, see [[hkdf()]]
155
     * @return bool|string the decrypted data or false on authentication failure
156
     * @see encryptByKey()
157
     */
158 10
    public function decryptByKey($data, $inputKey, $info = null)
159
    {
160 10
        return $this->decrypt($data, false, $inputKey, $info);
161
    }
162
163
    /**
164
     * Encrypts data.
165
     *
166
     * @param string $data data to be encrypted
167
     * @param boolean $passwordBased set true to use password-based key derivation
168
     * @param string $secret the encryption password or key
169
     * @param string $info context/application specific information, e.g. a user ID
170
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
171
     *
172
     * @return string the encrypted data
173
     * @throws InvalidConfigException on OpenSSL not loaded
174
     * @throws Exception on OpenSSL error
175
     * @see decrypt()
176
     */
177 2
    protected function encrypt($data, $passwordBased, $secret, $info)
178
    {
179 2
        if (!extension_loaded('openssl')) {
180
            throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
181
        }
182 2
        if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
183
            throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
184
        }
185
186 2
        list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
187
188 2
        $keySalt = $this->generateRandomKey($keySize);
189 2
        if ($passwordBased) {
190 1
            $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
191 1
        } else {
192 1
            $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
193
        }
194
195 2
        $iv = $this->generateRandomKey($blockSize);
196
197 2
        $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
198 2
        if ($encrypted === false) {
199
            throw new \yii\base\Exception('OpenSSL failure on encryption: ' . openssl_error_string());
200
        }
201
202 2
        $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
203 2
        $hashed = $this->hashData($iv . $encrypted, $authKey);
204
205
        /*
206
         * Output: [keySalt][MAC][IV][ciphertext]
207
         * - keySalt is KEY_SIZE bytes long
208
         * - MAC: message authentication code, length same as the output of MAC_HASH
209
         * - IV: initialization vector, length $blockSize
210
         */
211 2
        return $keySalt . $hashed;
212
    }
213
214
    /**
215
     * Decrypts data.
216
     *
217
     * @param string $data encrypted data to be decrypted.
218
     * @param boolean $passwordBased set true to use password-based key derivation
219
     * @param string $secret the decryption password or key
220
     * @param string $info context/application specific information, @see encrypt()
221
     *
222
     * @return bool|string the decrypted data or false on authentication failure
223
     * @throws InvalidConfigException on OpenSSL not loaded
224
     * @throws Exception on OpenSSL error
225
     * @see encrypt()
226
     */
227 20
    protected function decrypt($data, $passwordBased, $secret, $info)
228
    {
229 20
        if (!extension_loaded('openssl')) {
230
            throw new InvalidConfigException('Encryption requires the OpenSSL PHP extension');
231
        }
232 20
        if (!isset($this->allowedCiphers[$this->cipher][0], $this->allowedCiphers[$this->cipher][1])) {
233
            throw new InvalidConfigException($this->cipher . ' is not an allowed cipher');
234
        }
235
236 20
        list($blockSize, $keySize) = $this->allowedCiphers[$this->cipher];
237
238 20
        $keySalt = StringHelper::byteSubstr($data, 0, $keySize);
239 20
        if ($passwordBased) {
240 10
            $key = $this->pbkdf2($this->kdfHash, $secret, $keySalt, $this->derivationIterations, $keySize);
241 10
        } else {
242 10
            $key = $this->hkdf($this->kdfHash, $secret, $keySalt, $info, $keySize);
243
        }
244
245 20
        $authKey = $this->hkdf($this->kdfHash, $key, null, $this->authKeyInfo, $keySize);
246 20
        $data = $this->validateData(StringHelper::byteSubstr($data, $keySize, null), $authKey);
247 20
        if ($data === false) {
248 2
            return false;
249
        }
250
251 20
        $iv = StringHelper::byteSubstr($data, 0, $blockSize);
252 20
        $encrypted = StringHelper::byteSubstr($data, $blockSize, null);
253
254 20
        $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
255 20
        if ($decrypted === false) {
256
            throw new \yii\base\Exception('OpenSSL failure on decryption: ' . openssl_error_string());
257
        }
258
259 20
        return $decrypted;
260
    }
261
262
    /**
263
     * Derives a key from the given input key using the standard HKDF algorithm.
264
     * Implements HKDF specified in [RFC 5869](https://tools.ietf.org/html/rfc5869).
265
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
266
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
267
     * @param string $inputKey the source key
268
     * @param string $salt the random salt
269
     * @param string $info optional info to bind the derived key material to application-
270
     * and context-specific information, e.g. a user ID or API version, see
271
     * [RFC 5869](https://tools.ietf.org/html/rfc5869)
272
     * @param integer $length length of the output key in bytes. If 0, the output key is
273
     * the length of the hash algorithm output.
274
     * @throws InvalidParamException when HMAC generation fails.
275
     * @return string the derived key
276
     */
277 27
    public function hkdf($algo, $inputKey, $salt = null, $info = null, $length = 0)
278
    {
279 27
        $test = @hash_hmac($algo, '', '', true);
280 27
        if (!$test) {
281
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
282
        }
283 27
        $hashLength = StringHelper::byteLength($test);
284 27
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
285
            $length = (int) $length;
286
        }
287 27
        if (!is_int($length) || $length < 0 || $length > 255 * $hashLength) {
288
            throw new InvalidParamException('Invalid length');
289
        }
290 27
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
291
292 27
        if ($salt === null) {
293 20
            $salt = str_repeat("\0", $hashLength);
294 20
        }
295 27
        $prKey = hash_hmac($algo, $inputKey, $salt, true);
296
297 27
        $hmac = '';
298 27
        $outputKey = '';
299 27
        for ($i = 1; $i <= $blocks; $i++) {
300 27
            $hmac = hash_hmac($algo, $hmac . $info . chr($i), $prKey, true);
301 27
            $outputKey .= $hmac;
302 27
        }
303
304 27
        if ($length !== 0) {
305 27
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
306 27
        }
307 27
        return $outputKey;
308
    }
309
310
    /**
311
     * Derives a key from the given password using the standard PBKDF2 algorithm.
312
     * Implements HKDF2 specified in [RFC 2898](http://tools.ietf.org/html/rfc2898#section-5.2)
313
     * Recommend use one of the SHA-2 hash algorithms: sha224, sha256, sha384 or sha512.
314
     * @param string $algo a hash algorithm supported by `hash_hmac()`, e.g. 'SHA-256'
315
     * @param string $password the source password
316
     * @param string $salt the random salt
317
     * @param integer $iterations the number of iterations of the hash algorithm. Set as high as
318
     * possible to hinder dictionary password attacks.
319
     * @param integer $length length of the output key in bytes. If 0, the output key is
320
     * the length of the hash algorithm output.
321
     * @return string the derived key
322
     * @throws InvalidParamException when hash generation fails due to invalid params given.
323
     */
324 19
    public function pbkdf2($algo, $password, $salt, $iterations, $length = 0)
325
    {
326 19
        if (function_exists('hash_pbkdf2')) {
327 19
            $outputKey = hash_pbkdf2($algo, $password, $salt, $iterations, $length, true);
328 19
            if ($outputKey === false) {
329
                throw new InvalidParamException('Invalid parameters to hash_pbkdf2()');
330
            }
331 19
            return $outputKey;
332
        }
333
334
        // todo: is there a nice way to reduce the code repetition in hkdf() and pbkdf2()?
335
        $test = @hash_hmac($algo, '', '', true);
336
        if (!$test) {
337
            throw new InvalidParamException('Failed to generate HMAC with hash algorithm: ' . $algo);
338
        }
339
        if (is_string($iterations) && preg_match('{^\d{1,16}$}', $iterations)) {
340
            $iterations = (int) $iterations;
341
        }
342
        if (!is_int($iterations) || $iterations < 1) {
343
            throw new InvalidParamException('Invalid iterations');
344
        }
345
        if (is_string($length) && preg_match('{^\d{1,16}$}', $length)) {
346
            $length = (int) $length;
347
        }
348
        if (!is_int($length) || $length < 0) {
349
            throw new InvalidParamException('Invalid length');
350
        }
351
        $hashLength = StringHelper::byteLength($test);
352
        $blocks = $length !== 0 ? ceil($length / $hashLength) : 1;
353
354
        $outputKey = '';
355
        for ($j = 1; $j <= $blocks; $j++) {
356
            $hmac = hash_hmac($algo, $salt . pack('N', $j), $password, true);
357
            $xorsum = $hmac;
358
            for ($i = 1; $i < $iterations; $i++) {
359
                $hmac = hash_hmac($algo, $hmac, $password, true);
360
                $xorsum ^= $hmac;
361
            }
362
            $outputKey .= $xorsum;
363
        }
364
365
        if ($length !== 0) {
366
            $outputKey = StringHelper::byteSubstr($outputKey, 0, $length);
367
        }
368
        return $outputKey;
369
    }
370
371
    /**
372
     * Prefixes data with a keyed hash value so that it can later be detected if it is tampered.
373
     * There is no need to hash inputs or outputs of [[encryptByKey()]] or [[encryptByPassword()]]
374
     * as those methods perform the task.
375
     * @param string $data the data to be protected
376
     * @param string $key the secret key to be used for generating hash. Should be a secure
377
     * cryptographic key.
378
     * @param boolean $rawHash whether the generated hash value is in raw binary format. If false, lowercase
379
     * hex digits will be generated.
380
     * @return string the data prefixed with the keyed hash
381
     * @throws InvalidConfigException when HMAC generation fails.
382
     * @see validateData()
383
     * @see generateRandomKey()
384
     * @see hkdf()
385
     * @see pbkdf2()
386
     */
387 3
    public function hashData($data, $key, $rawHash = false)
388
    {
389 3
        $hash = hash_hmac($this->macHash, $data, $key, $rawHash);
390 3
        if (!$hash) {
391
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
392
        }
393 3
        return $hash . $data;
394
    }
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 boolean $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 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 21
    public function validateData($data, $key, $rawHash = false)
412
    {
413 21
        $test = @hash_hmac($this->macHash, '', '', $rawHash);
414 21
        if (!$test) {
415
            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
416
        }
417 21
        $hashLength = StringHelper::byteLength($test);
418 21
        if (StringHelper::byteLength($data) >= $hashLength) {
419 21
            $hash = StringHelper::byteSubstr($data, 0, $hashLength);
420 21
            $pureData = StringHelper::byteSubstr($data, $hashLength, null);
421
422 21
            $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash);
423
424 21
            if ($this->compareString($hash, $calculatedHash)) {
425 21
                return $pureData;
426
            }
427 3
        }
428 3
        return false;
429
    }
430
431
    /**
432
     * Generates specified number of random bytes.
433
     * Note that output may not be ASCII.
434
     * @see generateRandomString() if you need a string.
435
     *
436
     * @param integer $length the number of bytes to generate
437
     * @return string the generated random bytes
438
     * @throws InvalidConfigException if OpenSSL extension is required (e.g. on Windows) but not installed.
439
     * @throws Exception on failure.
440
     */
441 23
    public function generateRandomKey($length = 32)
442
    {
443 23
        if (function_exists('random_bytes')) {
444
            return random_bytes($length);
445
        }
446
447 23
        if (!is_int($length)) {
448
            throw new InvalidParamException('First parameter ($length) must be an integer');
449
        }
450
451 23
        if ($length < 1) {
452
            throw new InvalidParamException('First parameter ($length) must be greater than 0');
453
        }
454
455
        // The recent LibreSSL RNGs are faster and better than /dev/urandom.
456
        // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
457
        // https://bugs.php.net/bug.php?id=71143
458 23
        if ($this->_randomSource === 'LibreSSL'
459 23
            || ($this->_randomSource === null
460 23
                && defined('OPENSSL_VERSION_TEXT')
461 23
                && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
462 23
                && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105)
0 ignored issues
show
Bug introduced by
The variable $matches does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
463 23
        ) {
464
            $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
465
            if ($cryptoStrong === false) {
466
                throw new Exception(
467
                    'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
468
                );
469
            }
470
            if ($key !== false && StringHelper::byteLength($key) === $length) {
471
                $this->_randomSource = 'LibreSSL';
472
473
                return $key;
474
            }
475
476
            $this->_randomSource = null;
477
        }
478
479
        // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
480
        // CrypGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
481 23
        if ($this->_randomSource === 'mcrypt'
482 23
            || ($this->_randomSource === null
483 23
                && PHP_VERSION_ID >= 50307
484 23
                && function_exists('mcrypt_create_iv'))
485 23
        ) {
486 23
            $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
487 23
            if (StringHelper::byteLength($key) === $length) {
488 23
                $this->_randomSource = 'mcrypt';
489
490 23
                return $key;
491
            }
492
493
            $this->_randomSource = null;
494
        }
495
496
        // If not on Windows, try reading from /dev/urandom device. If successful, cache
497
        // the file pointer in $this->_randomSource.
498
        if (is_resource($this->_randomSource)
499
            || ($this->_randomSource === null
500
                && DIRECTORY_SEPARATOR === '/'
501
                && @is_readable('/dev/urandom'))
502
        ) {
503
            // Either open /dev/urandom or get the cached file pointer.
504
            if (is_resource($this->_randomSource)) {
505
                $urandomFile = $this->_randomSource;
506
            } else {
507
                $urandomFile = fopen('/dev/urandom', 'rb');
508
                if ($urandomFile) {
509
                    // Check the file's inode protection mode is 'character special'.
510
                    // NOTE: octal integer literals!
511
                    $fstat = fstat($urandomFile);
512
                    if (($fstat['mode'] & 0170000) !== 020000) {
513
                        fclose($urandomFile);
514
                        $urandomFile = null;
515
                    }
516
                } else {
517
                    $urandomFile = null;
518
                }
519
            }
520
521
            if ($urandomFile !== null) {
522
                // $length could be large so read using a loop.
523
                $key = '';
524
                $bytesLeft = $length;
525
                do {
526
                    $buffer = fread($urandomFile, min($bytesLeft, 8092));
527
                    if (!$buffer) {
528
                        $key = null;
529
                        break;
530
                    }
531
                    $key .= $buffer;
532
                    $bytesLeft = $length - StringHelper::byteLength($key);
533
                } while ($bytesLeft > 0);
534
535
                if ($key !== null && StringHelper::byteLength($key) === $length) {
536
                    $this->_randomSource = $urandomFile;
537
538
                    return $key;
539
                }
540
            }
541
542
            $this->_randomSource = null;
543
        }
544
545
        // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
546
        // of using OpenSSL library. Don't use OpenSSL on other platforms.
547
        if ($this->_randomSource === 'OpenSSL'
548
            || (DIRECTORY_SEPARATOR !== '/' && PHP_VERSION_ID >= 50400)
549
        ) {
550
            $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
551
            if ($cryptoStrong === false) {
552
                throw new Exception(
553
                    'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
554
                );
555
            }
556
            if ($key !== false && StringHelper::byteLength($key) === $length) {
557
                $this->_randomSource = 'OpenSSL';
558
559
                return $key;
560
            }
561
562
            $this->_randomSource = null;
563
        }
564
565
        throw new Exception('Unable to generate a random key');
566
    }
567
568
    /**
569
     * Generates a random string of specified length.
570
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
571
     *
572
     * @param integer $length the length of the key in characters
573
     * @return string the generated random key
574
     * @throws InvalidConfigException if OpenSSL extension is needed but not installed.
575
     * @throws Exception on failure.
576
     */
577 20
    public function generateRandomString($length = 32)
578
    {
579 20
        if (!is_int($length)) {
580
            throw new InvalidParamException('First parameter ($length) must be an integer');
581
        }
582
583 20
        if ($length < 1) {
584
            throw new InvalidParamException('First parameter ($length) must be greater than 0');
585
        }
586
587 20
        $bytes = $this->generateRandomKey($length);
588
        // '=' character(s) returned by base64_encode() are always discarded because
589
        // they are guaranteed to be after position $length in the base64_encode() output.
590 20
        return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
591
    }
592
593
    /**
594
     * Generates a secure hash from a password and a random salt.
595
     *
596
     * The generated hash can be stored in database.
597
     * Later when a password needs to be validated, the hash can be fetched and passed
598
     * to [[validatePassword()]]. For example,
599
     *
600
     * ```php
601
     * // generates the hash (usually done during user registration or when the password is changed)
602
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
603
     * // ...save $hash in database...
604
     *
605
     * // during login, validate if the password entered is correct using $hash fetched from database
606
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
607
     *     // password is good
608
     * } else {
609
     *     // password is bad
610
     * }
611
     * ```
612
     *
613
     * @param string $password The password to be hashed.
614
     * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
615
     * The higher the value of cost,
616
     * the longer it takes to generate the hash and to verify a password against it. Higher cost
617
     * therefore slows down a brute-force attack. For best protection against brute-force attacks,
618
     * set it to the highest value that is tolerable on production servers. The time taken to
619
     * compute the hash doubles for every increment by one of $cost.
620
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
621
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
622
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
623
     * @throws Exception on bad password parameter or cost parameter.
624
     * @throws InvalidConfigException when an unsupported password hash strategy is configured.
625
     * @see validatePassword()
626
     */
627 1
    public function generatePasswordHash($password, $cost = null)
628
    {
629 1
        if ($cost === null) {
630 1
            $cost = $this->passwordHashCost;
631 1
        }
632
633 1
        if (function_exists('password_hash')) {
634
            /** @noinspection PhpUndefinedConstantInspection */
635 1
            return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
636
        }
637
638
        $salt = $this->generateSalt($cost);
639
        $hash = crypt($password, $salt);
640
        // strlen() is safe since crypt() returns only ascii
641
        if (!is_string($hash) || strlen($hash) !== 60) {
642
            throw new Exception('Unknown error occurred while generating hash.');
643
        }
644
645
        return $hash;
646
    }
647
648
    /**
649
     * Verifies a password against a hash.
650
     * @param string $password The password to verify.
651
     * @param string $hash The hash to verify the password against.
652
     * @return boolean whether the password is correct.
653
     * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
654
     * @throws InvalidConfigException when an unsupported password hash strategy is configured.
655
     * @see generatePasswordHash()
656
     */
657 1
    public function validatePassword($password, $hash)
658
    {
659 1
        if (!is_string($password) || $password === '') {
660
            throw new InvalidParamException('Password must be a string and cannot be empty.');
661
        }
662
663 1
        if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
664 1
            || $matches[1] < 4
665 1
            || $matches[1] > 30
666 1
        ) {
667
            throw new InvalidParamException('Hash is invalid.');
668
        }
669
670 1
        if (function_exists('password_verify')) {
671 1
            return password_verify($password, $hash);
672
        }
673
674
        $test = crypt($password, $hash);
675
        $n = strlen($test);
676
        if ($n !== 60) {
677
            return false;
678
        }
679
680
        return $this->compareString($test, $hash);
681
    }
682
683
    /**
684
     * Generates a salt that can be used to generate a password hash.
685
     *
686
     * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
687
     * requires, for the Blowfish hash algorithm, a salt string in a specific format:
688
     * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
689
     * from the alphabet "./0-9A-Za-z".
690
     *
691
     * @param integer $cost the cost parameter
692
     * @return string the random salt value.
693
     * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
694
     */
695
    protected function generateSalt($cost = 13)
696
    {
697
        $cost = (int) $cost;
698
        if ($cost < 4 || $cost > 31) {
699
            throw new InvalidParamException('Cost must be between 4 and 31.');
700
        }
701
702
        // Get a 20-byte random string
703
        $rand = $this->generateRandomKey(20);
704
        // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
705
        $salt = sprintf("$2y$%02d$", $cost);
706
        // Append the random salt data in the required base64 format.
707
        $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));
708
709
        return $salt;
710
    }
711
712
    /**
713
     * Performs string comparison using timing attack resistant approach.
714
     * @see http://codereview.stackexchange.com/questions/13512
715
     * @param string $expected string to compare.
716
     * @param string $actual user-supplied string.
717
     * @return boolean whether strings are equal.
718
     */
719 41
    public function compareString($expected, $actual)
720
    {
721 41
        $expected .= "\0";
722 41
        $actual .= "\0";
723 41
        $expectedLength = StringHelper::byteLength($expected);
724 41
        $actualLength = StringHelper::byteLength($actual);
725 41
        $diff = $expectedLength - $actualLength;
726 41
        for ($i = 0; $i < $actualLength; $i++) {
727 41
            $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
728 41
        }
729 41
        return $diff === 0;
730
    }
731
}
732