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