8c1b7a8a06283eefb7bd3d475123d8afc6a69232
[friendica-addons.git/.git] / blockbot / blockbot.php
1 <?php
2 /**
3  * Name: blockbot
4  * Description: Blocking bots based on detecting bots/crawlers/spiders via the user agent and http_from header.
5  * Version: 0.2
6  * Author: Philipp Holzer <admin@philipp.info>
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  *
9  */
10
11 use Friendica\App;
12 use Friendica\Core\Hook;
13 use Friendica\Core\System;
14 use Friendica\DI;
15 use Jaybizzle\CrawlerDetect\CrawlerDetect;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Renderer;
18
19 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
20
21 function blockbot_install() {
22         Hook::register('init_1', __FILE__, 'blockbot_init_1');
23 }
24
25
26 function blockbot_uninstall() {
27         Hook::unregister('init_1', __FILE__, 'blockbot_init_1');
28 }
29
30 function blockbot_addon_admin(&$a, &$o) {
31         $t = Renderer::getMarkupTemplate("admin.tpl", "addon/blockbot/");
32
33         $o = Renderer::replaceMacros($t, [
34                 '$submit' => DI::l10n()->t('Save Settings'),
35                 '$good_crawlers' => ['good_crawlers', DI::l10n()->t('Allow "good" crawlers'), DI::config()->get('blockbot', 'good_crawlers'), "Don't block fediverse crawlers, relay servers and other bots with good purposes."],
36                 '$block_gab' => ['block_gab', DI::l10n()->t('Block GabSocial'), DI::config()->get('blockbot', 'block_gab'), 'Block the software GabSocial. This will block every access for that software. You can block dedicated gab instances in the blocklist settings in the admin section.'],
37                 '$training' => ['training', DI::l10n()->t('Training mode'), DI::config()->get('blockbot', 'training'), "Activates the training mode. This is only meant for developing purposes. Don't activate this on a production machine. This can cut communication with some systems."],
38         ]);
39 }
40
41 function blockbot_addon_admin_post(&$a) {
42         DI::config()->set('blockbot', 'good_crawlers', $_POST['good_crawlers'] ?? false);
43         DI::config()->set('blockbot', 'block_gab', $_POST['block_gab'] ?? false);
44         DI::config()->set('blockbot', 'training', $_POST['training'] ?? false);
45         info(DI::l10n()->t('Settings updated.'). EOL);
46 }
47
48 function blockbot_init_1(App $a) {
49         if (empty($_SERVER['HTTP_USER_AGENT'])) {
50                 return;
51         }
52
53         $logdata = ['agent' => $_SERVER['HTTP_USER_AGENT'], 'uri' => $_SERVER['REQUEST_URI']];
54
55         // List of "good" crawlers
56         $good_agents = ['fediverse.space crawler', 'fediverse.network crawler', 'Active_Pods_CheckBot_3.0',
57                         'Social-Relay/', 'Test Certificate Info', 'Uptimebot/', 'GNUSocialBot', 'UptimeRobot/'];
58
59         // List of known crawlers.
60         $agents = ['SemrushBot', 's~feedly-nikon3', 'Qwantify/Bleriot/', 'ltx71', 'Sogou web spider/',
61                 'Diffbot/', 'Twitterbot/', 'YisouSpider', 'evc-batch/', 'LivelapBot/', 'TrendsmapResolver/',
62                 'PaperLiBot/', 'Nuzzel', 'um-LN/', 'Google Favicon', 'Datanyze', 'BLEXBot/', '360Spider',
63                 'adscanner/', 'HeadlessChrome', 'wpif', 'startmebot/', 'Googlebot/', 'Applebot/',
64                 'facebookexternalhit/', 'GoogleImageProxy', 'bingbot/', 'heritrix/', 'ldspider',
65                 'AwarioRssBot/', 'Zabbix', 'TweetmemeBot/', 'dcrawl/', 'PhantomJS/', 'Googlebot-Image/',
66                 'CrowdTanglebot/', 'Mediapartners-Google', 'Baiduspider/', 'datagnionbot',
67                 'MegaIndex.ru/', 'SMUrlExpander', 'Hatena-Favicon/', 'Wappalyzer', 'FlipboardProxy/',
68                 'NetcraftSurveyAgent/', 'Dataprovider.com', 'SMTBot/', 'Nimbostratus-Bot/',
69                 'DuckDuckGo-Favicons-Bot/', 'IndieWebCards/', 'proximic', 'netEstate NE Crawler',
70                 'AhrefsBot/', 'YandexBot/', 'Exabot/', 'Mediumbot-MetaTagFetcher/', 'WhatsApp/',
71                 'TelegramBot', 'SurdotlyBot/', 'BingPreview/', 'SabsimBot/', 'CCBot/', 'WbSrch/',
72                 'DuckDuckBot-Https/', 'HTTP Banner Detection', 'YandexImages/', 'archive.org_bot',
73                 'ArchiveTeam ArchiveBot/', 'yacybot', 'https://developers.google.com/+/web/snippet/',
74                 'Scrapy/', 'github-camo', 'MJ12bot/', 'DotBot/', 'Pinterestbot/', 'Jooblebot/',
75                 'Cliqzbot/', 'YaK/', 'Mediatoolkitbot', 'Snacktory', 'FunWebProducts', 'oBot/',
76                 '7Siters/', 'KOCMOHABT', 'Google-SearchByImage', 'FemtosearchBot/',
77                 'HubSpot Crawler', 'DomainStatsBot/', 'Re-re Studio', 'AwarioSmartBot/',
78                 'SummalyBot/', 'DNSResearchBot/', 'PetalBot;', 'Nmap Scripting Engine;',
79                 'Google-Apps-Script; beanserver;', 'woorankreview/', 'Seekport Crawler;', 'AHC/',
80                 'SkypeUriPreview Preview/', 'Semanticbot/', 'Embed PHP library', 'XoviOnpageCrawler;',
81                 'GetHPinfo.com-Bot/', 'BoardReader Favicon Fetcher'];
82
83         if (!DI::config()->get('blockbot', 'good_crawlers')) {
84                 $agents = array_merge($agents, $good_agents);
85         } else {
86                 foreach ($good_agents as $good_agent) {
87                         if (stristr($_SERVER['HTTP_USER_AGENT'], $good_agent)) {
88                                 return;
89                         }
90                 }
91         }
92
93         if (DI::config()->get('blockbot', 'block_gab')) {
94                 $agents[] = 'GabSocial/';
95         }
96
97         foreach ($agents as $agent) {
98                 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
99                         System::httpExit(403, 'Bots are not allowed');
100                 }
101         }
102
103         // This switch here is only meant for developers who want to add more bots to the list above, it is not safe for production.
104         if (!DI::config()->get('blockbot', 'training')) {
105                 return;
106         }
107
108         $crawlerDetect = new CrawlerDetect();
109
110         if (!$crawlerDetect->isCrawler()) {
111                 logger::debug('Good user agent detected', $logdata);
112                 return;
113         }
114
115         // List of false positives' strings of known "good" agents.
116         $agents = ['curl', 'zgrab', 'Go-http-client', 'curb', 'github.com', 'reqwest', 'Feedly/',
117                 'Python-urllib/', 'Liferea/', 'aiohttp/', 'WordPress.com Reader', 'hackney/',
118                 'Faraday v', 'okhttp', 'UniversalFeedParser', 'PixelFedBot', 'python-requests',
119                 'WordPress/', 'http.rb/', 'Apache-HttpClient/', 'WordPress.com;', 'Pleroma',
120                 'Dispatch/', 'Ruby', 'Java/', 'libwww-perl/', 'Mastodon/',
121                 'lua-resty-http/', 'Tiny Tiny RSS/', 'Wget/', 'PostmanRuntime/',
122                 'W3C_Validator/', 'NetNewsWire', 'FeedValidator/'];
123
124         if (DI::config()->get('blockbot', 'good_crawlers')) {
125                 $agents = array_merge($agents, $good_agents);
126         }
127
128         foreach ($agents as $agent) {
129                 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {
130                         logger::notice('False positive', $logdata);
131                         return;
132                 }
133         }
134
135         logger::info('Blocked bot', $logdata);
136         System::httpExit(403, 'Bots are not allowed');
137 }