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