Passed
Pull Request — master (#99)
by Def
02:08
created

Ip::getRawOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 0
dl 0
loc 18
ccs 16
cts 16
cp 1
crap 1
rs 9.7666
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\ErrorMessage;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\Rule;
12
13
/**
14
 * The validator checks if the attribute value is a valid IPv4/IPv6 address or subnet.
15
 *
16
 * It also may change attribute's value if normalization of IPv6 expansion is enabled.
17
 *
18
 * The following are examples of validation rules using this validator:
19
 *
20
 * ```php
21
 * ['ip_address', 'ip'], // IPv4 or IPv6 address
22
 * ['ip_address', 'ip', 'ipv6' => false], // IPv4 address (IPv6 is disabled)
23
 * ['ip_address', 'ip', 'subnet' => true], // requires a CIDR prefix (like 10.0.0.1/24) for the IP address
24
 * ['ip_address', 'ip', 'subnet' => null], // CIDR prefix is optional
25
 * ['ip_address', 'ip', 'subnet' => null, 'normalize' => true], // CIDR prefix is optional and will be added when missing
26
 * ['ip_address', 'ip', 'ranges' => ['192.168.0.0/24']], // only IP addresses from the specified subnet are allowed
27
 * ['ip_address', 'ip', 'ranges' => ['!192.168.0.0/24', 'any']], // any IP is allowed except IP in the specified subnet
28
 * ['ip_address', 'ip', 'expandIPv6' => true], // expands IPv6 address to a full notation format
29
 * ```
30
 *
31
 * @property array $ranges The IPv4 or IPv6 ranges that are allowed or forbidden. See [[setRanges()]] for
32
 * detailed description.
33
 */
34
class Ip extends Rule
35
{
36
    /**
37
     * Negation char.
38
     *
39
     * Used to negate [[ranges]] or [[networks]] or to negate validating value when [[negation]] is set to `true`.
40
     *
41
     * @see allowNegation
42
     * @see networks
43
     * @see ranges
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 [[NEGATION_CHAR]] (independent of `negation` 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 [[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 [[subnet]] set to 'only',
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 [[subnet]] 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 [[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 16
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
195
    {
196 16
        if (!$this->allowIpv4 && !$this->allowIpv6) {
197 1
            throw new \RuntimeException('Both IPv4 and IPv6 checks can not be disabled at the same time');
198
        }
199 15
        $result = new Result();
200 15
        if (!is_string($value)) {
201 4
            $result->addError(new ErrorMessage($this->message));
202 4
            return $result;
203
        }
204
205 11
        if (preg_match($this->getIpParsePattern(), $value, $matches) === 0) {
206 6
            $result->addError(new ErrorMessage($this->message));
207 6
            return $result;
208
        }
209 8
        $negation = !empty($matches['not'] ?? null);
210 8
        $ip = $matches['ip'];
211 8
        $cidr = $matches['cidr'] ?? null;
212 8
        $ipCidr = $matches['ipCidr'];
213
214
        try {
215 8
            $ipVersion = IpHelper::getIpVersion($ip, false);
216
        } catch (\InvalidArgumentException $e) {
217
            $result->addError(new ErrorMessage($this->message));
218
            return $result;
219
        }
220
221 8
        if ($this->requireSubnet === true && $cidr === null) {
222 3
            $result->addError(new ErrorMessage($this->noSubnet));
223 3
            return $result;
224
        }
225 8
        if ($this->allowSubnet === false && $cidr !== null) {
226 3
            $result->addError(new ErrorMessage($this->hasSubnet));
227 3
            return $result;
228
        }
229 8
        if ($this->allowNegation === false && $negation) {
230 3
            $result->addError(new ErrorMessage($this->message));
231 3
            return $result;
232
        }
233 8
        if ($ipVersion === IpHelper::IPV6 && !$this->allowIpv6) {
234 1
            $result->addError(new ErrorMessage($this->ipv6NotAllowed));
235 1
            return $result;
236
        }
237 8
        if ($ipVersion === IpHelper::IPV4 && !$this->allowIpv4) {
238 2
            $result->addError(new ErrorMessage($this->ipv4NotAllowed));
239 2
            return $result;
240
        }
241 8
        if (!$result->isValid()) {
242
            return $result;
243
        }
244 8
        if ($cidr !== null) {
245
            try {
246 5
                IpHelper::getCidrBits($ipCidr);
247 2
            } catch (\InvalidArgumentException $e) {
248 2
                $result->addError(new ErrorMessage($this->wrongCidr));
249 2
                return $result;
250
            }
251
        }
252 8
        if (!$this->isAllowed($ipCidr)) {
253 4
            $result->addError(new ErrorMessage($this->notInRange));
254 4
            return $result;
255
        }
256
257 8
        return $result;
258
    }
259
260
    /**
261
     * Set the IPv4 or IPv6 ranges that are allowed or forbidden.
262
     *
263
     * The following preparation tasks are performed:
264
     *
265
     * - Recursively substitutes aliases (described in [[networks]]) with their values.
266
     * - Removes duplicates
267
     *
268
     * @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
269
     *
270
     * When the array is empty, or the option not set, all IP addresses are allowed.
271
     *
272
     * Otherwise, the rules are checked sequentially until the first match is found.
273
     * An IP address is forbidden, when it has not matched any of the rules.
274
     *
275
     * Example:
276
     *
277
     * ```php
278
     * (new Ip())->ranges([
279
     *          '192.168.10.128'
280
     *          '!192.168.10.0/24',
281
     *          'any' // allows any other IP addresses
282
     *      ]);
283
     * ```
284
     *
285
     * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
286
     * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
287
     */
288 10
    public function ranges(array $ranges): self
289
    {
290 10
        $new = clone $this;
291 10
        $new->ranges = $this->prepareRanges($ranges);
292 10
        return $new;
293
    }
294
295
    /**
296
     * Define network alias to be used in {@see ranges()}
297
     *
298
     * @param string $name name of the network
299
     * @param array $ranges ranges
300
     *
301
     * @return self
302
     */
303 2
    public function network(string $name, array $ranges): self
304
    {
305 2
        if (array_key_exists($name, $this->networks)) {
306 1
            throw new \RuntimeException("Network alias \"{$name}\" already set");
307
        }
308
309 2
        $new = clone $this;
310 2
        $new->networks[$name] = $ranges;
311 2
        return $new;
312
    }
313
314 5
    public function getRanges(): array
315
    {
316 5
        return $this->ranges;
317
    }
318
319 2
    public function allowIpv4(): self
320
    {
321 2
        $new = clone $this;
322 2
        $new->allowIpv4 = true;
323 2
        return $new;
324
    }
325
326 4
    public function disallowIpv4(): self
327
    {
328 4
        $new = clone $this;
329 4
        $new->allowIpv4 = false;
330 4
        return $new;
331
    }
332
333 2
    public function allowIpv6(): self
334
    {
335 2
        $new = clone $this;
336 2
        $new->allowIpv6 = true;
337 2
        return $new;
338
    }
339
340 2
    public function disallowIpv6(): self
341
    {
342 2
        $new = clone $this;
343 2
        $new->allowIpv6 = false;
344 2
        return $new;
345
    }
346
347 3
    public function allowNegation(): self
348
    {
349 3
        $new = clone $this;
350 3
        $new->allowNegation = true;
351 3
        return $new;
352
    }
353
354
    public function disallowNegation(): self
355
    {
356
        $new = clone $this;
357
        $new->allowNegation = false;
358
        return $new;
359
    }
360
361 5
    public function allowSubnet(): self
362
    {
363 5
        $new = clone $this;
364 5
        $new->allowSubnet = true;
365 5
        $new->requireSubnet = false;
366 5
        return $new;
367
    }
368
369 3
    public function requireSubnet(): self
370
    {
371 3
        $new = clone $this;
372 3
        $new->allowSubnet = true;
373 3
        $new->requireSubnet = true;
374 3
        return $new;
375
    }
376
377
    public function disallowSubnet(): self
378
    {
379
        $new = clone $this;
380
        $new->allowSubnet = false;
381
        $new->requireSubnet = false;
382
        return $new;
383
    }
384
385
    /**
386
     * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
387
     *
388
     * @return bool
389
     *
390
     * @see ranges
391
     */
392 8
    private function isAllowed(string $ip): bool
393
    {
394 8
        if (empty($this->ranges)) {
395 3
            return true;
396
        }
397
398 5
        foreach ($this->ranges as $string) {
399 5
            [$isNegated, $range] = $this->parseNegatedRange($string);
400 5
            if (IpHelper::inRange($ip, $range)) {
401 5
                return !$isNegated;
402
            }
403
        }
404
405 3
        return false;
406
    }
407
408
    /**
409
     * Parses IP address/range for the negation with [[NEGATION_CHAR]].
410
     *
411
     * @param $string
412
     *
413
     * @return array `[0 => bool, 1 => string]`
414
     *  - boolean: whether the string is negated
415
     *  - string: the string without negation (when the negation were present)
416
     */
417 10
    private function parseNegatedRange($string): array
418
    {
419 10
        $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
420 10
        return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
421
    }
422
423
    /**
424
     * Prepares array to fill in [[ranges]].
425
     *
426
     *  - Recursively substitutes aliases, described in [[networks]] with their values,
427
     *  - Removes duplicates.
428
     *
429
     * @param array $ranges
430
     *
431
     * @return array
432
     *
433
     * @see networks
434
     */
435 10
    private function prepareRanges(array $ranges): array
436
    {
437 10
        $result = [];
438 10
        foreach ($ranges as $string) {
439 10
            [$isRangeNegated, $range] = $this->parseNegatedRange($string);
440 10
            if (isset($this->networks[$range])) {
441 8
                $replacements = $this->prepareRanges($this->networks[$range]);
442 8
                foreach ($replacements as &$replacement) {
443 8
                    [$isReplacementNegated, $replacement] = $this->parseNegatedRange($replacement);
444 8
                    $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
445
                }
446
            } else {
447 10
                $result[] = $string;
448
            }
449
        }
450
451 10
        return array_unique($result);
452
    }
453
454
    /**
455
     * Used to get the Regexp pattern for initial IP address parsing.
456
     *
457
     * @return string
458
     */
459 11
    public function getIpParsePattern(): string
460
    {
461 11
        return '/^(?<not>' . preg_quote(
462 11
            static::NEGATION_CHAR,
463 11
            '/'
464 11
        ) . ')?(?<ipCidr>(?<ip>(?:' . IpHelper::IPV4_PATTERN . ')|(?:' . IpHelper::IPV6_PATTERN . '))(?:\/(?<cidr>-?\d+))?)$/';
465
    }
466
467 10
    public function getRawOptions(): array
468
    {
469 10
        return array_merge(
470 10
            parent::getRawOptions(),
471
            [
472 10
                'message' => new ErrorMessage($this->message),
473 10
                'allowIpv4' => $this->allowIpv4,
474 10
                'ipv4NotAllowedMessage' => new ErrorMessage($this->ipv4NotAllowed),
475 10
                'allowIpv6' => $this->allowIpv6,
476 10
                'ipv6NotAllowedMessage' => new ErrorMessage($this->ipv6NotAllowed),
477 10
                'allowSubnet' => $this->allowSubnet,
478 10
                'hasSubnetMessage' => new ErrorMessage($this->hasSubnet),
479 10
                'requireSubnet' => $this->requireSubnet,
480 10
                'noSubnetMessage' => new ErrorMessage($this->noSubnet),
481 10
                'allowNegation' => $this->allowNegation,
482 10
                'wrongCidrMessage' => new ErrorMessage($this->wrongCidr),
483 10
                'ranges' => $this->ranges,
484 10
                'notInRangeMessage' => new ErrorMessage($this->notInRange),
485
            ],
486
        );
487
    }
488
}
489