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