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