Cloudflare против Bots

Как уже ранее здесь публиковалось, что защищать свой сайт от ботов можно с помощью стандартного серверного программного обеспечения fail2ban. Но так же можно и спомощью CloudFlare, конечно если вы использует этот сервис для своего сайта. Если используете, то знаете, что и как там выглядит и как примерно это работает. Эта статья моя заметка, а не пошаговое руководство. материалы собирал, корректировал под себя естественно по сети. Пробовал и испытывал на своём сайте morikoff.ru.

Покажу несколько ключевых экранов, по которым можно понять, что и где нужно делать настройки. Но пояснять это не смогу в силу объёмности материала. Стоит отметить, что CloudFlare не стоят на месте, и постоянно, что-то улучшают, в том числе и переделываю все свои дашборды – экраны настроект, меняют разделы и меню. Так, что за ними не угнаться если пытаться писать инструкции.

Хотите лучше понять как всё работает, то у CloudFlare есть хорошая справка, на английском. Система мощная, и нужная для интернет сайтов. Но есть проблема, это всё чаще сегментируется в наше время.

И так, делаем Веб-брандмауэр на уровне зоны (WAF) обнаруживает и смягчает вредоносные запросы по всему трафику в соответствии с этой зоной.

Добавляем в рамках бесплатного аккаунта, всего пять правил, да и то ограниченного объёма. Да и в принципе хватает для основного. Выглядит так, см. ниже (изображения кликабельные):

Правила Веб-брандмауэра (WAF)

Правила проще вносить через поле Expression Preview, просто копипастом.

Если в процессе эксплуатации возникнут сомнения в действии всего этого, то правила можно временно отключать без удаления. Теперь переходим к этим правилам, которые вы можете изучить, а потом подстраивать под себя.


1. Разрешить доступ ботам поисковых систем Яндекс и Google

(http.user_agent contains "Google") or (http.user_agent contains "Yandex") or (http.user_agent contains "Googlebot")

Режим: Skip

Резюме: Разрешить заходить на сайт поисковым серверам надо. Однозначно.


2. Разрешить запросы с вашего собственного хостинга

(ip.geoip.asnum eq 15582) or (ip.geoip.asnum eq 9123) or (ip.geoip.asnum eq 8595) or (ip.geoip.asnum eq 8732) or (http.request.uri contains "/wp-cron.php")

Режим: Skip

В этом правиле используется ASNUM, который узнавать можно тут https://hackertarget.com/as-ip-lookup/ по ip-адресу вашего хостинга. Или спрашивайте своего хостинг-провайдера.

Резюме: Не надо запрещать самому сайту, или себе и коллегам ходить по сайту как привелигерованный пользователь ресурса. Как добавить другие сети, или ip-адреса сами смотрите.


3.1. Запретить доступ для пользователей из стран

(ip.geoip.country in {"CN" "UA" "IR" "IN" "SG" "GB" "PL" "ID" "TH" "HK" "CH" "BG" "CZ" "SC" "CA"}) or (ip.geoip.continent eq "AF") or (http.user_agent contains "ahrefs.com") or (http.user_agent contains "Abonti") or (http.user_agent contains "AspiegelBot") or (http.user_agent contains "aggregator") or (http.user_agent contains "AhrefsBot") or (http.user_agent contains "Aport") or (http.user_agent contains "asterias") or (http.user_agent contains "Baiduspider") or (http.user_agent contains "BDCbot") or (http.user_agent contains "bidswitchbot") or (http.user_agent contains "Birubot") or (http.user_agent contains "BLEXBot") or (http.user_agent contains "BUbiNG") or (http.user_agent contains "BuiltBotTough") or (http.user_agent contains "Bullseye") or (http.user_agent contains "BunnySlippers") or (http.user_agent contains "Butterfly") or (http.user_agent contains "ca-crawler") or (http.user_agent contains "CamontSpider") or (http.user_agent contains "CCBot") or (http.user_agent contains "Cegbfeieh") or (http.user_agent contains "CheeseBot") or (http.user_agent contains "CherryPicker") or (http.user_agent contains "coccoc") or (http.user_agent contains "CopyRightCheck") or (http.user_agent contains "cosmos") or (http.user_agent contains "crawler")

Режим: Block

Резюме: Сперва мы разрешили, а теперь запретили. Это имеет значение.


3.2. Запретить доступ для пауков и ботов

(http.user_agent contains "Crescent") or (http.user_agent contains "CyotekWebCopy/1.7") or (http.user_agent contains "CyotekHTTP/2.0") or (http.user_agent contains "DataForSeoBot") or (http.user_agent contains "DeuSu") or (http.user_agent contains "discobot") or (http.user_agent contains "DittoSpyder") or (http.user_agent contains "DnyzBot") or (http.user_agent contains "DomainCrawler") or (http.user_agent contains "DotBot") or (http.user_agent contains "Download Ninja") or (http.user_agent contains "EasouSpider") or (http.user_agent contains "EmailCollector") or (http.user_agent contains "EmailSiphon") or (http.user_agent contains "EmailWolf") or (http.user_agent contains "EroCrawler") or (http.user_agent contains "Exabot") or (http.user_agent contains "ExtractorPro") or (http.user_agent contains "Ezooms") or (http.user_agent contains "FairShare") or (http.user_agent contains "Fasterfox") or (http.user_agent contains "FeedBooster") or (http.user_agent contains "Foobot") or (http.user_agent contains "Genieo") or (http.user_agent contains "GetIntent Crawler") or (http.user_agent contains "Gigabot") or (http.user_agent contains "gold crawler") or (http.user_agent contains "GrapeshotCrawler") or (http.user_agent contains "grub-client") or (http.user_agent contains "Harvest") or (http.user_agent contains "hloader") or (http.user_agent contains "httplib") or (http.user_agent contains "HTTrack") or (http.user_agent contains "humanlinks") or (http.user_agent contains "HybridBot") or (http.user_agent contains "ia_archiver") or (http.user_agent contains "ieautodiscovery") or (http.user_agent contains "Incutio") or (http.user_agent contains "InfoNaviRobot") or (http.user_agent contains "InternetSeer") or (http.user_agent contains "IstellaBot") or (http.user_agent contains "Java") or (http.user_agent contains "Java/1.") or (http.user_agent contains "JamesBOT") or (http.user_agent contains "JennyBot") or (http.user_agent contains "JS-Kit") or (http.user_agent contains "k2spider") or (http.user_agent contains "Kenjin Spider") or (http.user_agent contains "Keyword Density/0.9") or (http.user_agent contains "kmSearchBot") or (http.user_agent contains "larbin") or (http.user_agent contains "LexiBot") or (http.user_agent contains "libWeb") or (http.user_agent contains "libwww") or (http.user_agent contains "Linguee") or (http.user_agent contains "LinkExchanger") or (http.user_agent contains "LinkextractorPro") or (http.user_agent contains "linko") or (http.user_agent contains "LinkScan/8.1a Unix") or (http.user_agent contains "LinkWalker") or (http.user_agent contains "LinkpadBot") or (http.user_agent contains "lmspider") or (http.user_agent contains "LNSpiderguy") or (http.user_agent contains "ltx71") or (http.user_agent contains "lwp-trivial") or (http.user_agent contains "lwp-trivial") or (http.user_agent contains "magpie") or (http.user_agent contains "Mata Hari") or (http.user_agent contains "MaxPointCrawler") or (http.user_agent contains "MegaIndex")

Режим: Block

Резюме: Найти списки ботов можно в сети. Исправляйте и добавляйте как вам нравится.


4. Блокировать известных ботов, уже идентифицированных как вредоносные

(ip.src in {::/0}) or (not ssl) or (not http.request.version in {"HTTP/2" "HTTP/3" "SPDY/3.1"})

Если вы наблюдаете множество ботов, приходящих напрямую без реферера, то необходимо добавить и использовать ещё и такое условие, которое будет запускать капчу тем, кто не по реферальной ссылке приходит (прямой заход делают как правило боты):

or (http.referer eq "")

Режим Managed Challenge


Вывод

Благодаря этим настройкам, удаётся отфильтровывать почти до 99% ботов. Найти журналы работы CloudFlare вы сможете сами. Скажу так, что до использования такого метода мой рабочий сайт имел до 1200 соединений, что изрядно нагружало веб-сервер и мониторинг показывал постоянную нагрузку в 70%. Всё это удалось преодолеть. Спасибо бесплатному аккаунту в CloudFlare.

P.S. Почему правило под номером 3 разделено на пару, просто сервис не давал вводить такое объёмное правило и пришлось его порезать.


UPDATE: После того как заблокировали IP-адрес выдаваемый сайту в DNS на Claudeflare – мне пришлось попробовать всё это дело настроить локально на своём же сервере. Всё сделано с помощью fail2ban. В том числе блокировка по странам, что для меня было на первом месте, т.к. Сингапур с Вьетнамом и сканерами своими просто достали)))

Опубликовано в категории: БЛОГ