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