4 * Description: Blocking bots based on detecting bots/crawlers/spiders via the user agent and http_from header.
6 * Author: Philipp Holzer <admin@philipp.info>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
11 use Friendica\Core\Hook;
13 use Jaybizzle\CrawlerDetect\CrawlerDetect;
14 use Friendica\Core\Logger;
15 use Friendica\Core\Renderer;
16 use Friendica\Network\HTTPException\ForbiddenException;
18 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
20 function blockbot_install()
22 Hook::register('init_1', __FILE__, 'blockbot_init_1');
25 function blockbot_addon_admin(string &$o)
27 $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/blockbot/');
29 $o = Renderer::replaceMacros($t, [
30 '$submit' => DI::l10n()->t('Save Settings'),
31 '$good_crawlers' => ['good_crawlers', DI::l10n()->t('Allow "good" crawlers'), DI::config()->get('blockbot', 'good_crawlers'), DI::l10n()->t("Don't block fediverse crawlers, relay servers and other bots with good purposes.")],
32 '$socialmedia_agents' => ['socialmedia_agents', DI::l10n()->t('Allow preview agents'), DI::config()->get('blockbot', 'socialmedia_agents'), DI::l10n()->t("Don't block agents from social media systems that want to generate preview data for links that had been set by their users.")],
33 '$http_libraries' => ['http_libraries', DI::l10n()->t('Allow generic HTTP libraries'), DI::config()->get('blockbot', 'http_libraries'), DI::l10n()->t("Don't block agents from generic HTTP libraries that could be used for good or for bad and that currently can't be traced back to any known Fediverse project.")],
34 '$block_gab' => ['block_gab', DI::l10n()->t('Block GabSocial'), DI::config()->get('blockbot', 'block_gab'), DI::l10n()->t('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.')],
35 '$training' => ['training', DI::l10n()->t('Training mode'), DI::config()->get('blockbot', 'training'), DI::l10n()->t("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.")],
39 function blockbot_addon_admin_post()
41 DI::config()->set('blockbot', 'good_crawlers', $_POST['good_crawlers'] ?? false);
42 DI::config()->set('blockbot', 'socialmedia_agents', $_POST['socialmedia_agents'] ?? false);
43 DI::config()->set('blockbot', 'http_libraries', $_POST['http_libraries'] ?? false);
44 DI::config()->set('blockbot', 'block_gab', $_POST['block_gab'] ?? false);
45 DI::config()->set('blockbot', 'training', $_POST['training'] ?? false);
48 function blockbot_init_1()
50 if (empty($_SERVER['HTTP_USER_AGENT'])) {
54 $logdata = ['agent' => $_SERVER['HTTP_USER_AGENT'], 'uri' => $_SERVER['REQUEST_URI']];
56 // List of known unwanted crawlers.
58 'SemrushBot', 's~feedly-nikon3', 'Qwantify/Bleriot/', 'ltx71', 'Sogou web spider/',
59 'Diffbot/', 'YisouSpider', 'evc-batch/', 'LivelapBot/', 'TrendsmapResolver/',
60 'PaperLiBot/', 'Nuzzel', 'um-LN/', 'Google Favicon', 'Datanyze', 'BLEXBot/', '360Spider',
61 'adscanner/', 'HeadlessChrome', 'wpif', 'startmebot/', 'Googlebot/', 'Applebot/',
62 'GoogleImageProxy', 'bingbot/', 'heritrix/', 'ldspider',
63 'AwarioRssBot/', 'TweetmemeBot/', 'dcrawl/', 'PhantomJS/', 'Googlebot-Image/',
64 'CrowdTanglebot/', 'Mediapartners-Google', 'Baiduspider', 'datagnionbot',
65 'MegaIndex.ru/', 'SMUrlExpander', 'Hatena-Favicon/', 'Wappalyzer', 'FlipboardProxy/',
66 'NetcraftSurveyAgent/', 'Dataprovider.com', 'SMTBot/', 'Nimbostratus-Bot/',
67 'DuckDuckGo-Favicons-Bot/', 'IndieWebCards/', 'proximic', 'netEstate NE Crawler',
68 'AhrefsBot/', 'YandexBot/', 'Exabot/', 'Mediumbot-MetaTagFetcher/',
69 'SurdotlyBot/', 'BingPreview/', 'SabsimBot/', 'CCBot/', 'WbSrch/',
70 'DuckDuckBot-Https/', 'HTTP Banner Detection', 'YandexImages/', 'archive.org_bot',
71 'ArchiveTeam ArchiveBot/', 'yacybot', 'https://developers.google.com/+/web/snippet/',
72 'Scrapy/', 'MJ12bot/', 'DotBot/', 'Pinterestbot/', 'Jooblebot/',
73 'Cliqzbot/', 'YaK/', 'Mediatoolkitbot', 'Snacktory', 'FunWebProducts', 'oBot/',
74 '7Siters/', 'KOCMOHABT', 'Google-SearchByImage', 'FemtosearchBot/',
75 'HubSpot Crawler', 'DomainStatsBot/', 'Re-re Studio', 'AwarioSmartBot/',
76 'DNSResearchBot/', 'PetalBot;', 'Nmap Scripting Engine;',
77 'Google-Apps-Script; beanserver;', 'woorankreview/', 'Seekport Crawler;', 'AHC/',
78 'Semanticbot/', 'XoviOnpageCrawler;', 'Pinterest/',
79 'GetHPinfo.com-Bot/', 'BoardReader Favicon Fetcher', 'Google-Adwords-Instant', 'newspaper/',
80 'YurichevBot/', 'Crawling at Home Project', 'InfoTigerBot/', 'AdIdxBot/',
81 'MicrosoftPreview/', 'masscan/', 'Timpibot/', 'everyfeed-spider/', 'AndroidDownloadManager/',
82 'WebZIP/', 'WDG_Validator/', 'Screaming Frog SEO Spider/', ' Bytespider;', 'ISSCyberRiskCrawler/',
83 'BitSightBot/', 'ev-crawler/', 'CensysInspect/1.1', 'Protopage/', 'Gaisbot/', 'WellKnownBot/',
84 'SuperBot/', 'Googlebot-Mobile/', 'GPTBot/', 'GenomeCrawlerd/', '2ip bot/', 'Ocarinabot',
85 'Yahoo! Slurp;', 'AdsBot-Google', 'Gregarius/', 'FAST-WebCrawler/', 'Xenu Link Sleuth/',
86 'Ask Jeeves', 'alexa site audit/', 'Yahoo! Slurp China;', 'Microsoft URL Control',
87 'Facebot', 'Googlebot-Video/', 'msnbot/', 'Offline Explorer/', 'YandexNews/', 'msnbot-media/',
88 'EmailWolf', 'Download Demon/', 'FeedFetcher-Google;', 'WebCopier', '+ONB_Bot_Btrix',
89 'scoopit-crawler/', 'ia_archiver', 'Quora-Bot/', 'WebwikiBot/', 'FullStoryBot/',
90 'wpbot/', 'SearchExpress', 'DuckDuckBot/', 'Google Web Preview',
93 if (DI::config()->get('blockbot', 'block_gab')) {
94 $agents[] = 'GabSocial/';
97 // List of "good" crawlers, mostly from the fediverse.
99 'fediverse.space crawler', 'fediverse.network crawler', 'Active_Pods_CheckBot_3.0',
100 'Social-Relay/', 'Test Certificate Info', 'Uptimebot/', 'GNUSocialBot', 'UptimeRobot/',
101 'PTST/', 'Zabbix', 'Poduptime/', 'FediFetcher', 'lemmy-stats-crawler',
102 'FedditLemmyverseCrawler/', 'lemmy-explorer-crawler/', 'URIports Validator',
103 'rss-is-dead.lol web bot;', 'fedistatsCrawler/', 'W3C_CSS_Validator_JFouffa/',
104 'IABot/', 'Slackbot 1', 'BeeperBot/', 'Matrix-Media-Repo/', 'P3P Validator',
108 if (!DI::config()->get('blockbot', 'good_crawlers')) {
109 $agents = array_merge($agents, $good_agents);
110 } elseif (blockbot_match($good_agents)) {
114 // List of agents from social media systems that fetch preview data via opem graph or twitter cards.
115 $socialmedia_agents = ['Twitterbot', 'facebookexternalhit/', 'SkypeUriPreview Preview/',
116 'TelegramBot', 'WhatsApp/', 'github-camo', 'Bluesky Cardyb/', 'XING-contenttabreceiver/',
117 'LinkedInBot/', 'Instagram ', 'Synapse (bot; ', 'Discordbot/', 'SummalyBot/',
118 'Slackbot-LinkExpanding', 'Slack-ImgProxy', 'Iframely/',
121 if (!DI::config()->get('blockbot', 'socialmedia_agents')) {
122 $agents = array_merge($agents, $socialmedia_agents);
123 } elseif (blockbot_match($socialmedia_agents)) {
128 $http_libraries = ['ReactorNetty/', 'GuzzleHttp/', 'Embed PHP library', 'python-urllib3/',
129 'EventMachine HttpClient', 'HTMLParser/'
132 if (!DI::config()->get('blockbot', 'http_libraries')) {
133 $agents = array_merge($agents, $http_libraries);
134 } elseif (blockbot_match($http_libraries)) {
138 if (blockbot_match($agents)) {
139 throw new ForbiddenException('Bots are not allowed. If you consider this a mistake, create an issue at https://github.com/friendica/friendica');
142 // This switch here is only meant for developers who want to add more bots to the list above, it is not safe for production.
143 if (!DI::config()->get('blockbot', 'training')) {
147 $crawlerDetect = new CrawlerDetect();
149 if (!$crawlerDetect->isCrawler()) {
150 logger::debug('Good user agent detected', $logdata);
154 // List of known "good" agents, mostly used by Fediverse systems, feed readers, ...
156 'curl', 'zgrab', 'Go-http-client', 'curb', 'github.com', 'reqwest', 'Feedly/',
157 'Python-urllib/', 'Liferea/', 'aiohttp/', 'WordPress.com Reader', 'hackney/',
158 'Faraday v', 'okhttp', 'UniversalFeedParser', 'PixelFedBot', 'python-requests',
159 'WordPress/', 'http.rb/', 'Apache-HttpClient/', 'WordPress.com;', 'Pleroma',
160 'Dispatch/', 'Ruby', 'Java/', 'libwww-perl/', 'Mastodon/', 'FeedlyApp/',
161 'lua-resty-http/', 'Tiny Tiny RSS/', 'Wget/', 'PostmanRuntime/',
162 'W3C_Validator/', 'NetNewsWire', 'FeedValidator/', 'theoldreader.com', 'axios/',
163 'Paw/', 'PeerTube/', 'fedi.inex.dev', 'FediDB/', 'index.community crawler',
164 'Slackbot-LinkExpanding', 'Firefish/', 'Takahe/', 'Akkoma ', 'Misskey/', 'Lynx/',
165 'camo-rs asset proxy', 'gotosocial/', 'incestoma ', 'SpaceCowboys Android RSS Reader',
166 'NewsBlur Feed Finder', 'Lemmy/', 'enby-town/', 'rss2tg bot;', '; HTTrack ',
167 'MbinBot', 'kbinBot', 'Pixelfed/', 'NewsBlur Feed Fetcher', 'NewsBlur Page Fetcher',
170 if (blockbot_match($agents)) {
171 logger::info('False positive', $logdata);
175 logger::notice('Blocked bot', $logdata);
176 throw new ForbiddenException('Bots are not allowed. If you consider this a mistake, create an issue at https://github.com/friendica/friendica');
179 function blockbot_match(array $agents)
181 foreach ($agents as $agent) {
182 if (stristr($_SERVER['HTTP_USER_AGENT'], $agent)) {