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