IpUtils.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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.'-v4';
  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] = false !== 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.'-v6';
  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. // Check to see if we were given a IP4 $requestIp or $ip by mistake
  115. if (!filter_var($requestIp, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  116. return self::$checkedIps[$cacheKey] = false;
  117. }
  118. if (str_contains($ip, '/')) {
  119. [$address, $netmask] = explode('/', $ip, 2);
  120. if (!filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  121. return self::$checkedIps[$cacheKey] = false;
  122. }
  123. if ('0' === $netmask) {
  124. return (bool) unpack('n*', @inet_pton($address));
  125. }
  126. if ($netmask < 1 || $netmask > 128) {
  127. return self::$checkedIps[$cacheKey] = false;
  128. }
  129. } else {
  130. if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
  131. return self::$checkedIps[$cacheKey] = false;
  132. }
  133. $address = $ip;
  134. $netmask = 128;
  135. }
  136. $bytesAddr = unpack('n*', @inet_pton($address));
  137. $bytesTest = unpack('n*', @inet_pton($requestIp));
  138. if (!$bytesAddr || !$bytesTest) {
  139. return self::$checkedIps[$cacheKey] = false;
  140. }
  141. for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
  142. $left = $netmask - 16 * ($i - 1);
  143. $left = ($left <= 16) ? $left : 16;
  144. $mask = ~(0xFFFF >> $left) & 0xFFFF;
  145. if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
  146. return self::$checkedIps[$cacheKey] = false;
  147. }
  148. }
  149. return self::$checkedIps[$cacheKey] = true;
  150. }
  151. /**
  152. * Anonymizes an IP/IPv6.
  153. *
  154. * Removes the last byte for v4 and the last 8 bytes for v6 IPs
  155. */
  156. public static function anonymize(string $ip): string
  157. {
  158. $wrappedIPv6 = false;
  159. if ('[' === substr($ip, 0, 1) && ']' === substr($ip, -1, 1)) {
  160. $wrappedIPv6 = true;
  161. $ip = substr($ip, 1, -1);
  162. }
  163. $packedAddress = inet_pton($ip);
  164. if (4 === \strlen($packedAddress)) {
  165. $mask = '255.255.255.0';
  166. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff:ffff'))) {
  167. $mask = '::ffff:ffff:ff00';
  168. } elseif ($ip === inet_ntop($packedAddress & inet_pton('::ffff:ffff'))) {
  169. $mask = '::ffff:ff00';
  170. } else {
  171. $mask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  172. }
  173. $ip = inet_ntop($packedAddress & inet_pton($mask));
  174. if ($wrappedIPv6) {
  175. $ip = '['.$ip.']';
  176. }
  177. return $ip;
  178. }
  179. }