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 |
||
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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) |
|
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 | 34 | public function generateRandomKey($length = 32) |
|
440 | { |
||
441 | 34 | if (function_exists('random_bytes')) { |
|
442 | return random_bytes($length); |
||
443 | } |
||
444 | |||
445 | 34 | if (!is_int($length)) { |
|
446 | 3 | throw new InvalidParamException('First parameter ($length) must be an integer'); |
|
447 | } |
||
448 | |||
449 | 31 | if ($length < 1) { |
|
450 | 2 | throw new InvalidParamException('First parameter ($length) must be greater than 0'); |
|
451 | } |
||
452 | |||
453 | // The recent LibreSSL RNGs are faster and likely better than /dev/urandom. |
||
454 | // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL. |
||
455 | // https://bugs.php.net/bug.php?id=71143 |
||
456 | 29 | if ($this->_useLibreSSL === null) { |
|
457 | 29 | $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT') |
|
458 | 29 | && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches) |
|
459 | 29 | && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105; |
|
460 | 29 | } |
|
461 | |||
462 | // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead |
||
463 | // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows. |
||
464 | 29 | if ($this->_useLibreSSL |
|
465 | || ( |
||
466 | 29 | DIRECTORY_SEPARATOR !== '/' |
|
467 | 29 | && substr_compare(PHP_OS, 'win', 0, 3, true) === 0 |
|
468 | 29 | && function_exists('openssl_random_pseudo_bytes') |
|
469 | ) |
||
470 | 29 | ) { |
|
471 | $key = openssl_random_pseudo_bytes($length, $cryptoStrong); |
||
472 | if ($cryptoStrong === false) { |
||
473 | throw new Exception( |
||
474 | 'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.' |
||
475 | ); |
||
476 | } |
||
477 | if ($key !== false && StringHelper::byteLength($key) === $length) { |
||
478 | return $key; |
||
479 | } |
||
480 | } |
||
481 | |||
482 | // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads |
||
483 | // CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom. |
||
484 | 29 | if (function_exists('mcrypt_create_iv')) { |
|
485 | 27 | $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); |
|
486 | 27 | if (StringHelper::byteLength($key) === $length) { |
|
487 | 27 | return $key; |
|
488 | } |
||
489 | } |
||
490 | |||
491 | // If not on Windows, try to open a random device. |
||
492 | 2 | if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') { |
|
493 | // urandom is a symlink to random on FreeBSD. |
||
494 | 2 | $device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom'; |
|
495 | // Check random device for special character device protection mode. Use lstat() |
||
496 | // instead of stat() in case an attacker arranges a symlink to a fake device. |
||
497 | 2 | $lstat = @lstat($device); |
|
498 | 2 | if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) { |
|
499 | 2 | $this->_randomFile = fopen($device, 'rb') ?: null; |
|
500 | |||
501 | 2 | if (is_resource($this->_randomFile)) { |
|
502 | // Reduce PHP stream buffer from default 8192 bytes to optimize data |
||
503 | // transfer from the random device for smaller values of $length. |
||
504 | // This also helps to keep future randoms out of user memory space. |
||
505 | 2 | $bufferSize = 8; |
|
506 | |||
507 | 2 | if (function_exists('stream_set_read_buffer')) { |
|
508 | 2 | stream_set_read_buffer($this->_randomFile, $bufferSize); |
|
509 | 2 | } |
|
510 | // stream_set_read_buffer() isn't implemented on HHVM |
||
511 | 2 | if (function_exists('stream_set_chunk_size')) { |
|
512 | 2 | stream_set_chunk_size($this->_randomFile, $bufferSize); |
|
513 | 2 | } |
|
514 | 2 | } |
|
515 | 2 | } |
|
516 | 2 | } |
|
517 | |||
518 | 2 | if (is_resource($this->_randomFile)) { |
|
519 | 2 | $buffer = ''; |
|
520 | 2 | $stillNeed = $length; |
|
521 | 2 | while ($stillNeed > 0) { |
|
522 | 2 | $someBytes = fread($this->_randomFile, $stillNeed); |
|
523 | 2 | if ($someBytes === false) { |
|
524 | break; |
||
525 | } |
||
526 | 2 | $buffer .= $someBytes; |
|
527 | 2 | $stillNeed -= StringHelper::byteLength($buffer); |
|
528 | 2 | if ($stillNeed === 0) { |
|
529 | // Leaving file pointer open in order to make next generation faster by reusing it. |
||
530 | 2 | return $buffer; |
|
531 | } |
||
532 | } |
||
533 | fclose($this->_randomFile); |
||
534 | $this->_randomFile = null; |
||
535 | } |
||
536 | |||
537 | throw new Exception('Unable to generate a random key'); |
||
538 | } |
||
539 | |||
540 | /** |
||
541 | * Generates a random string of specified length. |
||
542 | * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding. |
||
543 | * |
||
544 | * @param integer $length the length of the key in characters |
||
545 | * @return string the generated random key |
||
546 | * @throws Exception on failure. |
||
547 | */ |
||
548 | 23 | public function generateRandomString($length = 32) |
|
563 | |||
564 | /** |
||
565 | * Generates a secure hash from a password and a random salt. |
||
566 | * |
||
567 | * The generated hash can be stored in database. |
||
568 | * Later when a password needs to be validated, the hash can be fetched and passed |
||
569 | * to [[validatePassword()]]. For example, |
||
570 | * |
||
571 | * ```php |
||
572 | * // generates the hash (usually done during user registration or when the password is changed) |
||
573 | * $hash = Yii::$app->getSecurity()->generatePasswordHash($password); |
||
574 | * // ...save $hash in database... |
||
575 | * |
||
576 | * // during login, validate if the password entered is correct using $hash fetched from database |
||
577 | * if (Yii::$app->getSecurity()->validatePassword($password, $hash) { |
||
578 | * // password is good |
||
579 | * } else { |
||
580 | * // password is bad |
||
581 | * } |
||
582 | * ``` |
||
583 | * |
||
584 | * @param string $password The password to be hashed. |
||
585 | * @param integer $cost Cost parameter used by the Blowfish hash algorithm. |
||
586 | * The higher the value of cost, |
||
587 | * the longer it takes to generate the hash and to verify a password against it. Higher cost |
||
588 | * therefore slows down a brute-force attack. For best protection against brute-force attacks, |
||
589 | * set it to the highest value that is tolerable on production servers. The time taken to |
||
590 | * compute the hash doubles for every increment by one of $cost. |
||
591 | * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt', |
||
592 | * the output is always 60 ASCII characters, when set to 'password_hash' the output length |
||
593 | * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php) |
||
594 | * @throws Exception on bad password parameter or cost parameter. |
||
595 | * @see validatePassword() |
||
596 | */ |
||
597 | 1 | public function generatePasswordHash($password, $cost = null) |
|
617 | |||
618 | /** |
||
619 | * Verifies a password against a hash. |
||
620 | * @param string $password The password to verify. |
||
621 | * @param string $hash The hash to verify the password against. |
||
622 | * @return boolean whether the password is correct. |
||
623 | * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available. |
||
624 | * @see generatePasswordHash() |
||
625 | */ |
||
626 | 1 | public function validatePassword($password, $hash) |
|
651 | |||
652 | /** |
||
653 | * Generates a salt that can be used to generate a password hash. |
||
654 | * |
||
655 | * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function |
||
656 | * requires, for the Blowfish hash algorithm, a salt string in a specific format: |
||
657 | * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters |
||
658 | * from the alphabet "./0-9A-Za-z". |
||
659 | * |
||
660 | * @param integer $cost the cost parameter |
||
661 | * @return string the random salt value. |
||
662 | * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31. |
||
663 | */ |
||
664 | protected function generateSalt($cost = 13) |
||
680 | |||
681 | /** |
||
682 | * Performs string comparison using timing attack resistant approach. |
||
683 | * @see http://codereview.stackexchange.com/questions/13512 |
||
684 | * @param string $expected string to compare. |
||
685 | * @param string $actual user-supplied string. |
||
686 | * @return boolean whether strings are equal. |
||
687 | */ |
||
688 | 41 | public function compareString($expected, $actual) |
|
700 | } |
||
701 |