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 Iodev\Whois\Loaders\CurlLoader; 26use Iodev\Whois\Modules\Asn\AsnRouteInfo; 27use Iodev\Whois\Whois; 28use IPLib\Address\AddressInterface; 29use IPLib\Factory as IPFactory; 30use IPLib\Range\RangeInterface; 31use Psr\Http\Message\ResponseInterface; 32use Psr\Http\Message\ServerRequestInterface; 33use Psr\Http\Server\MiddlewareInterface; 34use Psr\Http\Server\RequestHandlerInterface; 35use Throwable; 36 37use function array_filter; 38use function array_map; 39use function assert; 40use function gethostbyaddr; 41use function gethostbyname; 42use function preg_match_all; 43use function random_int; 44use function response; 45use function str_contains; 46use function str_ends_with; 47 48/** 49 * Middleware to block bad robots before they waste our valuable CPU cycles. 50 */ 51class BadBotBlocker implements MiddlewareInterface 52{ 53 // Cache whois requests. Try to avoid all caches expiring at the same time. 54 private const WHOIS_TTL_MIN = 28 * 86400; 55 private const WHOIS_TTL_MAX = 35 * 86400; 56 private const WHOIS_TIMEOUT = 5; 57 58 // Bad robots - SEO optimisers, advertisers, etc. This list is shared with robots.txt. 59 public const BAD_ROBOTS = [ 60 'admantx', 61 'Adsbot', 62 'AhrefsBot', 63 'AspiegelBot', 64 'Barkrowler', 65 'BLEXBot', 66 'DataForSEO', 67 'DotBot', 68 'Grapeshot', 69 'ia_archiver', 70 'Linguee', 71 'MJ12bot', 72 'panscient', 73 'PetalBot', 74 'proximic', 75 'SemrushBot', 76 'Turnitin', 77 'XoviBot', 78 'ZoominfoBot', 79 ]; 80 81 /** 82 * Some search engines use reverse/forward DNS to verify the IP address. 83 * 84 * @see https://support.google.com/webmasters/answer/80553?hl=en 85 * @see https://www.bing.com/webmaster/help/which-crawlers-does-bing-use-8c184ec0 86 * @see https://www.bing.com/webmaster/help/how-to-verify-bingbot-3905dc26 87 * @see https://yandex.com/support/webmaster/robot-workings/check-yandex-robots.html 88 */ 89 private const ROBOT_REV_FWD_DNS = [ 90 'bingbot' => ['.search.msn.com'], 91 'BingPreview' => ['.search.msn.com'], 92 'Google' => ['.google.com', '.googlebot.com'], 93 'Mail.RU_Bot' => ['mail.ru'], 94 'msnbot' => ['.search.msn.com'], 95 'Qwantify' => ['.search.qwant.com'], 96 'Sogou' => ['.crawl.sogou.com'], 97 'Yahoo' => ['.crawl.yahoo.net'], 98 'Yandex' => ['.yandex.ru', '.yandex.net', '.yandex.com'], 99 ]; 100 101 /** 102 * Some search engines only use reverse DNS to verify the IP address. 103 * 104 * @see https://help.baidu.com/question?prod_id=99&class=0&id=3001 105 * @see https://napoveda.seznam.cz/en/full-text-search/seznambot-crawler 106 */ 107 private const ROBOT_REV_ONLY_DNS = [ 108 'Baiduspider' => ['.baidu.com', '.baidu.jp'], 109 'FreshBot' => ['.seznam.cz'], 110 'Seznam' => ['.seznam.cz'], 111 ]; 112 113 /** 114 * Some search engines operate from designated IP addresses. 115 * 116 * @see https://www.apple.com/go/applebot 117 * @see https://help.duckduckgo.com/duckduckgo-help-pages/results/duckduckbot 118 */ 119 private const ROBOT_IPS = [ 120 'AppleBot' => [ 121 '17.0.0.0/8', 122 ], 123 'Ask Jeeves' => [ 124 '65.214.45.143', 125 '65.214.45.148', 126 '66.235.124.192', 127 '66.235.124.7', 128 '66.235.124.101', 129 '66.235.124.193', 130 '66.235.124.73', 131 '66.235.124.196', 132 '66.235.124.74', 133 '63.123.238.8', 134 '202.143.148.61', 135 ], 136 'DuckDuckBot' => [ 137 '23.21.227.69', 138 '50.16.241.113', 139 '50.16.241.114', 140 '50.16.241.117', 141 '50.16.247.234', 142 '52.204.97.54', 143 '52.5.190.19', 144 '54.197.234.188', 145 '54.208.100.253', 146 '54.208.102.37', 147 '107.21.1.8', 148 ], 149 ]; 150 151 /** 152 * Some search engines operate from within a designated autonomous system. 153 * 154 * @see https://developers.facebook.com/docs/sharing/webmasters/crawler 155 * @see https://www.facebook.com/peering/ 156 */ 157 private const ROBOT_ASNS = [ 158 'facebook' => ['AS32934', 'AS63293'], 159 'twitter' => ['AS13414'], 160 ]; 161 162 /** 163 * @param ServerRequestInterface $request 164 * @param RequestHandlerInterface $handler 165 * 166 * @return ResponseInterface 167 */ 168 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 169 { 170 $ua = Validator::serverParams($request)->string('HTTP_USER_AGENT', ''); 171 $ip = Validator::attributes($request)->string('client-ip'); 172 $address = IPFactory::parseAddressString($ip); 173 assert($address instanceof AddressInterface); 174 175 foreach (self::BAD_ROBOTS as $robot) { 176 if (str_contains($ua, $robot)) { 177 return $this->response(); 178 } 179 } 180 181 foreach (self::ROBOT_REV_FWD_DNS as $robot => $valid_domains) { 182 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, false)) { 183 return $this->response(); 184 } 185 } 186 187 foreach (self::ROBOT_REV_ONLY_DNS as $robot => $valid_domains) { 188 if (str_contains($ua, $robot) && !$this->checkRobotDNS($ip, $valid_domains, true)) { 189 return $this->response(); 190 } 191 } 192 193 foreach (self::ROBOT_IPS as $robot => $valid_ips) { 194 if (str_contains($ua, $robot)) { 195 foreach ($valid_ips as $ip) { 196 $range = IPFactory::parseRangeString($ip); 197 198 if ($range instanceof RangeInterface && $range->contains($address)) { 199 continue 2; 200 } 201 } 202 203 return $this->response(); 204 } 205 } 206 207 foreach (self::ROBOT_ASNS as $robot => $asns) { 208 foreach ($asns as $asn) { 209 if (str_contains($ua, $robot)) { 210 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 211 if ($range->contains($address)) { 212 continue 2; 213 } 214 } 215 216 return $this->response(); 217 } 218 } 219 } 220 221 // Allow sites to block access from entire networks. 222 $block_asn = Validator::attributes($request)->string('block_asn', ''); 223 preg_match_all('/(AS\d+)/', $block_asn, $matches); 224 225 foreach ($matches[1] as $asn) { 226 foreach ($this->fetchIpRangesForAsn($asn) as $range) { 227 if ($range->contains($address)) { 228 return $this->response(); 229 } 230 } 231 } 232 233 return $handler->handle($request); 234 } 235 236 /** 237 * Check that an IP address belongs to a robot operator using a forward/reverse DNS lookup. 238 * 239 * @param string $ip 240 * @param array<string> $valid_domains 241 * @param bool $reverse_only 242 * 243 * @return bool 244 */ 245 private function checkRobotDNS(string $ip, array $valid_domains, bool $reverse_only): bool 246 { 247 $host = gethostbyaddr($ip); 248 249 if ($host === false) { 250 return false; 251 } 252 253 foreach ($valid_domains as $domain) { 254 if (str_ends_with($host, $domain)) { 255 return $reverse_only || $ip === gethostbyname($host); 256 } 257 } 258 259 return false; 260 } 261 262 /** 263 * Perform a whois search for an ASN. 264 * 265 * @param string $asn - The autonomous system number to query 266 * 267 * @return array<RangeInterface> 268 */ 269 private function fetchIpRangesForAsn(string $asn): array 270 { 271 return Registry::cache()->file()->remember('whois-asn-' . $asn, static function () use ($asn): array { 272 $mapper = static fn (AsnRouteInfo $route_info): ?RangeInterface => IPFactory::parseRangeString($route_info->route ?: $route_info->route6); 273 274 try { 275 $loader = new CurlLoader(self::WHOIS_TIMEOUT); 276 $whois = new Whois($loader); 277 $info = $whois->loadAsnInfo($asn); 278 $routes = $info->routes; 279 $ranges = array_map($mapper, $routes); 280 281 return array_filter($ranges); 282 } catch (Throwable $ex) { 283 return []; 284 } 285 }, random_int(self::WHOIS_TTL_MIN, self::WHOIS_TTL_MAX)); 286 } 287 288 /** 289 * @return ResponseInterface 290 */ 291 private function response(): ResponseInterface 292 { 293 return response('Not acceptable', StatusCodeInterface::STATUS_NOT_ACCEPTABLE); 294 } 295} 296