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