{"id":14289,"url":"\/distributions\/14289\/click?bit=1&hash=892464fe46102746d8d05914a41d0a54b0756f476a912469a2c12e8168d8a933","title":"\u041e\u0434\u0438\u043d \u0438\u043d\u0441\u0442\u0440\u0443\u043c\u0435\u043d\u0442 \u0443\u0432\u0435\u043b\u0438\u0447\u0438\u043b \u043f\u0440\u043e\u0434\u0430\u0436\u0438 \u043d\u0430 5%, \u0430 \u0441\u0440\u0435\u0434\u043d\u0438\u0439 \u0447\u0435\u043a \u2014 \u043d\u0430 20%","buttonText":"","imageUuid":""}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Действие: Allow

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

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

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

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

Правило: (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

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

Действие: LEGACY CAPTCHA

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

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

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

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

https://wmsn.biz/m.php?p=143697

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

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

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

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

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

Правило 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
  • Мониторим системы аналитики и контролируем отклонения.

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

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

Заключение

Когда мануал был готов, выяснилось, что почти 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
0
75 комментариев
Написать комментарий...
Roman Skulkin

Кто может решить вопрос с ботами? На паре сайтов количество трафика с роботами кратно превышает основной трафик. Подключил сервис botfaqtor, но этих роботов не блокирует. А они сильно ухудшают поведенческие на сайтах.

Ответить
Развернуть ветку
Mik Foxi

Антибот решает проблему поведенческих.

Ответить
Развернуть ветку
Эрик Куралов

А антибот с CF если поставить? Это убережет? Потому что CF снизил % роботности с 20 до 14, но это все равно много :( хочется до 7% снизить

Ответить
Развернуть ветку
Mik Foxi

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

Ответить
Развернуть ветку
павлуша морозов

Привет, нашел хоть где-то упоминание об этом в интернете! У меня похоже та самая ситуация после установки клауда и настройки как описано в статье резко в яндекс метрике появились внутренние переходы. Похоже в реальности это прямые заходы. Что можно с этим сделать?

Ответить
Развернуть ветку
antiddos24

Внутренние переходы - это в том числе и прямые заходы, только попавшие под проверку и прошедшие ее.
Нужно смотреть ваши правила и что лишнее вы закинули под капчу или проверку браузера.

Ответить
Развернуть ветку
72 комментария
Раскрывать всегда