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