Search
Write a publication
Pull to refresh

Fail2ban работа с NAT

Большинство используют Fail2ban для защиты различных программ на сервере. Но как быть, если надо защитить сервис, находящийся внутри локальной сети? Тут нам понадобится связка из iptables для маркировки трафика и Fail2ban для принятия решения по блокировке.

Всё будем делать на Centos 6.

Заставим iptables писать свой лог в отдельный файл, как тут — https://habrahabr.ru/post/259169/.

Определяемся, какой сервис будем защищать — пускай это будет сервер терминалов RDP на порту 3389.

Стандартное правило обычно выглядит вот так:

-A PREROUTING -i eth1 -p tcp -m tcp --dport 3389 -j DNAT --to-destination 192.168.1.209:3389

Теперь нам надо добавить к стандартному правилу проброса порта во внутреннюю сеть. Вида (eth1 — внешний интерфейс, порт 3389 (сервер терминалов) и внутренний адрес сервера 192.168.1.209):

Правила маркировки пакетов с помощью iptables, чтобы получить вот такие строчки в iptables:

-A PREROUTING -i eth1 -p tcp -m tcp --dport 3389 -m state --state NEW -m hashlimit --hashlimit 1/hour --hashlimit-burst 5 --hashlimit-mode srcip --hashlimit-name RDP --hashlimit-htable-expire 31000 -j LOG --log-prefix "Iptables: RDP 3389 detected: "
-A PREROUTING -i eth1 -p tcp -m tcp --dport 3389 -j LOG --log-prefix "Iptables: hashlimit: "
-A PREROUTING -i eth1 -p tcp -m tcp --dport 3389 -j DNAT --to-destination 192.168.1.209:3389

Почитать, что делает первая строчка и как она работает, можно вот тут https://habrahabr.ru/post/88461/.

Теперь пишем обработку файла iptables.log в Fail2ban.

Пишем в /etc/fail2ban/jail.local:

[rdp-bruteforce]
enabled  = true
filter   = rdp-bruteforce
action   = iptables-nat[name=rdp-bruteforce, protocol=tcp]
logpath  = /var/log/iptables.log
maxretry = 3 ; Три попытки
bantime  = 86400 ; Бан на 1 сутки
findtime = 60 ; Время за которое должно повториться событие 1 минута

Пишем в /etc/fail2ban/filter.d/rdp-bruteforce.conf:

# Fail2Ban configuration file
#
# Author: AwS59
#
[Definition]
# Option: failregex
# Notes.: regex to match the password failures messages in the logfile. The
#          host must be matched by a group named "host". The tag "<HOST>" can
#          be used for standard IP/hostname matching and is only an alias for
#          (?:::f{4,6}:)?(?P<host>[\w\-.^_]+)
# Values: TEXT
#
# Sample log: Feb 29 11:16:55 mars kernel: Iptables: hashlimit: IN=XXX OUT= MAC=XX:XX:XX:XX:XX: SRC=X.X.X.X DST=X.X.X.X LEN=X   
# TOS=0x00 PREC=0x00 TTL=X ID=X DF PROTO=TCP SPT=X DPT=X WINDOW=X RES=0x00 SYN URGP=0
#
failregex = hashlimit: .* SRC=<HOST>
# Option:  ignoreregex
# Notes.:  regex to ignore. If this regex matches, the line is ignored.
# Values:  TEXT
#
ignoreregex =

Пишем в /etc/fail2ban/action.d/iptables-nat.conf:

[INCLUDES]
before = iptables-common.conf
[Definition]
# Option:  actionstart
# Notes.:  command executed once at the start of Fail2Ban.
# Values:  CMD
#
actionstart = <iptables> -t nat -N f2b-<name>
                    <iptables> -t nat -A f2b-<name> -j <returntype>
                    <iptables> -t nat -I PREROUTING -p  <protocol> -j f2b-<name>
# Option:  actionstop
# Notes.:  command executed once at the end of Fail2Ban
# Values:  CMD
#
actionstop = <iptables> -t nat -D PREROUTING -p <protocol> -j f2b-<name>
                     <iptables> -t nat -F f2b-<name>
                     <iptables> -t nat -X f2b-<name>

# Option:  actioncheck
# Notes.:  command executed once before each actionban command
# Values:  CMD
#
actioncheck = <iptables> -n -L PREROUTING -t nat | grep -q 'f2b-<name>[ \t]'
# Option:  actionban
# Notes.:  command executed when banning an IP. Take care that the
#          command is executed with Fail2Ban user rights.
# Tags:    See jail.conf(5) man page
# Values:  CMD
#
actionban   = <iptables> -t nat -I f2b-<name> 1 -s <ip> -j DNAT --to <ip>
                      <iptables> -I FORWARD -s <ip> -d <ip> -j ACCEPT
# Option:  actionunban
# Notes.:  command executed when unbanning an IP. Take care that the
#          command is executed with Fail2Ban user rights.
# Tags:    See jail.conf(5) man page
# Values:  CMD
#
actionunban = <iptables> -t nat -D f2b-<name> -s <ip> -j DNAT --to <ip>
                        <iptables> -D FORWARD -s <ip> -d <ip> -j ACCEPT
[Init]

Осталось перезапустить службы iptables и Fail2ban и начинаем следить за iptables.log и появлением там строк с hashlimit и реакцией в Fail2ban на эти строчки.
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.