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