Completed
Push — security-enhancements ( 371440 )
by Alexander
08:04
created

Security   D

Complexity

Total Complexity 98

Size/Duplication

Total Lines 672
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 43.28%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 98
c 2
b 0
f 0
lcom 1
cbo 5
dl 0
loc 672
ccs 103
cts 238
cp 0.4328
rs 4.5711

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

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
461
            $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
0 ignored issues
show
Documentation introduced by
The property _useLibreSSL does not exist on object<yii\base\Security>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
462
                && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
463
                && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
464
        }
465
466
        // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
467
        // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
468
        if ($this->_useLibreSSL
0 ignored issues
show
Documentation introduced by
The property _useLibreSSL does not exist on object<yii\base\Security>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

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