Инструкция для RouterOS 7.x. Здесь нет отдельных шаблонов: команды выполняются
по порядку прямо в терминале MikroTik.
Схема имеет **две степени блокировки**, а не три:
1. первое нарушение — полный бан IP с WAN на `15m`, история нарушения хранится
`30d`;
2. повторное нарушение в течение этих `30d` — постоянный бан без timeout.
Списки `security-strikes-*` — это только история для определения повтора. Это не
третья степень блокировки.
## 1. Перед выполнением
Подключиться из LAN/VPN, включить Safe Mode (`Ctrl+X`) и проверить, что внешний
интерфейс входит в список `WAN`:
```routeros
/interface list member print detail where list="WAN"
/ip firewall raw print detail without-paging
/ip firewall filter print detail without-paging
/ip firewall nat print detail without-paging
```
Сделать backup и скачать оба файла с MikroTik:
```routeros
/export show-sensitive=no file=before-scanner-flood
/system backup save name=before-scanner-flood
/file print where name~"before-scanner-flood"
```
Если внешний interface-list называется не `WAN`, заменить `WAN` во всех командах
ниже. Если наружу опубликованы не только `80,443`, изменить список портов в
правиле `SCANBLOCK-SEC: inspect published web SYN rate`.
## 2. Добавить правила
Команды рассчитаны на чистую установку. Повторно их не выполнять, иначе появятся
дубликаты.
```routeros
/ip firewall raw add chain=prerouting action=drop in-interface-list=WAN src-address-list=security-permanent-blocks comment="SCANBLOCK-SEC: drop permanent blocks"
/ip firewall raw add chain=prerouting action=drop in-interface-list=WAN src-address-list=port-scan-suspects comment="SCANBLOCK-SEC: drop temporary port scans"
/ip firewall raw add chain=prerouting action=drop in-interface-list=WAN src-address-list=web-flood-suspects comment="SCANBLOCK-SEC: drop temporary web flood"
/ip firewall filter add chain=input action=jump jump-target=SCANBLOCK-port-scan in-interface-list=WAN protocol=tcp connection-state=new comment="SCANBLOCK-SEC: inspect WAN TCP scans"
/ip firewall filter add chain=input action=jump jump-target=SCANBLOCK-port-scan in-interface-list=WAN protocol=udp connection-state=new comment="SCANBLOCK-SEC: inspect WAN UDP scans"
/ip firewall filter add chain=SCANBLOCK-port-scan action=add-src-to-address-list address-list=security-permanent-blocks address-list-timeout=none-dynamic src-address-list=security-strikes-port-scan psd=21,3s,3,1 comment="SCANBLOCK-SEC: repeated port scan becomes permanent"
/ip firewall filter add chain=SCANBLOCK-port-scan action=drop src-address-list=security-permanent-blocks comment="SCANBLOCK-SEC: stop permanent port scanner"
/ip firewall filter add chain=SCANBLOCK-port-scan action=add-src-to-address-list address-list=security-strikes-port-scan address-list-timeout=30d psd=21,3s,3,1 comment="SCANBLOCK-SEC: remember port scan for 30 days"
/ip firewall filter add chain=SCANBLOCK-port-scan action=add-src-to-address-list address-list=port-scan-suspects address-list-timeout=15m psd=21,3s,3,1 comment="SCANBLOCK-SEC: temporary port-scan ban"
/ip firewall filter add chain=SCANBLOCK-port-scan action=drop src-address-list=port-scan-suspects comment="SCANBLOCK-SEC: stop current port scanner"
/ip firewall filter add chain=SCANBLOCK-port-scan action=return comment="SCANBLOCK-SEC: return from port-scan chain"
/ip firewall filter add chain=forward action=jump jump-target=SCANBLOCK-web-flood in-interface-list=WAN connection-state=new connection-nat-state=dstnat protocol=tcp tcp-flags=syn dst-port=80,443 comment="SCANBLOCK-SEC: inspect published web SYN rate"
/ip firewall filter add chain=SCANBLOCK-web-flood action=return protocol=tcp dst-limit=100,200,src-and-dst-addresses/10s comment="SCANBLOCK-SEC: allow normal web SYN rate"
/ip firewall filter add chain=SCANBLOCK-web-flood action=add-src-to-address-list address-list=security-permanent-blocks address-list-timeout=none-dynamic src-address-list=security-strikes-web-flood comment="SCANBLOCK-SEC: repeated web flood becomes permanent"
/ip firewall filter add chain=SCANBLOCK-web-flood action=drop src-address-list=security-permanent-blocks comment="SCANBLOCK-SEC: stop permanent web flooder"
/ip firewall filter add chain=SCANBLOCK-web-flood action=add-src-to-address-list address-list=security-strikes-web-flood address-list-timeout=30d comment="SCANBLOCK-SEC: remember web flood for 30 days"
/ip firewall filter add chain=SCANBLOCK-web-flood action=add-src-to-address-list address-list=web-flood-suspects address-list-timeout=15m comment="SCANBLOCK-SEC: temporary web-flood ban"
/ip firewall filter add chain=SCANBLOCK-web-flood action=drop comment="SCANBLOCK-SEC: stop current web flooder"
```
## 3. Расставить правила
Номера правил на каждом MikroTik разные, поэтому этот шаг безопаснее сделать в
WinBox перетаскиванием:
1. три правила `raw` с `SCANBLOCK-SEC` поставить в самое начало `IP -> Firewall -> Raw`;
2. два `input jump` поставить после `accept established,related,untracked`, но до
разрешающих правил внешних сервисов и до итогового `input drop`;
3. `forward jump` поставить после `accept established,related,untracked` и
fasttrack, но до разрешения DST-NAT и до итогового `forward drop`;
4. порядок правил внутри `SCANBLOCK-port-scan` и `SCANBLOCK-web-flood` не менять.
Проверить порядок и счётчики:
```routeros
/ip firewall raw print stats without-paging where comment~"SCANBLOCK-SEC"
/ip firewall filter print stats without-paging where comment~"SCANBLOCK-SEC"
```
Если почтовые уведомления не нужны, на этом настройка закончена.
## 4. Почтовые уведомления — при необходимости
Сначала настроить SMTP в `Tools -> E-mail`. Пароль лучше вводить через WinBox, а
не оставлять в истории терминала. Затем проверить отправку:
```routeros
/tool e-mail send to="recipient@example.com" subject="MikroTik SMTP test" body="SMTP test"
/log print without-paging where topics~"e-mail"
```
Заменить `recipient@example.com` в команде ниже и вставить её целиком. Скрипт
помечает успешно отправленные события словом `alert-sent`, поэтому одно событие
не должно порождать повторные письма.
```routeros
/system script add name=security-block-alert policy=read,write,test,sensitive source={
:local sentMarker "alert-sent"
:if ([/system script job print count-only as-value where script=[:jobname]] > 1) do={ :exit }
:local portItems [/ip firewall address-list find where list="port-scan-suspects"]
:local webItems [/ip firewall address-list find where list="web-flood-suspects"]
:local permanentItems [/ip firewall address-list find where list="security-permanent-blocks"]
:local newPort 0
:local newWeb 0
:local newPermanent 0
:local addresses ""
:foreach item in=$portItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={
:set newPort ($newPort + 1)
:set addresses ($addresses . "TEMP PORT-SCAN: " . [/ip firewall address-list get $item address] . "\r\n")
}
}
:foreach item in=$webItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={
:set newWeb ($newWeb + 1)
:set addresses ($addresses . "TEMP WEB-FLOOD: " . [/ip firewall address-list get $item address] . "\r\n")
}
}
:foreach item in=$permanentItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={
:set newPermanent ($newPermanent + 1)
:set addresses ($addresses . "PERMANENT: " . [/ip firewall address-list get $item address] . "\r\n")
}
}
:if (($newPort=0) and ($newWeb=0) and ($newPermanent=0)) do={ :exit }
:local routerName [/system identity get name]
:local body ("Router: " . $routerName . "\r\nTime: " . [/system clock get date] . " " . [/system clock get time])
:set body ($body . "\r\nPort-scan: " . $newPort . "\r\nWeb-flood: " . $newWeb . "\r\nPermanent: " . $newPermanent . "\r\n\r\n" . $addresses)
:local sent true
:onerror e in={
:retry command={ /tool e-mail send to="recipient@example.com" subject=("MikroTik security alert: " . $routerName) body=$body } delay=10s max=3
} do={
:set sent false
:log error ("security-block-alert: " . $e)
}
:if ($sent=false) do={ :exit }
:foreach item in=$portItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={ /ip firewall address-list set $item comment=($c . " " . $sentMarker) }
}
:foreach item in=$webItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={ /ip firewall address-list set $item comment=($c . " " . $sentMarker) }
}
:foreach item in=$permanentItems do={
:local c [/ip firewall address-list get $item comment]
:if ([:typeof [:find $c $sentMarker]]="nil") do={ /ip firewall address-list set $item comment=($c . " " . $sentMarker) }
}
}
/system scheduler add name=security-block-alert interval=1m start-time=startup on-event="/system script run security-block-alert" policy=read,write,test,sensitive disabled=yes comment="Email notifications for security blocks"
```
Проверить одним тестовым событием:
```routeros
/ip firewall address-list add list=port-scan-suspects address=192.0.2.1 timeout=5m comment="notification-test"
/system script run security-block-alert
/ip firewall address-list print detail where list="port-scan-suspects" and address="192.0.2.1"
/system script run security-block-alert
/log print without-paging where message~"security-block-alert|e-mail"
```
Должно прийти одно письмо, в comment должна появиться метка `alert-sent`, второй
запуск не должен прислать дубль. Затем удалить тест и включить расписание:
```routeros
/ip firewall address-list remove [find where list="port-scan-suspects" and address="192.0.2.1"]
/system scheduler enable [find where name="security-block-alert"]
/system scheduler print detail where name="security-block-alert"
```
## 5. Проверка блокировки
Запустить внешний тест один раз с другого интернет-подключения, затем проверить:
```routeros
/ip firewall address-list print detail without-paging where list="port-scan-suspects"
/ip firewall address-list print detail without-paging where list="web-flood-suspects"
/ip firewall address-list print detail without-paging where list="security-strikes-port-scan"
/ip firewall address-list print detail without-paging where list="security-strikes-web-flood"
/ip firewall address-list print detail without-paging where list="security-permanent-blocks"
/ip firewall raw print stats without-paging where comment~"SCANBLOCK-SEC"
```
Первое нарушение создаёт временный бан и strike. Повтор после удаления/истечения
временного бана, пока strike ещё существует, создаёт постоянный бан.
## 6. Разблокировать конкретный IP
Сначала посмотреть записи:
```routeros
/ip firewall address-list print detail without-paging where address="203.0.113.10"
```
Полностью простить только этот IP:
```routeros
/ip firewall address-list remove [find where list="port-scan-suspects" and address="203.0.113.10"]
/ip firewall address-list remove [find where list="web-flood-suspects" and address="203.0.113.10"]
/ip firewall address-list remove [find where list="security-strikes-port-scan" and address="203.0.113.10"]
/ip firewall address-list remove [find where list="security-strikes-web-flood" and address="203.0.113.10"]
/ip firewall address-list remove [find where list="security-permanent-blocks" and address="203.0.113.10"]
```
## 7. Важное ограничение
Это защита от сканирования и большого числа новых TCP-соединений. Она не спасёт
от DDoS, который уже забил внешний канал: для этого нужна фильтрация провайдера,
CDN или upstream anti-DDoS. HTTP-перебор логинов и опасные URL должен отдельно
обрабатывать reverse proxy/fail2ban.
