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