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

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