Просмотр файла app/Services/CloudFlare.php

Размер файла: 6.04Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Services;
  6.  
  7. use Closure;
  8. use Psr\Http\Message\ServerRequestInterface as Request;
  9. use RuntimeException;
  10.  
  11. class CloudFlare
  12. {
  13. private array $checkedIps = [];
  14.  
  15. /**
  16. * List of IP's used by CloudFlare.
  17. * @const array
  18. */
  19. protected const IPS = [
  20. '103.21.244.0/22',
  21. '103.22.200.0/22',
  22. '103.31.4.0/22',
  23. '104.16.0.0/13',
  24. '104.24.0.0/14',
  25. '108.162.192.0/18',
  26. '131.0.72.0/22',
  27. '141.101.64.0/18',
  28. '162.158.0.0/15',
  29. '172.64.0.0/13',
  30. '173.245.48.0/20',
  31. '188.114.96.0/20',
  32. '190.93.240.0/20',
  33. '197.234.240.0/22',
  34. '198.41.128.0/17',
  35. '2400:cb00::/32',
  36. '2405:8100::/32',
  37. '2405:b500::/32',
  38. '2606:4700::/32',
  39. '2803:f800::/32',
  40. '2c0f:f248::/32',
  41. '2a06:98c0::/29',
  42. ];
  43.  
  44. /**
  45. * @var Request
  46. */
  47. private $request;
  48.  
  49. public function __construct(Request $request)
  50. {
  51. $this->request = $request;
  52. }
  53.  
  54. /**
  55. * Checks if current request is coming from CloudFlare servers.
  56. *
  57. * @return bool
  58. */
  59. public function isTrustedRequest(): bool
  60. {
  61. return $this->checkIp($this->request->getAttribute('ip'), static::IPS);
  62. }
  63.  
  64. /**
  65. * Executes a callback on a trusted request.
  66. *
  67. * @param Closure $callback
  68. *
  69. * @return mixed
  70. */
  71. public function onTrustedRequest(Closure $callback)
  72. {
  73. if ($this->isTrustedRequest()) {
  74. return $callback();
  75. }
  76. }
  77.  
  78. /**
  79. * Determines "the real" IP address from the current request.
  80. *
  81. * @return string
  82. */
  83. public function ip(): string
  84. {
  85. return $this->onTrustedRequest(function () {
  86. return filter_var($this->request->getHeaderLine('CF_CONNECTING_IP'), FILTER_VALIDATE_IP);
  87. }) ?: $this->request->getAttribute('ip');
  88. }
  89.  
  90. /**
  91. * Determines country from the current request.
  92. *
  93. * @return string
  94. */
  95. public function country(): string
  96. {
  97. return $this->onTrustedRequest(function () {
  98. return $this->request->getHeaderLine('CF_IPCOUNTRY');
  99. }) ?: '';
  100. }
  101.  
  102. /**
  103. * Checks if an IPv4 or IPv6 address is contained in the list of given IPs or subnets.
  104. *
  105. * @param string|array $ips List of IPs or subnets (can be a string if only a single one)
  106. */
  107. public function checkIp(string $requestIp, string|array $ips): bool
  108. {
  109. if (!is_array($ips)) {
  110. $ips = [$ips];
  111. }
  112.  
  113. $method = substr_count($requestIp, ':') > 1 ? 'checkIp6' : 'checkIp4';
  114.  
  115. foreach ($ips as $ip) {
  116. if ($this->$method($requestIp, $ip)) {
  117. return true;
  118. }
  119. }
  120.  
  121. return false;
  122. }
  123.  
  124. /**
  125. * Compares two IPv4 addresses.
  126. * In case a subnet is given, it checks if it contains the request IP.
  127. *
  128. * @param string $ip IPv4 address or subnet in CIDR notation
  129. *
  130. * @return bool Whether the request IP matches the IP, or whether the request IP is within the CIDR subnet
  131. */
  132. public function checkIp4(string $requestIp, string $ip): bool
  133. {
  134. $cacheKey = $requestIp.'-'.$ip;
  135. if (isset($this->checkedIps[$cacheKey])) {
  136. return $this->checkedIps[$cacheKey];
  137. }
  138.  
  139. if (!filter_var($requestIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  140. return $this->checkedIps[$cacheKey] = false;
  141. }
  142.  
  143. if (str_contains($ip, '/')) {
  144. [$address, $netmask] = explode('/', $ip, 2);
  145.  
  146. if ('0' === $netmask) {
  147. return $this->checkedIps[$cacheKey] = filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
  148. }
  149.  
  150. if ($netmask < 0 || $netmask > 32) {
  151. return $this->checkedIps[$cacheKey] = false;
  152. }
  153. } else {
  154. $address = $ip;
  155. $netmask = 32;
  156. }
  157.  
  158. if (false === ip2long($address)) {
  159. return $this->checkedIps[$cacheKey] = false;
  160. }
  161.  
  162. return $this->checkedIps[$cacheKey] = 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, (int) $netmask);
  163. }
  164.  
  165. /**
  166. * Compares two IPv6 addresses.
  167. * In case a subnet is given, it checks if it contains the request IP.
  168. *
  169. * @author David Soria Parra <dsp at php dot net>
  170. *
  171. * @see https://github.com/dsp/v6tools
  172. *
  173. * @param string $ip IPv6 address or subnet in CIDR notation
  174. *
  175. * @throws RuntimeException When IPV6 support is not enabled
  176. */
  177. public function checkIp6(string $requestIp, string $ip): bool
  178. {
  179. $cacheKey = $requestIp.'-'.$ip;
  180. if (isset($this->checkedIps[$cacheKey])) {
  181. return $this->checkedIps[$cacheKey];
  182. }
  183.  
  184. if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
  185. throw new RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
  186. }
  187.  
  188. if (str_contains($ip, '/')) {
  189. [$address, $netmask] = explode('/', $ip, 2);
  190.  
  191. if ('0' === $netmask) {
  192. return (bool) unpack('n*', @inet_pton($address));
  193. }
  194.  
  195. if ($netmask < 1 || $netmask > 128) {
  196. return $this->checkedIps[$cacheKey] = false;
  197. }
  198. } else {
  199. $address = $ip;
  200. $netmask = 128;
  201. }
  202.  
  203. $bytesAddr = unpack('n*', @inet_pton($address));
  204. $bytesTest = unpack('n*', @inet_pton($requestIp));
  205.  
  206. if (!$bytesAddr || !$bytesTest) {
  207. return $this->checkedIps[$cacheKey] = false;
  208. }
  209.  
  210. for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
  211. $left = $netmask - 16 * ($i - 1);
  212. $left = ($left <= 16) ? $left : 16;
  213. $mask = ~(0xFFFF >> $left) & 0xFFFF;
  214. if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
  215. return $this->checkedIps[$cacheKey] = false;
  216. }
  217. }
  218.  
  219. return $this->checkedIps[$cacheKey] = true;
  220. }
  221. }