IpUtils.php 6.0 KB

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