Passed
Pull Request — master (#81)
by Def
01:31
created

Ip::getName()   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 Yiisoft\Validator\Result;
8
use Yiisoft\NetworkUtilities\IpHelper;
9
use Yiisoft\Validator\DataSetInterface;
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
     * @see allowSubnet
145
     */
146
    private string $wrongCidr = 'Contains wrong subnet mask.';
147
148
    /**
149
     * @var string user-defined error message is used when validation fails due to subnet [[subnet]] set to 'only',
150
     * but the CIDR prefix is not set.
151
     *
152
     * You may use the following placeholders in the message:
153
     *
154
     * - `{attribute}`: the label of the attribute being validated
155
     * - `{value}`: the value of the attribute being validated
156
     *
157
     * @see allowSubnet
158
     */
159
    private string $noSubnet = 'Must be an IP address with specified subnet.';
160
161
    /**
162
     * @var string user-defined error message is used when validation fails
163
     * due to [[subnet]] is false, but CIDR prefix is present.
164
     *
165
     * You may use the following placeholders in the message:
166
     *
167
     * - `{attribute}`: the label of the attribute being validated
168
     * - `{value}`: the value of the attribute being validated
169
     *
170
     * @see allowSubnet
171
     */
172
    private string $hasSubnet = 'Must not be a subnet.';
173
174
    /**
175
     * @var string user-defined error message is used when validation fails due to IP address
176
     * is not not allowed by [[ranges]] check.
177
     *
178
     * You may use the following placeholders in the message:
179
     *
180
     * - `{attribute}`: the label of the attribute being validated
181
     * - `{value}`: the value of the attribute being validated
182
     *
183
     * @see ranges
184
     */
185
    private string $notInRange = 'Is not in the allowed range.';
186
187
    /**
188
     * @var array
189
     */
190
    private array $ranges = [];
191
192 16
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
193
    {
194 16
        if (!$this->allowIpv4 && !$this->allowIpv6) {
195 1
            throw new \RuntimeException('Both IPv4 and IPv6 checks can not be disabled at the same time');
196
        }
197 15
        $result = new Result();
198 15
        if (!is_string($value)) {
199 4
            $result->addError($this->translateMessage($this->message));
200 4
            return $result;
201
        }
202
203 11
        if (preg_match($this->getIpParsePattern(), $value, $matches) === 0) {
204 6
            $result->addError($this->translateMessage($this->message));
205 6
            return $result;
206
        }
207 8
        $negation = !empty($matches['not'] ?? null);
208 8
        $ip = $matches['ip'];
209 8
        $cidr = $matches['cidr'] ?? null;
210 8
        $ipCidr = $matches['ipCidr'];
211
212
        try {
213 8
            $ipVersion = IpHelper::getIpVersion($ip, false);
214
        } catch (\InvalidArgumentException $e) {
215
            $result->addError($this->translateMessage($this->message));
216
            return $result;
217
        }
218
219 8
        if ($this->requireSubnet === true && $cidr === null) {
220 3
            $result->addError($this->translateMessage($this->noSubnet));
221 3
            return $result;
222
        }
223 8
        if ($this->allowSubnet === false && $cidr !== null) {
224 3
            $result->addError($this->translateMessage($this->hasSubnet));
225 3
            return $result;
226
        }
227 8
        if ($this->allowNegation === false && $negation) {
228 3
            $result->addError($this->translateMessage($this->message));
229 3
            return $result;
230
        }
231 8
        if ($ipVersion === IpHelper::IPV6 && !$this->allowIpv6) {
232 1
            $result->addError($this->translateMessage($this->ipv6NotAllowed));
233 1
            return $result;
234
        }
235 8
        if ($ipVersion === IpHelper::IPV4 && !$this->allowIpv4) {
236 2
            $result->addError($this->translateMessage($this->ipv4NotAllowed));
237 2
            return $result;
238
        }
239 8
        if (!$result->isValid()) {
240
            return $result;
241
        }
242 8
        if ($cidr !== null) {
243
            try {
244 5
                IpHelper::getCidrBits($ipCidr);
245 2
            } catch (\InvalidArgumentException $e) {
246 2
                $result->addError($this->translateMessage($this->wrongCidr));
247 2
                return $result;
248
            }
249
        }
250 8
        if (!$this->isAllowed($ipCidr)) {
251 4
            $result->addError($this->translateMessage($this->notInRange));
252 4
            return $result;
253
        }
254
255 8
        return $result;
256
    }
257
258
    /**
259
     * Set the IPv4 or IPv6 ranges that are allowed or forbidden.
260
     *
261
     * The following preparation tasks are performed:
262
     *
263
     * - Recursively substitutes aliases (described in [[networks]]) with their values.
264
     * - Removes duplicates
265
     *
266
     * @param array $ranges the IPv4 or IPv6 ranges that are allowed or forbidden.
267
     *
268
     * When the array is empty, or the option not set, all IP addresses are allowed.
269
     *
270
     * Otherwise, the rules are checked sequentially until the first match is found.
271
     * An IP address is forbidden, when it has not matched any of the rules.
272
     *
273
     * Example:
274
     *
275
     * ```php
276
     * (new Ip())->ranges([
277
     *          '192.168.10.128'
278
     *          '!192.168.10.0/24',
279
     *          'any' // allows any other IP addresses
280
     *      ]);
281
     * ```
282
     *
283
     * In this example, access is allowed for all the IPv4 and IPv6 addresses excluding the `192.168.10.0/24` subnet.
284
     * IPv4 address `192.168.10.128` is also allowed, because it is listed before the restriction.
285
     */
286 10
    public function ranges(array $ranges): self
287
    {
288 10
        $new = clone $this;
289 10
        $new->ranges = $this->prepareRanges($ranges);
290 10
        return $new;
291
    }
292
293
    /**
294
     * Define network alias to be used in {@see ranges()}
295
     *
296
     * @param string $name name of the network
297
     * @param array $ranges ranges
298
     * @return self
299
     */
300 2
    public function network(string $name, array $ranges): self
301
    {
302 2
        if (array_key_exists($name, $this->networks)) {
303 1
            throw new \RuntimeException("Network alias \"{$name}\" already set");
304
        }
305
306 2
        $new = clone $this;
307 2
        $new->networks[$name] = $ranges;
308 2
        return $new;
309
    }
310
311 5
    public function getRanges(): array
312
    {
313 5
        return $this->ranges;
314
    }
315
316 2
    public function allowIpv4(): self
317
    {
318 2
        $new = clone $this;
319 2
        $new->allowIpv4 = true;
320 2
        return $new;
321
    }
322
323 4
    public function disallowIpv4(): self
324
    {
325 4
        $new = clone $this;
326 4
        $new->allowIpv4 = false;
327 4
        return $new;
328
    }
329
330 2
    public function allowIpv6(): self
331
    {
332 2
        $new = clone $this;
333 2
        $new->allowIpv6 = true;
334 2
        return $new;
335
    }
336
337 2
    public function disallowIpv6(): self
338
    {
339 2
        $new = clone $this;
340 2
        $new->allowIpv6 = false;
341 2
        return $new;
342
    }
343
344 3
    public function allowNegation(): self
345
    {
346 3
        $new = clone $this;
347 3
        $new->allowNegation = true;
348 3
        return $new;
349
    }
350
351
    public function disallowNegation(): self
352
    {
353
        $new = clone $this;
354
        $new->allowNegation = false;
355
        return $new;
356
    }
357
358 5
    public function allowSubnet(): self
359
    {
360 5
        $new = clone $this;
361 5
        $new->allowSubnet = true;
362 5
        $new->requireSubnet = false;
363 5
        return $new;
364
    }
365
366 3
    public function requireSubnet(): self
367
    {
368 3
        $new = clone $this;
369 3
        $new->allowSubnet = true;
370 3
        $new->requireSubnet = true;
371 3
        return $new;
372
    }
373
374
    public function disallowSubnet(): self
375
    {
376
        $new = clone $this;
377
        $new->allowSubnet = false;
378
        $new->requireSubnet = false;
379
        return $new;
380
    }
381
382
    /**
383
     * The method checks whether the IP address with specified CIDR is allowed according to the [[ranges]] list.
384
     *
385
     * @see ranges
386
     */
387 8
    private function isAllowed(string $ip): bool
388
    {
389 8
        if (empty($this->ranges)) {
390 3
            return true;
391
        }
392
393 5
        foreach ($this->ranges as $string) {
394 5
            [$isNegated, $range] = $this->parseNegatedRange($string);
395 5
            if (IpHelper::inRange($ip, $range)) {
396 5
                return !$isNegated;
397
            }
398
        }
399
400 3
        return false;
401
    }
402
403
    /**
404
     * Parses IP address/range for the negation with [[NEGATION_CHAR]].
405
     *
406
     * @param $string
407
     * @return array `[0 => bool, 1 => string]`
408
     *  - boolean: whether the string is negated
409
     *  - string: the string without negation (when the negation were present)
410
     */
411 10
    private function parseNegatedRange($string): array
412
    {
413 10
        $isNegated = strpos($string, static::NEGATION_CHAR) === 0;
414 10
        return [$isNegated, $isNegated ? substr($string, strlen(static::NEGATION_CHAR)) : $string];
415
    }
416
417
    /**
418
     * Prepares array to fill in [[ranges]].
419
     *
420
     *  - Recursively substitutes aliases, described in [[networks]] with their values,
421
     *  - Removes duplicates.
422
     *
423
     * @param array $ranges
424
     * @return array
425
     * @see networks
426
     */
427 10
    private function prepareRanges(array $ranges): array
428
    {
429 10
        $result = [];
430 10
        foreach ($ranges as $string) {
431 10
            [$isRangeNegated, $range] = $this->parseNegatedRange($string);
432 10
            if (isset($this->networks[$range])) {
433 8
                $replacements = $this->prepareRanges($this->networks[$range]);
434 8
                foreach ($replacements as &$replacement) {
435 8
                    [$isReplacementNegated, $replacement] = $this->parseNegatedRange($replacement);
436 8
                    $result[] = ($isRangeNegated && !$isReplacementNegated ? static::NEGATION_CHAR : '') . $replacement;
437
                }
438
            } else {
439 10
                $result[] = $string;
440
            }
441
        }
442
443 10
        return array_unique($result);
444
    }
445
446
    /**
447
     * Used to get the Regexp pattern for initial IP address parsing.
448
     * @return string
449
     */
450 11
    public function getIpParsePattern(): string
451
    {
452 11
        return '/^(?<not>' . preg_quote(
453 11
            static::NEGATION_CHAR,
454 11
            '/'
455 11
        ) . ')?(?<ipCidr>(?<ip>(?:' . IpHelper::IPV4_PATTERN . ')|(?:' . IpHelper::IPV6_PATTERN . '))(?:\/(?<cidr>-?\d+))?)$/';
456
    }
457
458
    /**
459
     * @inheritDoc
460
     * @return string
461
     */
462 1
    public function getName(): string
463
    {
464 1
        return 'ip';
465
    }
466
467
    /**
468
     * @inheritDoc
469
     * @return array
470
     */
471 10
    public function getOptions(): array
472
    {
473 10
        return array_merge(
474 10
            $this->allowIpv4 ? [] : ['allowIpv4' => $this->allowIpv4, 'ipv4NotAllowedMessage' => $this->translateMessage($this->ipv4NotAllowed)],
475 10
            $this->allowIpv6 ? [] : ['allowIpv6' => $this->allowIpv6, 'ipv6NotAllowedMessage' => $this->translateMessage($this->ipv6NotAllowed)],
476 10
            $this->allowSubnet ? ['allowSubnet' => $this->allowSubnet] : ['hasSubnetMessage' => $this->translateMessage($this->hasSubnet)],
477 10
            $this->requireSubnet ? ['requireSubnet' => $this->requireSubnet, 'noSubnetMessage' => $this->translateMessage($this->noSubnet)] : [],
478 10
            $this->allowNegation ? ['allowNegation' => $this->allowNegation] : [],
479 10
            ['message' => $this->translateMessage($this->message)],
480 10
            ['wrongCidrMessage' => $this->translateMessage($this->wrongCidr)],
481 10
            empty($this->ranges) ? [] : ['ranges' => $this->ranges, 'notInRangeMessage' => $this->translateMessage($this->notInRange)],
482 10
            parent::getOptions()
483
        );
484
    }
485
}
486