2018年9月21日金曜日

Fail2banで永久banしたい(CentOS7 firewallcmd-ipset)

昔、GmailはGoogleのメールサーバから全く別のメールアドレスでメールを送信する設定が出来ました。それが、暗号化してないとダメになって、いつの間にかドメインが違うと登録できなくなっていました。昔に設定した既得権でずっと使えていたのですが、つい最近、手違いで設定解除してしまいました。仕方がないので、PostfixにCyrus SASLでSMTP-AUTHを導入しました。数時間後にmaillogを見ると、「SASL LOGIN authentication failed」の嵐になっていました。こういう輩には速攻で、永久にお引き取り願おうと思っております。というわけで、今回はCentOS7+Fail2ban(firewallcmd-ipset)の設定をしていきます。
まずは、インストールします。
# yum install --enablerepo=epel -y fail2ban fail2ban-systemd
次に、/etc/fail2ban/jail.localを作成します。このファイルはjail.confをオーバーライドするものです。
jail.local
[DEFAULT]
ignoreip = 127.0.0.1/8 172.16.1.0/24
maxretry = 5
findtime = 3600
bantime  = 86400
backend  = systemd
usedns   = yes

[postfix-sasl]
enabled  = true
findtime = 86400
bantime  = -1
port     = smtp,465,submission
logpath  = %(postfix_log)s
bantimeにマイナスを設定すると永久banになるようです。
早速、起動と行きたいところですが、このままでは上手く動きません。
ipsetのtimeoutにbantimeを入れる動作をするためにエラーになってしまいます。0が永久ですが、bantimeに0入れるとfail2banがban & unbanを繰り返します。
また、ログが更新されると再起動した時にログ落ちしたIPはbanされませんので、追加されるたびに別のファイル(下記では、permanent_bans.ip)に残しておき、起動時にそのファイルから再度、読み込みします。
これを変更するには/etc/fail2ban/action.d/firewallcmd-ipset.confのactionstartとactionbanを編集します。
firewallcmd-ipset.conf(抜粋)
#actionstart = ipset create fail2ban-<name> hash:ip timeout <bantime>
#              firewall-cmd --direct --add-rule ipv4 filter <chain> 0 -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>

actionstart = ipset create fail2ban-<name> hash:ip timeout 0
              firewall-cmd --direct --add-rule ipv4 filter <chain> 0 -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>
              cat /etc/fail2ban/permanent_bans.ip | awk '/^fail2ban-<name> / {print $2}' | while read IP; do ipset add fail2ban-<name> $IP timeout 0 -exist; done

actionstop = firewall-cmd --direct --remove-rule ipv4 filter <chain> 0 -p <protocol> -m multiport --dports <port> -m set --match-set fail2ban-<name> src -j <blocktype>
             ipset flush fail2ban-<name>
             ipset destroy fail2ban-<name>

#actionban = ipset add fail2ban-<name> <ip> timeout <bantime> -exist
actionban = ipset add fail2ban-<name> <ip> timeout 0 -exist
            echo "fail2ban-<name> <ip>" >> /etc/fail2ban/permanent_bans.ip
また、blocktypeは相手に応答しないdropにします。
iptables-common.conf(抜粋)
#blocktype = REJECT --reject-with icmp-port-unreachable
blocktype = DROP
後は起動するだけです。
# systemctl start fail2ban
# systemctl enable fail2ban
banのリストを見るには、
# ipset list
unbanしたいときは、/etc/fail2ban/permanent_bans.ip から該当のipを削除して
# fail2ban-client set postfix-sasl unbunip <ip_addr>
という感じです。

0 件のコメント:

コメントを投稿

postfix main.cf smtpd_sender_restrictions

最近、メールサーバでキューを確認すると、やたらと???@0000.comへのバウンスメールが溜まっている。 中身を確認すると、PICほにゃららというファイル名で難読化したJavaScriptが添付されているメールです。 何が目的なのか分かりませんが、ごみメール送ってきてバウン...