Passed
Pull Request — master (#175)
by
unknown
02:31
created

Ip::isAllowed()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

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