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