1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2022 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 'Barkrowler', 71 'BLEXBot', 72 'DataForSEO', 73 'DotBot', 74 'Grapeshot', 75 'Honolulu-bot', // Aggressive crawer, no info available 76 'ia_archiver', 77 'Linguee', 78 'MJ12bot', 79 'netEstate NE', 80 'panscient', 81 'PetalBot', 82 'proximic', 83 'SemrushBot', 84 'SEOkicks', 85 'SiteKiosk', 86 'Turnitin', 87 'XoviBot', 88 'ZoominfoBot', 89 ]; 90 91 /** 92 * Some search engines use reverse/forward DNS to verify the IP address. 93 * 94 * @see https://developer.amazon.com/support/amazonbot 95 * @see https://support.google.com/webmasters/answer/80553?hl=en 96 * @see https://www.bing.com/webmaster/help/which-crawlers-does-bing-use-8c184ec0 97 * @see https://www.bing.com/webmaster/help/how-to-verify-bingbot-3905dc26 98 * @see https://yandex.com/support/webmaster/robot-workings/check-yandex-robots.html 99 * @see https://www.mojeek.com/bot.html 100 * @see https://support.apple.com/en-gb/HT204683 101 */ 102 private const ROBOT_REV_FWD_DNS = [ 103 'Amazonbot' => ['.crawl.amazon.com'], 104 'Applebot' => ['.applebot.apple.com'], 105 'bingbot' => ['.search.msn.com'], 106 'BingPreview' => ['.search.msn.com'], 107 'Google' => ['.google.com', '.googlebot.com'], 108 'MojeekBot' => ['.mojeek.com'], 109 'Mail.RU_Bot' => ['.mail.ru'], 110 'msnbot' => ['.search.msn.com'], 111 'Qwantify' => ['.search.qwant.com'], 112 'Sogou' => ['.crawl.sogou.com'], 113 'Yahoo' => ['.crawl.yahoo.net'], 114 'Yandex' => ['.yandex.ru', '.yandex.net', '.yandex.com'], 115 ]; 116 117 /** 118 * Some search engines only use reverse DNS to verify the IP address. 119 * 120 * @see https://help.baidu.com/question?prod_id=99&class=0&id=3001 121 * @see https://napoveda.seznam.cz/en/full-text-search/seznambot-crawler 122 * @see https://www.ionos.de/terms-gtc/faq-crawler 123 */ 124 private const ROBOT_REV_ONLY_DNS = [ 125 'Baiduspider' => ['.baidu.com', '.baidu.jp'], 126 'FreshBot' => ['.seznam.cz'], 127 'IonCrawl' => ['.1und1.org'], 128 'Neevabot' => ['.neeva.com'], 129 ]; 130 131 /** 132 * Some search engines operate from designated IP addresses. 133 * 134 * @see https://www.apple.com/go/applebot 135 * @see https://help.duckduckgo.com/duckduckgo-help-pages/results/duckduckbot 136 */ 137 private const ROBOT_IPS = [ 138 'AppleBot' => [ 139 '17.0.0.0/8', 140 ], 141 'Ask Jeeves' => [ 142 '65.214.45.143', 143 '65.214.45.148', 144 '66.235.124.192', 145 '66.235.124.7', 146 '66.235.124.101', 147 '66.235.124.193', 148 '66.235.124.73', 149 '66.235.124.196', 150 '66.235.124.74', 151 '63.123.238.8', 152 '202.143.148.61', 153 ], 154 'DuckDuckBot' => [ 155 '23.21.227.69', 156 '50.16.241.113', 157 '50.16.241.114', 158 '50.16.241.117', 159 '50.16.247.234', 160 '52.204.97.54', 161 '52.5.190.19', 162 '54.197.234.188', 163 '54.208.100.253', 164 '54.208.102.37', 165 '107.21.1.8', 166 ], 167 ]; 168 169 /** 170 * Some search engines operate from designated IP addresses. 171 * 172 * @see https://bot.seekport.com/ 173 */ 174 private const ROBOT_IP_FILES = [ 175 'SeekportBot' => 'https://bot.seekport.com/seekportbot_ips.txt', 176 ]; 177 178 /** 179 * Some search engines operate from within a designated autonomous system. 180 * 181 * @see https://developers.facebook.com/docs/sharing/webmasters/crawler 182 * @see https://www.facebook.com/peering/ 183 */ 184 private const ROBOT_ASNS = [ 185 'facebook' => ['AS32934', 'AS63293'], 186 'twitter' => ['AS13414'], 187 ]; 188 189 /** 190 * @param ServerRequestInterface $request 191 * @param RequestHandlerInterface $handler 192 * 193 * @return ResponseInterface 194 */ 195 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 196 { 197 $ua = Validator::serverParams($request)->string('HTTP_USER_AGENT', ''); 198 $ip = Validator::attributes($request)->string('client-ip'); 199 $address = IPFactory::parseAddressString($ip); 200 assert($address instanceof AddressInterface); 201 202 foreach (self::BAD_ROBOTS as $robot) { 203 if (str_contains($ua, $robot)) { 204 return $this->response(); 205 } 206 } 207 208 foreach (self::ROBOT_REV_FWD_DNS as $robot => $valid_domains) { 209 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, false)) { 210 return $this->response(); 211 } 212 } 213 214 foreach (self::ROBOT_REV_ONLY_DNS as $robot => $valid_domains) { 215 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, true)) { 216 return $this->response(); 217 } 218 } 219 220 foreach (self::ROBOT_IPS as $robot => $valid_ip_ranges) { 221 if (str_contains($ua, $robot)) { 222 foreach ($valid_ip_ranges as $ip_range) { 223 $range = IPFactory::parseRangeString($ip_range); 224 225 if ($range instanceof RangeInterface && $range->contains($address)) { 226 continue 2; 227 } 228 } 229 230 return $this->response(); 231 } 232 } 233 234 foreach (self::ROBOT_IP_FILES as $robot => $url) { 235 if (str_contains($ua, $robot)) { 236 $valid_ip_ranges = $this->fetchIpRangesForUrl($robot, $url); 237 238 foreach ($valid_ip_ranges as $ip_range) { 239 $range = IPFactory::parseRangeString($ip_range); 240 241 if ($range instanceof RangeInterface && $range->contains($address)) { 242 continue 2; 243 } 244 } 245 246 return $this->response(); 247 } 248 } 249 250 foreach (self::ROBOT_ASNS as $robot => $asns) { 251 foreach ($asns as $asn) { 252 if (str_contains($ua, $robot)) { 253 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 254 if ($range->contains($address)) { 255 continue 2; 256 } 257 } 258 259 return $this->response(); 260 } 261 } 262 } 263 264 // Allow sites to block access from entire networks. 265 $block_asn = Validator::attributes($request)->string('block_asn', ''); 266 preg_match_all('/(AS\d+)/', $block_asn, $matches); 267 268 foreach ($matches[1] as $asn) { 269 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 270 if ($range->contains($address)) { 271 return $this->response(); 272 } 273 } 274 } 275 276 return $handler->handle($request); 277 } 278 279 /** 280 * Check that an IP address belongs to a robot operator using a forward/reverse DNS lookup. 281 * 282 * @param string $ip 283 * @param array<string> $valid_domains 284 * @param bool $reverse_only 285 * 286 * @return bool 287 */ 288 private function checkRobotDNS(string $ip, array $valid_domains, bool $reverse_only): bool 289 { 290 $host = gethostbyaddr($ip); 291 292 if ($host === false) { 293 return false; 294 } 295 296 foreach ($valid_domains as $domain) { 297 if (str_ends_with($host, $domain)) { 298 return $reverse_only || $ip === gethostbyname($host); 299 } 300 } 301 302 return false; 303 } 304 305 /** 306 * Perform a whois search for an ASN. 307 * 308 * @param string $asn - The autonomous system number to query 309 * 310 * @return array<RangeInterface> 311 */ 312 private function fetchIpRangesForAsn(string $asn): array 313 { 314 return Registry::cache()->file()->remember('whois-asn-' . $asn, static function () use ($asn): array { 315 $mapper = static fn (AsnRouteInfo $route_info): ?RangeInterface => IPFactory::parseRangeString($route_info->route ?: $route_info->route6); 316 317 try { 318 $loader = new CurlLoader(self::WHOIS_TIMEOUT); 319 $whois = new Whois($loader); 320 $info = $whois->loadAsnInfo($asn); 321 $routes = $info->routes; 322 $ranges = array_map($mapper, $routes); 323 324 return array_filter($ranges); 325 } catch (Throwable) { 326 return []; 327 } 328 }, random_int(self::WHOIS_TTL_MIN, self::WHOIS_TTL_MAX)); 329 } 330 331 /** 332 * Fetch a list of IP addresses from a remote file. 333 * 334 * @param string $ua 335 * @param string $url 336 * 337 * @return array<string> 338 */ 339 private function fetchIpRangesForUrl(string $ua, string $url): array 340 { 341 return Registry::cache()->file()->remember('url-ip-list-' . $ua, static function () use ($url): array { 342 try { 343 $client = new Client(); 344 $response = $client->get($url, ['timeout' => 5]); 345 $contents = $response->getBody()->getContents(); 346 347 preg_match_all(self::REGEX_IPV4, $contents, $matches); 348 349 return $matches[0]; 350 } catch (GuzzleException) { 351 return []; 352 } 353 }, random_int(self::WHOIS_TTL_MIN, self::WHOIS_TTL_MAX)); 354 } 355 356 /** 357 * @return ResponseInterface 358 */ 359 private function response(): ResponseInterface 360 { 361 return response('Not acceptable', StatusCodeInterface::STATUS_NOT_ACCEPTABLE); 362 } 363} 364