Completed
Push — better-test-security ( 49028a...e94b68 )
by Carsten
08:39
created

Security   D

Complexity

Total Complexity 98

Size/Duplication

Total Lines 671
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 68.62%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 98
c 5
b 0
f 0
lcom 1
cbo 5
dl 0
loc 671
ccs 164
cts 239
cp 0.6862
rs 4.5755

16 Methods

Rating   Name   Duplication   Size   Complexity  
A encryptByPassword() 0 4 1
A encryptByKey() 0 4 1
A decryptByPassword() 0 4 1
A decryptByKey() 0 4 1
B encrypt() 0 36 5
B decrypt() 0 34 6
C hkdf() 0 32 11
C pbkdf2() 0 46 16
A hashData() 0 8 2
A validateData() 0 19 4
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
F generateRandomKey() 0 101 29

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