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