Настраиваем CloudFlare для фильтрации ботов

В этой статьей рассмотрим детальную настройку сервиса CloudFlare для защиты сайта от всевозможных роботов, ботов, парсеров.

Все мы знаем, что утро начинается не с кофе. Утро 4 августа для меня началось с сообщения:

Роботность 96% это перебор
Роботность 96% это перебор

Немного поразмыслив, вспомнил про мануал от Артёма Акулова, где он рассказывает, как фильтрует 99% ботов (включая ПФ ботов) с помощью несложной настройки CloudFlare (дальше CF) и сервиса AntiBot - рекомендую к прочтению.

Перечитав пост, понял что там не хватает крайне важных деталей, а именно самих настроек CF. Есть описание, что они должны делать, но нет самих переменных.

Артём отказался раскрывать детали 
Артём отказался раскрывать детали 

На мой запрос Артём так и не ответил, поэтому начал воссоздавать те самые правила самостоятельно.

Сталкивались с необходимостью фильтрации ботов?
Да, регулярно
Да, иногда
Не сталкивался

Кого фильтруем?

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

  • Пользователей из ненужных стран - подойдет, если у вас небольшой региональный коммерческий проект и зарубежного трафика там быть недолжно. Сомневаюсь, что бетон из Балашихи может быть интересен бразильцам.
  • Всех, кто приходит с IPV6 и без HTTPS заставляем разгадать каптчу:
Настраиваем CloudFlare для фильтрации ботов
  • Блокируем по списку юзерагентов различные сервисы-анализаторы, мониторинги и парсеры;
  • Отправляем на JS проверку всех, кто обращается по протоколу ниже HTTP/2 и прямые заходы. Многие спайдеры вроде Screaming Frog работают именно на протоколах HTTP1, тем самым мы можем на уровне CF запретить любой парсинг сайта;

Видео инструкция по настройке

Начинаем настройку

Я не буду расписывать как добавить сайт в CF, будем считать что вы разобрались.

Заходим в раздел Security - WAF

Настраиваем CloudFlare для фильтрации ботов

Жмём на кнопку Creat firewall rules

Настраиваем CloudFlare для фильтрации ботов

Всего нам доступны 5 правил, но в рамках одного правила мы можем комбинировать несколько фильтров, если они подразумевают одно и тоже действие. Всего предусмотрено 5 действий:

  • Block— блокировка доступа.
  • Challenge (CAPTCHA)— включение проверки с помощью Google reCAPTCHA.
  • JS Challenge— показ межстраничного уведомления как при включении режима I’m Under Attack.
  • Bypass— отключение проверки.
  • Allow — полный доступ.

Дальше мы начинаем создавать фильтры. Обратите внимание, что ВАЖЕН ПОРЯДОК СОЗДАНИЯ. Чем раньше создано правило, тем оно приоритетнее. Приоритет можно менять перетаскиванием:

Настраиваем CloudFlare для фильтрации ботов

Дополнительные условия

And — правило сработает, когда оба условия соблюдаются.

Or — правило сработает, когда соблюдается хотя бы одно условие.

Как легко добавлять правила

Настройки можно вбивать вручную, либо использовать поле "Edit expression"

Настраиваем CloudFlare для фильтрации ботов

Открываем доступ хорошим ботам

В первую очередь открываем доступ хорошим ботам. Обратите внимание, что отдельной настройкой надо пустить Mail.ru, CF, как и многие другие не считают его хорошим.

Настраиваем CloudFlare для фильтрации ботов

Правило: (cf.client.bot) or (http.user_agent contains "Mail.RU_Bot")

Действие: Allow

Закрываем доступ из всех стран, кроме ...

Полезно, если вы уверены, что трафика из других стран у вас нет. Проверить можно с помощью Яндекс.Метрики в разделе Аудитория - География;

Пример распределения посетителей по ГЕО
Пример распределения посетителей по ГЕО

Логика фильтра следующая: Если страна не "Россия", то заблокировать

Настраиваем CloudFlare для фильтрации ботов

Правило: (ip.geoip.country ne "RU" and ip.geoip.country ne "BY" and ip.geoip.country ne "KZ")

Действие: Block

Показываем капчу всем, кто ломится по IPV6 или HTTP

Важно! Необходимо включить принудительный редирект с HTTP на HTTPS:

SSL/TLS - Edge Certificates - Always Use HTTPS

Настраиваем CloudFlare для фильтрации ботов
Настраиваем CloudFlare для фильтрации ботов

Правило: (ip.src in {::/0}) or (not ssl)

Действие: LEGACY CAPTCHA

JS проверка для прямых заходов и обращений с протоколом ниже HTTP/2

В данном правиле фильтруем всех, кто использует HTTP 1 и HTTP 1.1 протоколы. Чаще всего это боты. Тут же фильтруем ПФ ботов, которые прогревают профили через прямые заходы на различные сайты.

Начало прогрева профилей через ваш сайт выглядит примерно так:

Настраиваем CloudFlare для фильтрации ботов

Запрещаем доступ всем, кто не HTTP2 протокол, говноботы, ддос-боты и прочее непотребство идет в основном по HTTP/1.0 и HTTP/1.1

https://wmsn.biz/m.php?p=143697
Настраиваем CloudFlare для фильтрации ботов

Правило: (not http.request.version in {"HTTP/2" "HTTP/3" "SPDY/3.1"}) or (http.referer eq "")

Действие: Block или JS challenge.

Блокируем краулеры

Краулеры, парсеры и прочие проверяльщики создают бешенную нагрузку на крупных ресурсах. Можно их отсекать еще на подлёте. Актуальные юзерагенты взяты отсюда и адаптированы под CF. Опционально можно запретить доступ для сохранения данных в вебархиве с помощью блокировки юзерагента ia_archiver

Настраиваем CloudFlare для фильтрации ботов

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

Правило 1:

(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") or (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")

Правило 2:

(http.user_agent contains "memoryBot") or (http.user_agent contains "Microsoft URL Control") or (http.user_agent contains "MIIxpc") or (http.user_agent contains "Mippin") or (http.user_agent contains "Missigua Locator") or (http.user_agent contains "Mister PiX") or (http.user_agent contains "MJ12bot") or (http.user_agent contains "MLBot") or (http.user_agent contains "moget") or (http.user_agent contains "MSIECrawler") or (http.user_agent contains "msnbot") or (http.user_agent contains "msnbot-media") or (http.user_agent contains "NetAnts") or (http.user_agent contains "NICErsPRO") or (http.user_agent contains "Niki-Bot") or (http.user_agent contains "NjuiceBot") or (http.user_agent contains "NPBot") or (http.user_agent contains "Nutch") or (http.user_agent contains "Offline Explorer") or (http.user_agent contains "OLEcrawler") or (http.user_agent contains "Openfind") or (http.user_agent contains "panscient.com") or (http.user_agent contains "PostRank") or (http.user_agent contains "ProPowerBot/2.14") or (http.user_agent contains "PetalBot") or (http.user_agent contains "ProWebWalker") or (http.user_agent contains "ptd-crawler") or (http.user_agent contains "Purebot") or (http.user_agent contains "PycURL") or (http.user_agent contains "python-rcontainsuests") or (http.user_agent contains "Python-urllib") or (http.user_agent contains "QueryN Metasearch") or (http.user_agent contains "RepoMonkey") or (http.user_agent contains "Riddler") or (http.user_agent contains "RMA") or (http.user_agent contains "Scrapy") or (http.user_agent contains "SemrushBot") or (http.user_agent contains "serf") or (http.user_agent contains "SeznamBot") or (http.user_agent contains "SISTRIX") or (http.user_agent contains "SiteBot") or (http.user_agent contains "sitecheck.Internetseer.com") or (http.user_agent contains "SiteSnagger") or (http.user_agent contains "Serpstat") or (http.user_agent contains "Slurp") or (http.user_agent contains "SnapPreviewBot") or (http.user_agent contains "Sogou") or (http.user_agent contains "Soup") or (http.user_agent contains "SpankBot") or (http.user_agent contains "spanner") or (http.user_agent contains "spbot") or (http.user_agent contains "Spinn3r") or (http.user_agent contains "SpyFu") or (http.user_agent contains "suggybot") or (http.user_agent contains "SurveyBot") or (http.user_agent contains "suzuran") or (http.user_agent contains "SWeb") or (http.user_agent contains "Szukacz/1.4") or (http.user_agent contains "Teleport") or (http.user_agent contains "Telesoft") or (http.user_agent contains "The Intraformant") or (http.user_agent contains "TheNomad") or (http.user_agent contains "TightTwatBot") or (http.user_agent contains "Titan") or (http.user_agent contains "toCrawl/UrlDispatcher") or (http.user_agent contains "True_Robot") or (http.user_agent contains "ttCrawler") or (http.user_agent contains "turingos") or (http.user_agent contains "TurnitinBot") or (http.user_agent contains "UbiCrawler") or (http.user_agent contains "UnisterBot") or (http.user_agent contains "Unknown") or (http.user_agent contains "uptime files") or (http.user_agent contains "URLy Warning") or (http.user_agent contains "User-Agent") or (http.user_agent contains "VCI") or (http.user_agent contains "Vedma") or (http.user_agent contains "Voyager") or (http.user_agent contains "WBSearchBot") or (http.user_agent contains "Web Downloader/6.9") or (http.user_agent contains "Web Image Collector") or (http.user_agent contains "WebAuto") or (http.user_agent contains "WebBandit") or (http.user_agent contains "WebCopier") or (http.user_agent contains "WebEnhancer") or (http.user_agent contains "WebmasterWorldForumBot") or (http.user_agent contains "WebReaper") or (http.user_agent contains "WebSauger") or (http.user_agent contains "Website Quester") or (http.user_agent contains "Webster Pro") or (http.user_agent contains "WebStripper") or (http.user_agent contains "WebZip") or (http.user_agent contains "Wotbox") or (http.user_agent contains "wsr-agent") or (http.user_agent contains "WWW-Collector-E") or (http.user_agent contains "Yeti")

Действие: Block

Проверяем корректность правил

Проверить корректность правил можно двумя способами.

Первый способ

  • Следим за отчётом CF
  • Мониторим системы аналитики и контролируем отклонения.
Настраиваем CloudFlare для фильтрации ботов

Второй способ

  • Меняем страну через VPN и пробуем попасть на сайт. Если блок работает - вас не пустит;
  • С помощью сервиса Bertal.ru меняем юзерагент и пробуем отправить запрос на сайт, тут же проверяем фильтрацию HTTP трафика.
  • Если включен фильтр на прямой трафик - пробуем просто зайти по прямому адресу.

Заключение

Когда мануал был готов, выяснилось, что почти 100% трафика на проекте накручивается.
Когда мануал был готов, выяснилось, что почти 100% трафика на проекте накручивается.

Для подготовки материала использовал источники:

  • https://wmsn.biz/m.php?p=143697
  • https://highload.today/cloudflare-ddos/#7
  • https://g-soft.info/articles/1307/cloudflare-blokirovka-dostupa-k-saytu-s-opredelennyh-stran/
  • https://byroot.ru/153-blokirovka-ipv6-cherez-cloudflare.html
  • https://seo-zona.ru/badbot
  • https://vc.ru/seo/359664-voskreshaem-internet-magazin-avtozapchastey-i-delaem-20-mln-rubley-na-seo-trafike
631631 показ
37K37K открытий
75 комментариев

Спасибо за мануал, хорошее дело. Но пара спорных моментов:
а) А точно стоит выстраивать всю эту оборону на сайте не под атакой? Это ж дело такое, когда с водой можно и ребенка выплеснуть. Скажем, известен инцидент, когда сайт влетел под фильтры, и несмотря на правки яндексоиды их не принимали - потому что не видели. Оказалось, что доступно 2 зеркала - одно по ipv4, другое - ipv6. Яндексоиды и их бот ходили по ipv6, и исправлений не видели. Да и поисковые боты используют http2 совсем даже не всегда, и так можно подсократить процессы сканирования, и без того уже дохловатые в рамках всего интернета.
б) Список блокируемых ботов и парсеров я бы сильно проредил. Это не стоит копипастить, это стоит подбирать по проекту индивидуально.

Ответить

Спасибо, как всегда замечания по делу.
а) В самом начале уточняю что в видео, что в статье, что использовать все правила не стоит, а выборочно под проект.
б) Имеет место быть, список нужно собирать по логам сервера для конкретного проекта

Ответить

А зачем блокировать IPV6? Вы хотите еще больше затормозить переход на этот протокол?

Ответить

Ну, а сколько реальных людей в рамках РФ ходят по ipv6? Процентов 5-7 наберется? А теперь учтём, что цена проксей на этом протоколе - в разы дешевле ipv4, да и свои прокси поднять на ipv6 легче лёгкого. Вот и получается, что для многих сайтов, где и без того под 80% всего мизерного трафа - боты, блок ipv6 в минус никак не сыграет вообще, только в плюс.

Ответить

Вот для этого

Ответить

Сомневаюсь что статья на VC затормозит переход на IPv6, при этом в данный момент живых пользователей на этом протоколе - минимум

Ответить

...получается, если бот будет использовать user-agent маил. ru, тогда на сайте автора проблем у него не будет..

Ответить