Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/IpUtils.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 /**
15 * Http utility functions.
16 *
17 * @author Fabien Potencier <[email protected]>
18 */
19 class IpUtils
20 {
21 public const PRIVATE_SUBNETS = [
22 '127.0.0.0/8', // RFC1700 (Loopback)
23 '10.0.0.0/8', // RFC1918
24 '192.168.0.0/16', // RFC1918
25 '172.16.0.0/12', // RFC1918
26 '169.254.0.0/16', // RFC3927
27 '0.0.0.0/8', // RFC5735
28 '240.0.0.0/4', // RFC1112
29 '::1/128', // Loopback
30 'fc00::/7', // Unique Local Address
31 'fe80::/10', // Link Local Address
32 '::ffff:0:0/96', // IPv4-mapped IPv6 addresses (RFC 4291 section 2.5.5.2)
33 '::/128', // Unspecified address
34 '::/96', // IPv4-compatible IPv6 addresses (RFC 4291 section 2.5.5.1)
35 '2002::/16', // 6to4 (RFC 3056)
36 '2001::/32', // Teredo tunneling (RFC 4380)
37 '64:ff9b::/96', // NAT64 well-known prefix (RFC 6052)
38 '64:ff9b:1::/48', // NAT64 local-use prefix (RFC 8215)
39 ];
40
41 private static array $checkedIps = [];
42
43 /**
44 * This class should not be instantiated.
45 */
46 private function __construct()
47 {
48 }
49
50 /**
51 * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
52 *
53 * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
54 */
55 public static function checkIp(string $requestIp, string|array $ips): bool
56 {
57 if (!\is_array($ips)) {
58 $ips = [$ips];
59 }
60
61 $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4';
62
63 foreach ($ips as $ip) {
64 if (self::$method($requestIp, $ip)) {
65 return true;
66 }
67 }
68
69 return false;
70 }
71
72 /**
73 * Compares two IPv4 addresses.
74 * In case a subnet is given, it checks if it contains the request IP.
75 *
76 * @param string $ip IPv4 address or subnet in CIDR notation
77 *
78 * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
79 */
80 public static function checkIp4(string $requestIp, string $ip): bool
81 {
82 $cacheKey = $requestIp.'-'.$ip.'-v4';
83 if (null !== $cacheValue = self::getCacheResult($cacheKey)) {
84 return $cacheValue;
85 }
86
87 if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
88 return self::setCacheResult($cacheKey, false);
89 }
90
91 if (str_contains($ip, '/')) {
92 [$address, $netmask] = explode('/', $ip, 2);
93
94 if ('0' === $netmask) {
95 return self::setCacheResult($cacheKey, false !== filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4));
96 }
97
98 if ($netmask < 0 || $netmask > 32) {
99 return self::setCacheResult($cacheKey, false);
100 }
101 } else {
102 $address = $ip;
103 $netmask = 32;
104 }
105
106 if (false === ip2long($address)) {
107 return self::setCacheResult($cacheKey, false);
108 }
109
110 return self::setCacheResult($cacheKey, 0 === substr_compare(\sprintf('%032b', ip2long($requestIp)), \sprintf('%032b', ip2long($address)), 0, $netmask));
111 }
112
113 /**
114 * Compares two IPv6 addresses.
115 * In case a subnet is given, it checks if it contains the request IP.
116 *
117 * @author David Soria Parra <dsp at php dot net>
118 *
119 * @see https://github.com/dsp/v6tools
120 *
121 * @param string $ip IPv6 address or subnet in CIDR notation
122 *
123 * @throws \RuntimeException When IPV6 support is not enabled
124 */
125 public static function checkIp6(string $requestIp, string $ip): bool
126 {
127 $cacheKey = $requestIp.'-'.$ip.'-v6';
128 if (null !== $cacheValue = self::getCacheResult($cacheKey)) {
129 return $cacheValue;
130 }
131
132 if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
133 throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
134 }
135
136 // Check to see if we were given a IP4 $requestIp or $ip by mistake
137 if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
138 return self::setCacheResult($cacheKey, false);
139 }
140
141 if (str_contains($ip, '/')) {
142 [$address, $netmask] = explode('/', $ip, 2);
143
144 if (!filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
145 return self::setCacheResult($cacheKey, false);
146 }
147
148 if ('0' === $netmask) {
149 return (bool) unpack('n*', @inet_pton($address));
150 }
151
152 if ($netmask < 1 || $netmask > 128) {
153 return self::setCacheResult($cacheKey, false);
154 }
155 } else {
156 if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
157 return self::setCacheResult($cacheKey, false);
158 }
159
160 $address = $ip;
161 $netmask = 128;
162 }
163
164 $bytesAddr = unpack('n*', @inet_pton($address));
165 $bytesTest = unpack('n*', @inet_pton($requestIp));
166
167 if (!$bytesAddr || !$bytesTest) {
168 return self::setCacheResult($cacheKey, false);
169 }
170
171 for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
172 $left = $netmask - 16 * ($i - 1);
173 $left = ($left <= 16) ? $left : 16;
174 $mask = ~(0xFFFF >> $left) & 0xFFFF;
175 if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
176 return self::setCacheResult($cacheKey, false);
177 }
178 }
179
180 return self::setCacheResult($cacheKey, true);
181 }
182
183 /**
184 * Anonymizes an IP/IPv6.
185 *
186 * Removes the last bytes of IPv4 and IPv6 addresses (1 byte for IPv4 and 8 bytes for IPv6 by default).
187 *
188 * @param int<0, 4> $v4Bytes
189 * @param int<0, 16> $v6Bytes
190 */
191 public static function anonymize(string $ip/* , int $v4Bytes = 1, int $v6Bytes = 8 */): string
192 {
193 $v4Bytes = 1 < \func_num_args() ? func_get_arg(1) : 1;
194 $v6Bytes = 2 < \func_num_args() ? func_get_arg(2) : 8;
195
196 if ($v4Bytes < 0 || $v6Bytes < 0) {
197 throw new \InvalidArgumentException('Cannot anonymize less than 0 bytes.');
198 }
199
200 if ($v4Bytes > 4 || $v6Bytes > 16) {
201 throw new \InvalidArgumentException('Cannot anonymize more than 4 bytes for IPv4 and 16 bytes for IPv6.');
202 }
203
204 /*
205 * If the IP contains a % symbol, then it is a local-link address with scoping according to RFC 4007
206 * In that case, we only care about the part before the % symbol, as the following functions, can only work with
207 * the IP address itself. As the scope can leak information (containing interface name), we do not want to
208 * include it in our anonymized IP data.
209 */
210 if (str_contains($ip, '%')) {
211 $ip = substr($ip, 0, strpos($ip, '%'));
212 }
213
214 $wrappedIPv6 = false;
215 if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
216 $wrappedIPv6 = true;
217 $ip = substr($ip, 1, -1);
218 }
219
220 $mappedIpV4MaskGenerator = static function (string $mask, int $bytesToAnonymize) {
221 $mask .= str_repeat('ff', 4 - $bytesToAnonymize);
222 $mask .= str_repeat('00', $bytesToAnonymize);
223
224 return '::'.implode(':', str_split($mask, 4));
225 };
226
227 $packedAddress = inet_pton($ip);
228 if (4 === \strlen($packedAddress)) {
229 $mask = rtrim(str_repeat('255.', 4 - $v4Bytes).str_repeat('0.', $v4Bytes), '.');
230 } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
231 $mask = $mappedIpV4MaskGenerator('ffff', $v4Bytes);
232 } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
233 $mask = $mappedIpV4MaskGenerator('', $v4Bytes);
234 } else {
235 $mask = str_repeat('ff', 16 - $v6Bytes).str_repeat('00', $v6Bytes);
236 $mask = implode(':', str_split($mask, 4));
237 }
238 $ip = inet_ntop($packedAddress & inet_pton($mask));
239
240 if ($wrappedIPv6) {
241 $ip = '['.$ip.']';
242 }
243
244 return $ip;
245 }
246
247 /**
248 * Checks if an IPv4 or IPv6 address is contained in the list of private IP subnets.
249 */
250 public static function isPrivateIp(string $requestIp): bool
251 {
252 return self::checkIp($requestIp, self::PRIVATE_SUBNETS);
253 }
254
255 private static function getCacheResult(string $cacheKey): ?bool
256 {
257 if (isset(self::$checkedIps[$cacheKey])) {
258 // Move the item last in cache (LRU)
259 $value = self::$checkedIps[$cacheKey];
260 unset(self::$checkedIps[$cacheKey]);
261 self::$checkedIps[$cacheKey] = $value;
262
263 return self::$checkedIps[$cacheKey];
264 }
265
266 return null;
267 }
268
269 private static function setCacheResult(string $cacheKey, bool $result): bool
270 {
271 if (1000 < \count(self::$checkedIps)) {
272 // stop memory leak if there are many keys
273 self::$checkedIps = \array_slice(self::$checkedIps, 500, null, true);
274 }
275
276 return self::$checkedIps[$cacheKey] = $result;
277 }
278 }