IpUtils.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. '::1/128', // Loopback
  27. 'fc00::/7', // Unique Local Address
  28. 'fe80::/10', // Link Local Address
  29. '::ffff:0:0/96', // IPv4 translations
  30. '::/128', // Unspecified address
  31. ];
  32. private static array $checkedIps = [];
  33. /**
  34. * This class should not be instantiated.
  35. */
  36. private function __construct()
  37. {
  38. }
  39. /**
  40. * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
  41. *
  42. * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
  43. */
  44. public static function checkIp(string $requestIp, string|array $ips): bool
  45. {
  46. if (!\is_array($ips)) {
  47. $ips = [$ips];
  48. }
  49. $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4';
  50. foreach ($ips as $ip) {
  51. if (self::$method($requestIp, $ip)) {
  52. return true;
  53. }
  54. }
  55. return false;
  56. }
  57. /**
  58. * Compares two IPv4 addresses.
  59. * In case a subnet is given, it checks if it contains the request IP.
  60. *
  61. * @param string $ip IPv4 address or subnet in CIDR notation
  62. *
  63. * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
  64. */
  65. public static function checkIp4(string $requestIp, string $ip): bool
  66. {
  67. $cacheKey = $requestIp.'-'.$ip.'-v4';
  68. if (null !== $cacheValue = self::getCacheResult($cacheKey)) {
  69. return $cacheValue;
  70. }
  71. if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
  72. return self::setCacheResult($cacheKey, false);
  73. }
  74. if (str_contains($ip, '/')) {
  75. [$address, $netmask] = explode('/', $ip, 2);
  76. if ('0' === $netmask) {
  77. return self::setCacheResult($cacheKey, false !== filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4));
  78. }
  79. if ($netmask < 0 || $netmask > 32) {
  80. return self::setCacheResult($cacheKey, false);
  81. }
  82. } else {
  83. $address = $ip;
  84. $netmask = 32;
  85. }
  86. if (false === ip2long($address)) {
  87. return self::setCacheResult($cacheKey, false);
  88. }
  89. return self::setCacheResult($cacheKey, 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask));
  90. }
  91. /**
  92. * Compares two IPv6 addresses.
  93. * In case a subnet is given, it checks if it contains the request IP.
  94. *
  95. * @author David Soria Parra <dsp at php dot net>
  96. *
  97. * @see https://github.com/dsp/v6tools
  98. *
  99. * @param string $ip IPv6 address or subnet in CIDR notation
  100. *
  101. * @throws \RuntimeException When IPV6 support is not enabled
  102. */
  103. public static function checkIp6(string $requestIp, string $ip): bool
  104. {
  105. $cacheKey = $requestIp.'-'.$ip.'-v6';
  106. if (null !== $cacheValue = self::getCacheResult($cacheKey)) {
  107. return $cacheValue;
  108. }
  109. if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
  110. throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
  111. }
  112. // Check to see if we were given a IP4 $requestIp or $ip by mistake
  113. if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  114. return self::setCacheResult($cacheKey, false);
  115. }
  116. if (str_contains($ip, '/')) {
  117. [$address, $netmask] = explode('/', $ip, 2);
  118. if (!filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  119. return self::setCacheResult($cacheKey, false);
  120. }
  121. if ('0' === $netmask) {
  122. return (bool) unpack('n*', @inet_pton($address));
  123. }
  124. if ($netmask < 1 || $netmask > 128) {
  125. return self::setCacheResult($cacheKey, false);
  126. }
  127. } else {
  128. if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  129. return self::setCacheResult($cacheKey, false);
  130. }
  131. $address = $ip;
  132. $netmask = 128;
  133. }
  134. $bytesAddr = unpack('n*', @inet_pton($address));
  135. $bytesTest = unpack('n*', @inet_pton($requestIp));
  136. if (!$bytesAddr || !$bytesTest) {
  137. return self::setCacheResult($cacheKey, false);
  138. }
  139. for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
  140. $left = $netmask - 16 * ($i - 1);
  141. $left = ($left <= 16) ? $left : 16;
  142. $mask = ~(0xFFFF >> $left) & 0xFFFF;
  143. if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
  144. return self::setCacheResult($cacheKey, false);
  145. }
  146. }
  147. return self::setCacheResult($cacheKey, true);
  148. }
  149. /**
  150. * Anonymizes an IP/IPv6.
  151. *
  152. * Removes the last byte for v4 and the last 8 bytes for v6 IPs
  153. */
  154. public static function anonymize(string $ip): string
  155. {
  156. /**
  157. * If the IP contains a % symbol, then it is a local-link address with scoping according to RFC 4007
  158. * In that case, we only care about the part before the % symbol, as the following functions, can only work with
  159. * the IP address itself. As the scope can leak information (containing interface name), we do not want to
  160. * include it in our anonymized IP data.
  161. */
  162. if (str_contains($ip, '%')) {
  163. $ip = substr($ip, 0, strpos($ip, '%'));
  164. }
  165. $wrappedIPv6 = false;
  166. if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
  167. $wrappedIPv6 = true;
  168. $ip = substr($ip, 1, -1);
  169. }
  170. $packedAddress = inet_pton($ip);
  171. if (4 === \strlen($packedAddress)) {
  172. $mask = '255.255.255.0';
  173. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
  174. $mask = '::ffff:ffff:ff00';
  175. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
  176. $mask = '::ffff:ff00';
  177. } else {
  178. $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  179. }
  180. $ip = inet_ntop($packedAddress & inet_pton($mask));
  181. if ($wrappedIPv6) {
  182. $ip = '['.$ip.']';
  183. }
  184. return $ip;
  185. }
  186. /**
  187. * Checks if an IPv4 or IPv6 address is contained in the list of private IP subnets.
  188. */
  189. public static function isPrivateIp(string $requestIp): bool
  190. {
  191. return self::checkIp($requestIp, self::PRIVATE_SUBNETS);
  192. }
  193. private static function getCacheResult(string $cacheKey): ?bool
  194. {
  195. if (isset(self::$checkedIps[$cacheKey])) {
  196. // Move the item last in cache (LRU)
  197. $value = self::$checkedIps[$cacheKey];
  198. unset(self::$checkedIps[$cacheKey]);
  199. self::$checkedIps[$cacheKey] = $value;
  200. return self::$checkedIps[$cacheKey];
  201. }
  202. return null;
  203. }
  204. private static function setCacheResult(string $cacheKey, bool $result): bool
  205. {
  206. if (1000 < \count(self::$checkedIps)) {
  207. // stop memory leak if there are many keys
  208. self::$checkedIps = \array_slice(self::$checkedIps, 500, null, true);
  209. }
  210. return self::$checkedIps[$cacheKey] = $result;
  211. }
  212. }