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