IpUtils.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. $wrappedIPv6 = false;
  157. if (str_starts_with($ip, '[') && str_ends_with($ip, ']')) {
  158. $wrappedIPv6 = true;
  159. $ip = substr($ip, 1, -1);
  160. }
  161. $packedAddress = inet_pton($ip);
  162. if (4 === \strlen($packedAddress)) {
  163. $mask = '255.255.255.0';
  164. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
  165. $mask = '::ffff:ffff:ff00';
  166. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
  167. $mask = '::ffff:ff00';
  168. } else {
  169. $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  170. }
  171. $ip = inet_ntop($packedAddress & inet_pton($mask));
  172. if ($wrappedIPv6) {
  173. $ip = '['.$ip.']';
  174. }
  175. return $ip;
  176. }
  177. /**
  178. * Checks if an IPv4 or IPv6 address is contained in the list of private IP subnets.
  179. */
  180. public static function isPrivateIp(string $requestIp): bool
  181. {
  182. return self::checkIp($requestIp, self::PRIVATE_SUBNETS);
  183. }
  184. private static function getCacheResult(string $cacheKey): ?bool
  185. {
  186. if (isset(self::$checkedIps[$cacheKey])) {
  187. // Move the item last in cache (LRU)
  188. $value = self::$checkedIps[$cacheKey];
  189. unset(self::$checkedIps[$cacheKey]);
  190. self::$checkedIps[$cacheKey] = $value;
  191. return self::$checkedIps[$cacheKey];
  192. }
  193. return null;
  194. }
  195. private static function setCacheResult(string $cacheKey, bool $result): bool
  196. {
  197. if (1000 < \count(self::$checkedIps)) {
  198. // stop memory leak if there are many keys
  199. self::$checkedIps = \array_slice(self::$checkedIps, 500, null, true);
  200. }
  201. return self::$checkedIps[$cacheKey] = $result;
  202. }
  203. }