IpUtils.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. private static $checkedIps = [];
  19. /**
  20. * This class should not be instantiated.
  21. */
  22. private function __construct()
  23. {
  24. }
  25. /**
  26. * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
  27. *
  28. * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
  29. *
  30. * @return bool
  31. */
  32. public static function checkIp(?string $requestIp, $ips)
  33. {
  34. if (null === $requestIp) {
  35. trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
  36. return false;
  37. }
  38. if (!\is_array($ips)) {
  39. $ips = [$ips];
  40. }
  41. $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4';
  42. foreach ($ips as $ip) {
  43. if (self::$method($requestIp, $ip)) {
  44. return true;
  45. }
  46. }
  47. return false;
  48. }
  49. /**
  50. * Compares two IPv4 addresses.
  51. * In case a subnet is given, it checks if it contains the request IP.
  52. *
  53. * @param string $ip IPv4 address or subnet in CIDR notation
  54. *
  55. * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
  56. */
  57. public static function checkIp4(?string $requestIp, string $ip)
  58. {
  59. if (null === $requestIp) {
  60. trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
  61. return false;
  62. }
  63. $cacheKey = $requestIp.'-'.$ip;
  64. if (isset(self::$checkedIps[$cacheKey])) {
  65. return self::$checkedIps[$cacheKey];
  66. }
  67. if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
  68. return self::$checkedIps[$cacheKey] = false;
  69. }
  70. if (str_contains($ip, '/')) {
  71. [$address, $netmask] = explode('/', $ip, 2);
  72. if ('0' === $netmask) {
  73. return self::$checkedIps[$cacheKey] = filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4);
  74. }
  75. if ($netmask < 0 || $netmask > 32) {
  76. return self::$checkedIps[$cacheKey] = false;
  77. }
  78. } else {
  79. $address = $ip;
  80. $netmask = 32;
  81. }
  82. if (false === ip2long($address)) {
  83. return self::$checkedIps[$cacheKey] = false;
  84. }
  85. return self::$checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask);
  86. }
  87. /**
  88. * Compares two IPv6 addresses.
  89. * In case a subnet is given, it checks if it contains the request IP.
  90. *
  91. * @author David Soria Parra <dsp at php dot net>
  92. *
  93. * @see https://github.com/dsp/v6tools
  94. *
  95. * @param string $ip IPv6 address or subnet in CIDR notation
  96. *
  97. * @return bool
  98. *
  99. * @throws \RuntimeException When IPV6 support is not enabled
  100. */
  101. public static function checkIp6(?string $requestIp, string $ip)
  102. {
  103. if (null === $requestIp) {
  104. trigger_deprecation('symfony/http-foundation', '5.4', 'Passing null as $requestIp to "%s()" is deprecated, pass an empty string instead.', __METHOD__);
  105. return false;
  106. }
  107. $cacheKey = $requestIp.'-'.$ip;
  108. if (isset(self::$checkedIps[$cacheKey])) {
  109. return self::$checkedIps[$cacheKey];
  110. }
  111. if (!((\extension_loaded('sockets') && \defined('AF_INET6')) || @inet_pton('::1'))) {
  112. throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
  113. }
  114. if (str_contains($ip, '/')) {
  115. [$address, $netmask] = explode('/', $ip, 2);
  116. if ('0' === $netmask) {
  117. return (bool) unpack('n*', @inet_pton($address));
  118. }
  119. if ($netmask < 1 || $netmask > 128) {
  120. return self::$checkedIps[$cacheKey] = false;
  121. }
  122. } else {
  123. $address = $ip;
  124. $netmask = 128;
  125. }
  126. $bytesAddr = unpack('n*', @inet_pton($address));
  127. $bytesTest = unpack('n*', @inet_pton($requestIp));
  128. if (!$bytesAddr || !$bytesTest) {
  129. return self::$checkedIps[$cacheKey] = false;
  130. }
  131. for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
  132. $left = $netmask - 16 * ($i - 1);
  133. $left = ($left <= 16) ? $left : 16;
  134. $mask = ~(0xFFFF >> $left) & 0xFFFF;
  135. if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
  136. return self::$checkedIps[$cacheKey] = false;
  137. }
  138. }
  139. return self::$checkedIps[$cacheKey] = true;
  140. }
  141. /**
  142. * Anonymizes an IP/IPv6.
  143. *
  144. * Removes the last byte for v4 and the last 8 bytes for v6 IPs
  145. */
  146. public static function anonymize(string $ip): string
  147. {
  148. $wrappedIPv6 = false;
  149. if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) {
  150. $wrappedIPv6 = true;
  151. $ip = substr($ip, 1, -1);
  152. }
  153. $packedAddress = inet_pton($ip);
  154. if (4 === \strlen($packedAddress)) {
  155. $mask = '255.255.255.0';
  156. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
  157. $mask = '::ffff:ffff:ff00';
  158. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
  159. $mask = '::ffff:ff00';
  160. } else {
  161. $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  162. }
  163. $ip = inet_ntop($packedAddress & inet_pton($mask));
  164. if ($wrappedIPv6) {
  165. $ip = '['.$ip.']';
  166. }
  167. return $ip;
  168. }
  169. }