Passed
Push — master ( 2b6758...acf834 )
by Aleksei
06:59
created

Ip::prepareRanges()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 7
nop 1
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\NetworkUtilities\IpHelper;
8
use Yiisoft\Validator\DataSetInterface;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule;
11
12
/**
13
 * The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.
14
 *
15
 * It also may change attribute's value if normalization of IPv6 expansion is enabled.
16
 *
17
 * The following are examples of validation rules using this validator:
18
 *
19
 * ```php
20
 * ['ip_address', 'ip'], // IPv4 or IPv6 address
21
 * ['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
22
 * ['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
23
 * ['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
24
 * ['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
25
 * ['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
26
 * ['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
27
 * ['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
28
 * ```
29
 *
30
 * @property array $ranges The IPv4 or IPv6 ranges that are allowed or forbidden. See [[setRanges()]] for
31
 * detailed description.
32
 */
33
class Ip extends Rule
34
{
35
    /**
36
     * Negation char.
37
     *
38
     * Used to negate [[ranges]] or [[networks]] or to negate validating value when [[negation]] is set to `true`.
39
     *
40
     * @see allowNegation
41
     * @see networks
42
     * @see ranges
43
     */
44
    private const NEGATION_CHAR = '!';
45
46
    /**
47
     * @var array The network aliases, that can be used in {@see ranges()}.
48
     *  - key - alias name
49
     *  - value - array of strings. String can be an IP range, IP address or another alias. String can be
50
     *    negated with [[NEGATION_CHAR]] (independent of `negation` option).
51
     *
52
     * The following aliases are defined by default:
53
     *  - `*`: `any`
54
     *  - `any`: `0.0.0.0/0, ::/0`
55
     *  - `private`: `10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fd00::/8`
56
     *  - `multicast`: `224.0.0.0/4, ff00::/8`
57
     *  - `linklocal`: `169.254.0.0/16, fe80::/10`
58
     *  - `localhost`: `127.0.0.0/8', ::1`
59
     *  - `documentation`: `192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32`
60
     *  - `system`: `multicast, linklocal, localhost, documentation`
61
     */
62
    private array $networks = [
63
        '*' => ['any'],
64
        'any' => ['0.0.0.0/0', '::/0'],
65
        'private' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fd00::/8'],
66
        'multicast' => ['224.0.0.0/4', 'ff00::/8'],
67
        'linklocal' => ['169.254.0.0/16', 'fe80::/10'],
68
        'localhost' => ['127.0.0.0/8', '::1'],
69
        'documentation' => ['192.0.2.0/24', '198.51.100.0/24', '203.0.113.0/24', '2001:db8::/32'],
70
        'system' => ['multicast', 'linklocal', 'localhost', 'documentation'],
71
    ];
72
73
    /**
74
     * @var bool whether the validating value can be an IPv6 address. Defaults to `true`.
75
     */
76
    private bool $allowIpv6 = true;
77
78
    /**
79
     * @var bool whether the validating value can be an IPv4 address. Defaults to `true`.
80
     */
81
    private bool $allowIpv4 = true;
82
83
    /**
84
     * @var bool whether the address can be an IP with CIDR subnet, like `192.168.10.0/24`.
85
     * The following values are possible:
86
     *
87
     * - `false` - the address must not have a subnet (default).
88
     * - `true` - specifying a subnet is optional.
89
     */
90
    private bool $allowSubnet = false;
91
92
    /**
93
     * @var bool
94
     */
95
    private bool $requireSubnet = false;
96
97
    /**
98
     * @var bool whether address may have a [[NEGATION_CHAR]] character at the beginning.
99
     * Defaults to `false`.
100
     */
101
    private bool $allowNegation = false;
102
103
    /**
104
     * @var string user-defined error message is used when validation fails due to the wrong IP address format.
105
     *
106
     * You may use the following placeholders in the message:
107
     *
108
     * - `{attribute}`: the label of the attribute being validated
109
     * - `{value}`: the value of the attribute being validated
110
     */
111
    private string $message = 'Must be a valid IP address.';
112
113
    /**
114
     * @var string user-defined error message is used when validation fails due to the disabled IPv6 validation.
115
     *
116
     * You may use the following placeholders in the message:
117
     *
118
     * - `{attribute}`: the label of the attribute being validated
119
     * - `{value}`: the value of the attribute being validated
120
     *
121
     * @see allowIpv6
122
     */
123
    private string $ipv6NotAllowed = 'Must not be an IPv6 address.';
124
125
    /**
126
     * @var string user-defined error message is used when validation fails due to the disabled IPv4 validation.
127
     *
128
     * You may use the following placeholders in the message:
129
     *
130
     * - `{attribute}`: the label of the attribute being validated
131
     * - `{value}`: the value of the attribute being validated
132
     *
133
     * @see allowIpv4
134
     */
135
    private string $ipv4NotAllowed = 'Must not be an IPv4 address.';
136
137
    /**
138
     * @var string user-defined error message is used when validation fails due to the wrong CIDR.
139
     *
140
     * You may use the following placeholders in the message:
141
     *
142
     * - `{attribute}`: the label of the attribute being validated
143
     * - `{value}`: the value of the attribute being validated
144
     *
145
     * @see allowSubnet
146
     */
147
    private string $wrongCidr = 'Contains wrong subnet mask.';
148
149
    /**
150
     * @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
151
     * but the CIDR prefix is not set.
152
     *
153
     * You may use the following placeholders in the message:
154
     *
155
     * - `{attribute}`: the label of the attribute being validated
156
     * - `{value}`: the value of the attribute being validated
157
     *
158
     * @see allowSubnet
159
     */
160
    private string $noSubnet = 'Must be an IP address with specified subnet.';
161
162
    /**
163
     * @var string user-defined error message is used when validation fails
164
     * due to [[subnet]] is false, but CIDR prefix is present.
165
     *
166
     * You may use the following placeholders in the message:
167
     *
168
     * - `{attribute}`: the label of the attribute being validated
169
     * - `{value}`: the value of the attribute being validated
170
     *
171
     * @see allowSubnet
172
     */
173
    private string $hasSubnet = 'Must not be a subnet.';
174
175
    /**
176
     * @var string user-defined error message is used when validation fails due to IP address
177
     * is not not allowed by [[ranges]] check.
178
     *
179
     * You may use the following placeholders in the message:
180
     *
181
     * - `{attribute}`: the label of the attribute being validated
182
     * - `{value}`: the value of the attribute being validated
183
     *
184
     * @see ranges
185
     */
186
    private string $notInRange = 'Is not in the allowed range.';
187
188
    /**
189
     * @var array
190
     */
191
    private array $ranges = [];
192
193 16
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
194
    {
195 16
        if (!$this->allowIpv4 && !$this->allowIpv6) {
196 1
            throw new \RuntimeException('Both IPv4 and IPv6 checks can not be disabled at the same time');
197
        }
198 15
        $result = new Result();
199 15
        if (!is_string($value)) {
200 4
            $result->addError($this->translateMessage($this->message));
201 4
            return $result;
202
        }
203
204 11
        if (preg_match($this->getIpParsePattern(), $value, $matches) === 0) {
205 6
            $result->addError($this->translateMessage($this->message));
206 6
            return $result;
207
        }
208 8
        $negation = !empty($matches['not'] ?? null);
209 8
        $ip = $matches['ip'];
210 8
        $cidr = $matches['cidr'] ?? null;
211 8
        $ipCidr = $matches['ipCidr'];
212
213
        try {
214 8
            $ipVersion = IpHelper::getIpVersion($ip, false);
215
        } catch (\InvalidArgumentException $e) {
216
            $result->addError($this->translateMessage($this->message));
217
            return $result;
218
        }
219
220 8
        if ($this->requireSubnet === true && $cidr === null) {
221 3
            $result->addError($this->translateMessage($this->noSubnet));
222 3
            return $result;
223
        }
224 8
        if ($this->allowSubnet === false && $cidr !== null) {
225 3
            $result->addError($this->translateMessage($this->hasSubnet));
226 3
            return $result;
227
        }
228 8
        if ($this->allowNegation === false && $negation) {
229 3
            $result->addError($this->translateMessage($this->message));
230 3
            return $result;
231
        }
232 8
        if ($ipVersion === IpHelper::IPV6 && !$this->allowIpv6) {
233 1
            $result->addError($this->translateMessage($this->ipv6NotAllowed));
234 1
            return $result;
235
        }
236 8
        if ($ipVersion === IpHelper::IPV4 && !$this->allowIpv4) {
237 2
            $result->addError($this->translateMessage($this->ipv4NotAllowed));
238 2
            return $result;
239
        }
240 8
        if (!$result->isValid()) {
241
            return $result;
242
        }
243 8
        if ($cidr !== null) {
244
            try {
245 5
                IpHelper::getCidrBits($ipCidr);
246 2
            } catch (\InvalidArgumentException $e) {
247 2
                $result->addError($this->translateMessage($this->wrongCidr));
248 2
                return $result;
249
            }
250
        }
251 8
        if (!$this->isAllowed($ipCidr)) {
252 4
            $result->addError($this->translateMessage($this->notInRange));
253 4
            return $result;
254
        }
255
256 8
        return $result;
257
    }
258
259
    /**
260
     * Set the IPv4 or IPv6 ranges that are allowed or forbidden.
261
     *
262
     * The following preparation tasks are performed:
263
     *
264
     * - Recursively substitutes aliases (described in [[networks]]) with their values.
265
     * - Removes duplicates
266
     *
267
     * @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
268
     *
269
     * When the array is empty, or the option not set, all IP addresses are allowed.
270
     *
271
     * Otherwise, the rules are checked sequentially until the first match is found.
272
     * An IP address is forbidden, when it has not matched any of the rules.
273
     *
274
     * Example:
275
     *
276
     * ```php
277
     * (new Ip())->ranges([
278
     *          '192.168.10.128'
279
     *          '!192.168.10.0/24',
280
     *          'any' // allows any other IP addresses
281
     *      ]);
282
     * ```
283
     *
284
     * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
285
     * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
286
     */
287 10
    public function ranges(array $ranges): self
288
    {
289 10
        $new = clone $this;
290 10
        $new->ranges = $this->prepareRanges($ranges);
291 10
        return $new;
292
    }
293
294
    /**
295
     * Define network alias to be used in {@see ranges()}
296
     *
297
     * @param string $name name of the network
298
     * @param array $ranges ranges
299
     *
300
     * @return self
301
     */
302 2
    public function network(string $name, array $ranges): self
303
    {
304 2
        if (array_key_exists($name, $this->networks)) {
305 1
            throw new \RuntimeException("Network alias \"{$name}\" already set");
306
        }
307
308 2
        $new = clone $this;
309 2
        $new->networks[$name] = $ranges;
310 2
        return $new;
311
    }
312
313 5
    public function getRanges(): array
314
    {
315 5
        return $this->ranges;
316
    }
317
318 2
    public function allowIpv4(): self
319
    {
320 2
        $new = clone $this;
321 2
        $new->allowIpv4 = true;
322 2
        return $new;
323
    }
324
325 4
    public function disallowIpv4(): self
326
    {
327 4
        $new = clone $this;
328 4
        $new->allowIpv4 = false;
329 4
        return $new;
330
    }
331
332 2
    public function allowIpv6(): self
333
    {
334 2
        $new = clone $this;
335 2
        $new->allowIpv6 = true;
336 2
        return $new;
337
    }
338
339 2
    public function disallowIpv6(): self
340
    {
341 2
        $new = clone $this;
342 2
        $new->allowIpv6 = false;
343 2
        return $new;
344
    }
345
346 3
    public function allowNegation(): self
347
    {
348 3
        $new = clone $this;
349 3
        $new->allowNegation = true;
350 3
        return $new;
351
    }
352
353
    public function disallowNegation(): self
354
    {
355
        $new = clone $this;
356
        $new->allowNegation = false;
357
        return $new;
358
    }
359
360 5
    public function allowSubnet(): self
361
    {
362 5
        $new = clone $this;
363 5
        $new->allowSubnet = true;
364 5
        $new->requireSubnet = false;
365 5
        return $new;
366
    }
367
368 3
    public function requireSubnet(): self
369
    {
370 3
        $new = clone $this;
371 3
        $new->allowSubnet = true;
372 3
        $new->requireSubnet = true;
373 3
        return $new;
374
    }
375
376
    public function disallowSubnet(): self
377
    {
378
        $new = clone $this;
379
        $new->allowSubnet = false;
380
        $new->requireSubnet = false;
381
        return $new;
382
    }
383
384
    /**
385
     * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
386
     *
387
     * @return bool
388
     *
389
     * @see ranges
390
     */
391 8
    private function isAllowed(string $ip): bool
392
    {
393 8
        if (empty($this->ranges)) {
394 3
            return true;
395
        }
396
397 5
        foreach ($this->ranges as $string) {
398 5
            [$isNegated, $range] = $this->parseNegatedRange($string);
399 5
            if (IpHelper::inRange($ip, $range)) {
400 5
                return !$isNegated;
401
            }
402
        }
403
404 3
        return false;
405
    }
406
407
    /**
408
     * Parses IP address/range for the negation with [[NEGATION_CHAR]].
409
     *
410
     * @param $string
411
     *
412
     * @return array `[0 => bool, 1 => string]`
413
     *  - boolean: whether the string is negated
414
     *  - string: the string without negation (when the negation were present)
415
     */
416 10
    private function parseNegatedRange($string): array
417
    {
418 10
        $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
419 10
        return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
420
    }
421
422
    /**
423
     * Prepares array to fill in [[ranges]].
424
     *
425
     *  - Recursively substitutes aliases, described in [[networks]] with their values,
426
     *  - Removes duplicates.
427
     *
428
     * @param array $ranges
429
     *
430
     * @return array
431
     *
432
     * @see networks
433
     */
434 10
    private function prepareRanges(array $ranges): array
435
    {
436 10
        $result = [];
437 10
        foreach ($ranges as $string) {
438 10
            [$isRangeNegated, $range] = $this->parseNegatedRange($string);
439 10
            if (isset($this->networks[$range])) {
440 8
                $replacements = $this->prepareRanges($this->networks[$range]);
441 8
                foreach ($replacements as &$replacement) {
442 8
                    [$isReplacementNegated, $replacement] = $this->parseNegatedRange($replacement);
443 8
                    $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
444
                }
445
            } else {
446 10
                $result[] = $string;
447
            }
448
        }
449
450 10
        return array_unique($result);
451
    }
452
453
    /**
454
     * Used to get the Regexp pattern for initial IP address parsing.
455
     *
456
     * @return string
457
     */
458 11
    public function getIpParsePattern(): string
459
    {
460 11
        return '/^(?<not>' . preg_quote(
461 11
            static::NEGATION_CHAR,
462 11
            '/'
463 11
        ) . ')?(?<ipCidr>(?<ip>(?:' . IpHelper::IPV4_PATTERN . ')|(?:' . IpHelper::IPV6_PATTERN . '))(?:\/(?<cidr>-?\d+))?)$/';
464
    }
465
466 10
    public function getOptions(): array
467
    {
468 10
        return array_merge(
469 10
            parent::getOptions(),
470
            [
471 10
                'message' => $this->translateMessage($this->message),
472 10
                'allowIpv4' => $this->allowIpv4,
473 10
                'ipv4NotAllowedMessage' => $this->translateMessage($this->ipv4NotAllowed),
474 10
                'allowIpv6' => $this->allowIpv6,
475 10
                'ipv6NotAllowedMessage' => $this->translateMessage($this->ipv6NotAllowed),
476 10
                'allowSubnet' => $this->allowSubnet,
477 10
                'hasSubnetMessage' => $this->translateMessage($this->hasSubnet),
478 10
                'requireSubnet' => $this->requireSubnet,
479 10
                'noSubnetMessage' => $this->translateMessage($this->noSubnet),
480 10
                'allowNegation' => $this->allowNegation,
481 10
                'wrongCidrMessage' => $this->translateMessage($this->wrongCidr),
482 10
                'ranges' => $this->ranges,
483 10
                'notInRangeMessage' => $this->translateMessage($this->notInRange),
484
            ],
485
        );
486
    }
487
}
488