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