Passed
Push — master ( 52f31e...9d8a75 )
by Alexander
05:40 queued 04:13
created

Ip::allowNegation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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