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