Passed
Push — master ( 99ab46...a20a6f )
by Alexander
02:59
created

Ip::rule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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