IpUtils.php 5.4 KB

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