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