IpUtils.php 9.4 KB

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