1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2023 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Http\Middleware; 21 22use Fig\Http\Message\StatusCodeInterface; 23use Fisharebest\Webtrees\Registry; 24use Fisharebest\Webtrees\Validator; 25use GuzzleHttp\Client; 26use GuzzleHttp\Exception\GuzzleException; 27use Iodev\Whois\Loaders\CurlLoader; 28use Iodev\Whois\Modules\Asn\AsnRouteInfo; 29use Iodev\Whois\Whois; 30use IPLib\Address\AddressInterface; 31use IPLib\Factory as IPFactory; 32use IPLib\Range\RangeInterface; 33use Psr\Http\Message\ResponseInterface; 34use Psr\Http\Message\ServerRequestInterface; 35use Psr\Http\Server\MiddlewareInterface; 36use Psr\Http\Server\RequestHandlerInterface; 37use Throwable; 38 39use function array_filter; 40use function array_map; 41use function assert; 42use function gethostbyaddr; 43use function gethostbyname; 44use function preg_match_all; 45use function random_int; 46use function response; 47use function str_contains; 48use function str_ends_with; 49 50/** 51 * Middleware to block bad robots before they waste our valuable CPU cycles. 52 */ 53class BadBotBlocker implements MiddlewareInterface 54{ 55 private const REGEX_OCTET = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'; 56 private const REGEX_IPV4 = '/\\b' . self::REGEX_OCTET . '(?:\\.' . self::REGEX_OCTET . '){3}\\b/'; 57 58 // Cache whois requests. Try to avoid all caches expiring at the same time. 59 private const WHOIS_TTL_MIN = 28 * 86400; 60 private const WHOIS_TTL_MAX = 35 * 86400; 61 private const WHOIS_TIMEOUT = 5; 62 63 // Bad robots - SEO optimisers, advertisers, etc. This list is shared with robots.txt. 64 public const BAD_ROBOTS = [ 65 'admantx', 66 'Adsbot', 67 'AhrefsBot', 68 'Amazonbot', // Until it understands crawl-delay and noindex / nofollow 69 'AspiegelBot', 70 'Awario', // Brand management 71 'Barkrowler', 72 'BLEXBot', 73 'Bytespider', 74 'CCBot', // Used to train a number of LLMs 75 'ChatGPT-User', // Used by ChatGPT during operation 76 'DataForSeoBot', // https://dataforseo.com/dataforseo-bot 77 'DotBot', 78 'FacebookBot', // Collects training data for Facebook's LLM translator. 79 'Google-Extended', // Collects training data for Google Bard 80 'GPTBot', // Collects training data for ChatGPT 81 'Grapeshot', 82 'Honolulu-bot', // Aggressive crawer, no info available 83 'ia_archiver', 84 'linabot', // Aggressive crawer, no info available 85 'Linguee', 86 'MegaIndex.ru', 87 'MJ12bot', 88 'netEstate NE', 89 'Omgilibot', // Collects training data for LLMs 90 'panscient', 91 'PetalBot', 92 'proximic', 93 'SeekportBot', // Pretends to be a search engine - but isn't 94 'SemrushBot', 95 'serpstatbot', 96 'SEOkicks', 97 'SiteKiosk', 98 'TinyTestBot', 99 'Turnitin', 100 'wp_is_mobile', // Nothing to do with wordpress 101 'XoviBot', 102 'YisouSpider', 103 'ZoominfoBot', 104 ]; 105 106 /** 107 * Some search engines use reverse/forward DNS to verify the IP address. 108 * 109 * @see https://developer.amazon.com/support/amazonbot 110 * @see https://support.google.com/webmasters/answer/80553?hl=en 111 * @see https://www.bing.com/webmaster/help/which-crawlers-does-bing-use-8c184ec0 112 * @see https://www.bing.com/webmaster/help/how-to-verify-bingbot-3905dc26 113 * @see https://yandex.com/support/webmaster/robot-workings/check-yandex-robots.html 114 * @see https://www.mojeek.com/bot.html 115 * @see https://support.apple.com/en-gb/HT204683 116 */ 117 private const ROBOT_REV_FWD_DNS = [ 118 'Amazonbot' => ['.crawl.amazon.com'], 119 'Applebot' => ['.applebot.apple.com'], 120 'BingPreview' => ['.search.msn.com'], 121 'Google' => ['.google.com', '.googlebot.com'], 122 'Mail.RU_Bot' => ['.mail.ru'], 123 'MicrosoftPreview' => ['.search.msn.com'], 124 'MojeekBot' => ['.mojeek.com'], 125 'Qwantify' => ['.search.qwant.com'], 126 'Sogou' => ['.crawl.sogou.com'], 127 'Yahoo' => ['.crawl.yahoo.net'], 128 'Yandex' => ['.yandex.ru', '.yandex.net', '.yandex.com'], 129 'bingbot' => ['.search.msn.com'], 130 'msnbot' => ['.search.msn.com'], 131 ]; 132 133 /** 134 * Some search engines only use reverse DNS to verify the IP address. 135 * 136 * @see https://help.baidu.com/question?prod_id=99&class=0&id=3001 137 * @see https://napoveda.seznam.cz/en/full-text-search/seznambot-crawler 138 * @see https://www.ionos.de/terms-gtc/faq-crawler 139 */ 140 private const ROBOT_REV_ONLY_DNS = [ 141 'Baiduspider' => ['.baidu.com', '.baidu.jp'], 142 'FreshBot' => ['.seznam.cz'], 143 'IonCrawl' => ['.1und1.org'], 144 'Neevabot' => ['.neeva.com'], 145 'SeznamBot' => ['.seznam.cz'], 146 ]; 147 148 /** 149 * Some search engines operate from designated IP addresses. 150 * 151 * @see https://www.apple.com/go/applebot 152 * @see https://help.duckduckgo.com/duckduckgo-help-pages/results/duckduckbot 153 */ 154 private const ROBOT_IPS = [ 155 'AppleBot' => [ 156 '17.0.0.0/8', 157 ], 158 'Ask Jeeves' => [ 159 '65.214.45.143', 160 '65.214.45.148', 161 '66.235.124.192', 162 '66.235.124.7', 163 '66.235.124.101', 164 '66.235.124.193', 165 '66.235.124.73', 166 '66.235.124.196', 167 '66.235.124.74', 168 '63.123.238.8', 169 '202.143.148.61', 170 ], 171 'DuckDuckBot' => [ 172 '23.21.227.69', 173 '50.16.241.113', 174 '50.16.241.114', 175 '50.16.241.117', 176 '50.16.247.234', 177 '52.204.97.54', 178 '52.5.190.19', 179 '54.197.234.188', 180 '54.208.100.253', 181 '54.208.102.37', 182 '107.21.1.8', 183 ], 184 ]; 185 186 /** 187 * Some search engines operate from designated IP addresses. 188 * 189 * @see https://bot.seekport.com/ 190 */ 191 private const ROBOT_IP_FILES = [ 192 'SeekportBot' => 'https://bot.seekport.com/seekportbot_ips.txt', 193 ]; 194 195 /** 196 * Some search engines operate from within a designated autonomous system. 197 * 198 * @see https://developers.facebook.com/docs/sharing/webmasters/crawler 199 * @see https://www.facebook.com/peering/ 200 */ 201 private const ROBOT_ASNS = [ 202 'facebook' => ['AS32934', 'AS63293'], 203 'twitter' => ['AS13414'], 204 ]; 205 206 /** 207 * @param ServerRequestInterface $request 208 * @param RequestHandlerInterface $handler 209 * 210 * @return ResponseInterface 211 */ 212 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 213 { 214 $ua = Validator::serverParams($request)->string('HTTP_USER_AGENT', ''); 215 $ip = Validator::attributes($request)->string('client-ip'); 216 $address = IPFactory::parseAddressString($ip); 217 assert($address instanceof AddressInterface); 218 219 foreach (self::BAD_ROBOTS as $robot) { 220 if (str_contains($ua, $robot)) { 221 return $this->response(); 222 } 223 } 224 225 foreach (self::ROBOT_REV_FWD_DNS as $robot => $valid_domains) { 226 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, false)) { 227 return $this->response(); 228 } 229 } 230 231 foreach (self::ROBOT_REV_ONLY_DNS as $robot => $valid_domains) { 232 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, true)) { 233 return $this->response(); 234 } 235 } 236 237 foreach (self::ROBOT_IPS as $robot => $valid_ip_ranges) { 238 if (str_contains($ua, $robot)) { 239 foreach ($valid_ip_ranges as $ip_range) { 240 $range = IPFactory::parseRangeString($ip_range); 241 242 if ($range instanceof RangeInterface && $range->contains($address)) { 243 continue 2; 244 } 245 } 246 247 return $this->response(); 248 } 249 } 250 251 foreach (self::ROBOT_IP_FILES as $robot => $url) { 252 if (str_contains($ua, $robot)) { 253 $valid_ip_ranges = $this->fetchIpRangesForUrl($robot, $url); 254 255 foreach ($valid_ip_ranges as $ip_range) { 256 $range = IPFactory::parseRangeString($ip_range); 257 258 if ($range instanceof RangeInterface && $range->contains($address)) { 259 continue 2; 260 } 261 } 262 263 return $this->response(); 264 } 265 } 266 267 foreach (self::ROBOT_ASNS as $robot => $asns) { 268 foreach ($asns as $asn) { 269 if (str_contains($ua, $robot)) { 270 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 271 if ($range->contains($address)) { 272 continue 2; 273 } 274 } 275 276 return $this->response(); 277 } 278 } 279 } 280 281 // Allow sites to block access from entire networks. 282 $block_asn = Validator::attributes($request)->string('block_asn', ''); 283 preg_match_all('/(AS\d+)/', $block_asn, $matches); 284 285 foreach ($matches[1] as $asn) { 286 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 287 if ($range->contains($address)) { 288 return $this->response(); 289 } 290 } 291 } 292 293 return $handler->handle($request); 294 } 295 296 /** 297 * Check that an IP address belongs to a robot operator using a forward/reverse DNS lookup. 298 * 299 * @param string $ip 300 * @param array<string> $valid_domains 301 * @param bool $reverse_only 302 * 303 * @return bool 304 */ 305 private function checkRobotDNS(string $ip, array $valid_domains, bool $reverse_only): bool 306 { 307 $host = gethostbyaddr($ip); 308 309 if ($host === false) { 310 return false; 311 } 312 313 foreach ($valid_domains as $domain) { 314 if (str_ends_with($host, $domain)) { 315 return $reverse_only || $ip === gethostbyname($host); 316 } 317 } 318 319 return false; 320 } 321 322 /** 323 * Perform a whois search for an ASN. 324 * 325 * @param string $asn The autonomous system number to query 326 * 327 * @return array<RangeInterface> 328 */ 329 private function fetchIpRangesForAsn(string $asn): array 330 { 331 return Registry::cache()->file()->remember('whois-asn-' . $asn, static function () use ($asn): array { 332 $mapper = static fn (AsnRouteInfo $route_info): ?RangeInterface => IPFactory::parseRangeString($route_info->route ?: $route_info->route6); 333 334 try { 335 $loader = new CurlLoader(self::WHOIS_TIMEOUT); 336 $whois = new Whois($loader); 337 $info = $whois->loadAsnInfo($asn); 338 $routes = $info->routes; 339 $ranges = array_map($mapper, $routes); 340 341 return array_filter($ranges); 342 } catch (Throwable) { 343 return []; 344 } 345 }, random_int(self::WHOIS_TTL_MIN, self::WHOIS_TTL_MAX)); 346 } 347 348 /** 349 * Fetch a list of IP addresses from a remote file. 350 * 351 * @param string $ua 352 * @param string $url 353 * 354 * @return array<string> 355 */ 356 private function fetchIpRangesForUrl(string $ua, string $url): array 357 { 358 return Registry::cache()->file()->remember('url-ip-list-' . $ua, static function () use ($url): array { 359 try { 360 $client = new Client(); 361 $response = $client->get($url, ['timeout' => 5]); 362 $contents = $response->getBody()->getContents(); 363 364 preg_match_all(self::REGEX_IPV4, $contents, $matches); 365 366 return $matches[0]; 367 } catch (GuzzleException) { 368 return []; 369 } 370 }, random_int(self::WHOIS_TTL_MIN, self::WHOIS_TTL_MAX)); 371 } 372 373 /** 374 * @return ResponseInterface 375 */ 376 private function response(): ResponseInterface 377 { 378 return response('Not acceptable', StatusCodeInterface::STATUS_NOT_ACCEPTABLE); 379 } 380} 381