IpValidator::validateSubnet()   F
last analyzed

Complexity

Conditions 28
Paths 156

Size

Total Lines 74
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 43
CRAP Score 28

Importance

Changes 0
Metric Value
cc 28
eloc 45
nc 156
nop 1
dl 0
loc 74
ccs 43
cts 43
cp 1
crap 28
rs 3.7
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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