8ec727c1
曹明
初始化代码提交
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\validators;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\JsExpression;
/**
* The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.
*
* It also may change attribute's value if normalization of IPv6 expansion is enabled.
*
* The following are examples of validation rules using this validator:
*
* ```php
* ['ip_address', 'ip'], // IPv4 or IPv6 address
* ['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
* ['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
* ['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
* ['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
* ['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
* ['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
* ['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
* ```
*
* @property array $ranges The IPv4 or IPv6 ranges that are allowed or forbidden. See [[setRanges()]] for
* detailed description.
*
* @author Dmitry Naumenko <d.naumenko.a@gmail.com>
* @since 2.0.7
*/
class IpValidator extends Validator
{
/**
* The length of IPv6 address in bits
*/
const IPV6_ADDRESS_LENGTH = 128;
/**
* The length of IPv4 address in bits
*/
const IPV4_ADDRESS_LENGTH = 32;
/**
* Negation char. Used to negate [[ranges]] or [[networks]]
* or to negate validating value when [[negation]] is set to `true`
* @see negation
* @see networks
* @see ranges
*/
const NEGATION_CHAR = '!';
/**
* @var array The network aliases, that can be used in [[ranges]].
* - key - alias name
* - value - array of strings. String can be an IP range, IP address or another alias. String can be
* negated with [[NEGATION_CHAR]] (independent of `negation` option).
*
* The following aliases are defined by default:
* - `*`: `any`
* - `any`: `0.0.0.0/0, ::/0`
* - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
* - `multicast`: `224.0.0.0/4, ff00::/8`
* - `linklocal`: `169.254.0.0/16, fe80::/10`
* - `localhost`: `127.0.0.0/8', ::1`
* - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
* - `system`: `multicast, linklocal, localhost, documentation`
*
*/
public $networks = [
'*' => ['any'],
'any' => ['0.0.0.0/0', '::/0'],
'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
'multicast' => ['224.0.0.0/4', 'ff00::/8'],
'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
'localhost' => ['127.0.0.0/8', '::1'],
'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
];
/**
* @var bool whether the validating value can be an IPv6 address. Defaults to `true`.
*/
public $ipv6 = true;
/**
* @var bool whether the validating value can be an IPv4 address. Defaults to `true`.
*/
public $ipv4 = true;
/**
* @var bool whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`.
* The following values are possible:
*
* - `false` - the address must not have a subnet (default).
* - `true` - specifying a subnet is required.
* - `null` - specifying a subnet is optional.
*/
public $subnet = false;
/**
* @var bool whether to add the CIDR prefix with the smallest length (32 for IPv4 and 128 for IPv6) to an
* address without it. Works only when `subnet` is not `false`. For example:
* - `10.0.1.5` will normalized to `10.0.1.5/32`
* - `2008:db0::1` will be normalized to `2008:db0::1/128`
* Defaults to `false`.
* @see subnet
*/
public $normalize = false;
/**
* @var bool whether address may have a [[NEGATION_CHAR]] character at the beginning.
* Defaults to `false`.
*/
public $negation = false;
/**
* @var bool whether to expand an IPv6 address to the full notation format.
* Defaults to `false`.
*/
public $expandIPv6 = false;
/**
* @var string Regexp-pattern to validate IPv4 address
*/
public $ipv4Pattern = '/^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9]))$/';
/**
* @var string Regexp-pattern to validate IPv6 address
*/
public $ipv6Pattern = '/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/';
/**
* @var string user-defined error message is used when validation fails due to the wrong IP address format.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*/
public $message;
/**
* @var string user-defined error message is used when validation fails due to the disabled IPv6 validation.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*
* @see ipv6
*/
public $ipv6NotAllowed;
/**
* @var string user-defined error message is used when validation fails due to the disabled IPv4 validation.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*
* @see ipv4
*/
public $ipv4NotAllowed;
/**
* @var string user-defined error message is used when validation fails due to the wrong CIDR.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
* @see subnet
*/
public $wrongCidr;
/**
* @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
* but the CIDR prefix is not set.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*
* @see subnet
*/
public $noSubnet;
/**
* @var string user-defined error message is used when validation fails
* due to [[subnet]] is false, but CIDR prefix is present.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*
* @see subnet
*/
public $hasSubnet;
/**
* @var string user-defined error message is used when validation fails due to IP address
* is not not allowed by [[ranges]] check.
*
* You may use the following placeholders in the message:
*
* - `{attribute}`: the label of the attribute being validated
* - `{value}`: the value of the attribute being validated
*
* @see ranges
*/
public $notInRange;
/**
* @var array
*/
private $_ranges = [];
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if (!$this->ipv4 && !$this->ipv6) {
throw new InvalidConfigException('Both IPv4 and IPv6 checks can not be disabled at the same time');
}
if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} must be a valid IP address.');
}
if ($this->ipv6NotAllowed === null) {
$this->ipv6NotAllowed = Yii::t('yii', '{attribute} must not be an IPv6 address.');
}
if ($this->ipv4NotAllowed === null) {
$this->ipv4NotAllowed = Yii::t('yii', '{attribute} must not be an IPv4 address.');
}
if ($this->wrongCidr === null) {
$this->wrongCidr = Yii::t('yii', '{attribute} contains wrong subnet mask.');
}
if ($this->noSubnet === null) {
$this->noSubnet = Yii::t('yii', '{attribute} must be an IP address with specified subnet.');
}
if ($this->hasSubnet === null) {
$this->hasSubnet = Yii::t('yii', '{attribute} must not be a subnet.');
}
if ($this->notInRange === null) {
$this->notInRange = Yii::t('yii', '{attribute} is not in the allowed range.');
}
}
/**
* Set the IPv4 or IPv6 ranges that are allowed or forbidden.
*
* The following preparation tasks are performed:
*
* - Recursively substitutes aliases (described in [[networks]]) with their values.
* - Removes duplicates
*
* @property array the IPv4 or IPv6 ranges that are allowed or forbidden.
* See [[setRanges()]] for detailed description.
* @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
*
* When the array is empty, or the option not set, all IP addresses are allowed.
*
* Otherwise, the rules are checked sequentially until the first match is found.
* An IP address is forbidden, when it has not matched any of the rules.
*
* Example:
*
* ```php
* [
* 'ranges' => [
* '192.168.10.128'
* '!192.168.10.0/24',
* 'any' // allows any other IP addresses
* ]
* ]
* ```
*
* In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
* IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
*/
public function setRanges($ranges)
{
$this->_ranges = $this->prepareRanges((array) $ranges);
}
/**
* @return array The IPv4 or IPv6 ranges that are allowed or forbidden.
*/
public function getRanges()
{
return $this->_ranges;
}
/**
* @inheritdoc
*/
protected function validateValue($value)
{
$result = $this->validateSubnet($value);
if (is_array($result)) {
$result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
return $result;
} else {
return null;
}
}
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$result = $this->validateSubnet($value);
if (is_array($result)) {
$result[1] = array_merge(['ip' => is_array($value) ? 'array()' : $value], $result[1]);
$this->addError($model, $attribute, $result[0], $result[1]);
} else {
$model->$attribute = $result;
}
}
/**
* Validates an IPv4/IPv6 address or subnet
*
* @param $ip string
* @return string|array
* string - the validation was successful;
* array - an error occurred during the validation.
* Array[0] contains the text of an error, array[1] contains values for the placeholders in the error message
*/
private function validateSubnet($ip)
{
if (!is_string($ip)) {
return [$this->message, []];
}
$negation = null;
$cidr = null;
$isCidrDefault = false;
if (preg_match($this->getIpParsePattern(), $ip, $matches)) {
$negation = ($matches[1] !== '') ? $matches[1] : null;
$ip = $matches[2];
$cidr = isset($matches[4]) ? $matches[4] : null;
}
if ($this->subnet === true && $cidr === null) {
return [$this->noSubnet, []];
}
if ($this->subnet === false && $cidr !== null) {
return [$this->hasSubnet, []];
}
if ($this->negation === false && $negation !== null) {
return [$this->message, []];
}
if ($this->getIpVersion($ip) == 6) {
if ($cidr !== null) {
if ($cidr > static::IPV6_ADDRESS_LENGTH || $cidr < 0) {
return [$this->wrongCidr, []];
}
} else {
$isCidrDefault = true;
$cidr = static::IPV6_ADDRESS_LENGTH;
}
if (!$this->validateIPv6($ip)) {
return [$this->message, []];
}
if (!$this->ipv6) {
return [$this->ipv6NotAllowed, []];
}
if ($this->expandIPv6) {
$ip = $this->expandIPv6($ip);
}
} else {
if ($cidr !== null) {
if ($cidr > static::IPV4_ADDRESS_LENGTH || $cidr < 0) {
return [$this->wrongCidr, []];
}
} else {
$isCidrDefault = true;
$cidr = static::IPV4_ADDRESS_LENGTH;
}
if (!$this->validateIPv4($ip)) {
return [$this->message, []];
}
if (!$this->ipv4) {
return [$this->ipv4NotAllowed, []];
}
}
if (!$this->isAllowed($ip, $cidr)) {
return [$this->notInRange, []];
}
$result = $negation . $ip;
if ($this->subnet !== false && (!$isCidrDefault || $isCidrDefault && $this->normalize)) {
$result .= "/$cidr";
}
return $result;
}
/**
* Expands an IPv6 address to it's full notation. For example `2001:db8::1` will be
* expanded to `2001:0db8:0000:0000:0000:0000:0000:0001`
*
* @param string $ip the original IPv6
* @return string the expanded IPv6
*/
private function expandIPv6($ip)
{
$hex = unpack('H*hex', inet_pton($ip));
return substr(preg_replace('/([a-f0-9]{4})/i', '$1:', $hex['hex']), 0, -1);
}
/**
* The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
*
* @param string $ip
* @param int $cidr
* @return bool
* @see ranges
*/
private function isAllowed($ip, $cidr)
{
if (empty($this->ranges)) {
return true;
}
foreach ($this->ranges as $string) {
list($isNegated, $range) = $this->parseNegatedRange($string);
if ($this->inRange($ip, $cidr, $range)) {
return !$isNegated;
}
}
return false;
}
/**
* Parses IP address/range for the negation with [[NEGATION_CHAR]].
*
* @param $string
* @return array `[0 => bool, 1 => string]`
* - boolean: whether the string is negated
* - string: the string without negation (when the negation were present)
*/
private function parseNegatedRange($string)
{
$isNegated = strpos($string, static::NEGATION_CHAR) === 0;
return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
}
/**
* Prepares array to fill in [[ranges]]:
* - Recursively substitutes aliases, described in [[networks]] with their values
* - Removes duplicates
*
*
* @param $ranges
* @return array
* @see networks
*/
private function prepareRanges($ranges)
{
$result = [];
foreach ($ranges as $string) {
list($isRangeNegated, $range) = $this->parseNegatedRange($string);
if (isset($this->networks[$range])) {
$replacements = $this->prepareRanges($this->networks[$range]);
foreach ($replacements as &$replacement) {
list($isReplacementNegated, $replacement) = $this->parseNegatedRange($replacement);
$result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
}
} else {
$result[] = $string;
}
}
return array_unique($result);
}
/**
* Validates IPv4 address
*
* @param string $value
* @return bool
*/
protected function validateIPv4($value)
{
return preg_match($this->ipv4Pattern, $value) !== 0;
}
/**
* Validates IPv6 address
*
* @param string $value
* @return bool
*/
protected function validateIPv6($value)
{
return preg_match($this->ipv6Pattern, $value) !== 0;
}
/**
* Gets the IP version
*
* @param string $ip
* @return int
*/
private function getIpVersion($ip)
{
return strpos($ip, ':') === false ? 4 : 6;
}
/**
* Used to get the Regexp pattern for initial IP address parsing
* @return string
*/
private function getIpParsePattern()
{
return '/^(' . preg_quote(static::NEGATION_CHAR, '/') . '?)(.+?)(\/(\d+))?$/';
}
/**
* Checks whether the IP is in subnet range
*
* @param string $ip an IPv4 or IPv6 address
* @param int $cidr
* @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
* @return bool
*/
private function inRange($ip, $cidr, $range)
{
$ipVersion = $this->getIpVersion($ip);
$binIp = $this->ip2bin($ip);
$parts = explode('/', $range);
$net = array_shift($parts);
$range_cidr = array_shift($parts);
$netVersion = $this->getIpVersion($net);
if ($ipVersion !== $netVersion) {
return false;
}
if ($range_cidr === null) {
$range_cidr = $netVersion === 4 ? static::IPV4_ADDRESS_LENGTH : static::IPV6_ADDRESS_LENGTH;
}
$binNet = $this->ip2bin($net);
return substr($binIp, 0, $range_cidr) === substr($binNet, 0, $range_cidr) && $cidr >= $range_cidr;
}
/**
* Converts IP address to bits representation
*
* @param string $ip
* @return string bits as a string
*/
private function ip2bin($ip)
{
if ($this->getIpVersion($ip) === 4) {
return str_pad(base_convert(ip2long($ip), 10, 2), static::IPV4_ADDRESS_LENGTH, '0', STR_PAD_LEFT);
} else {
$unpack = unpack('A16', inet_pton($ip));
$binStr = array_shift($unpack);
$bytes = static::IPV6_ADDRESS_LENGTH / 8; // 128 bit / 8 = 16 bytes
$result = '';
while ($bytes-- > 0) {
$result = sprintf('%08b', isset($binStr[$bytes]) ? ord($binStr[$bytes]) : '0') . $result;
}
return $result;
}
}
/**
* @inheritdoc
*/
public function clientValidateAttribute($model, $attribute, $view)
{
ValidationAsset::register($view);
$options = $this->getClientOptions($model, $attribute);
return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');';
}
/**
* @inheritdoc
*/
public function getClientOptions($model, $attribute)
{
$messages = [
'ipv6NotAllowed' => $this->ipv6NotAllowed,
'ipv4NotAllowed' => $this->ipv4NotAllowed,
'message' => $this->message,
'noSubnet' => $this->noSubnet,
'hasSubnet' => $this->hasSubnet,
];
foreach ($messages as &$message) {
$message = $this->formatMessage($message, [
'attribute' => $model->getAttributeLabel($attribute),
]);
}
$options = [
'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv4Pattern)),
'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($this->ipv6Pattern)),
'messages' => $messages,
'ipv4' => (bool) $this->ipv4,
'ipv6' => (bool) $this->ipv6,
'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($this->getIpParsePattern())),
'negation' => $this->negation,
'subnet' => $this->subnet,
];
if ($this->skipOnEmpty) {
$options['skipOnEmpty'] = 1;
}
return $options;
}
}
|