使用 Fail2Ban 來防止有心人士暴力破解 SASL 信件認證

最近每天系統報表都會顯示以下

pam_unix(smtp:auth): check pass; user unknown
 pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
 pam_unix(smtp:auth): check pass; user unknown
 pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
 pam_unix(smtp:auth): check pass; user unknown
 pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
 pam_unix(smtp:auth): check pass; user unknown
 pam_unix(smtp:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=
 pam_unix(smtp:auth): check pass; user unknown
Apr 13 02:33:58 jupiter saslauthd[15953]:                 : auth failure: [user=liuwei] [service=smtp] [realm=] [mech=pam] [reason=PAM auth error]
Apr 13 02:34:02 jupiter saslauthd[15954]:                 : auth failure: [user=liuwei] [service=smtp] [realm=] [mech=pam] [reason=PAM auth error]
Apr 13 02:34:05 jupiter saslauthd[15952]:                 : auth failure: [user=liuwei] [service=smtp] [realm=] [mech=pam] [reason=PAM auth error]

查看系統的 /var/log/messages 會出現以下

Apr 14 16:29:49 jupiter saslauthd[15954]:                 : auth failure: [user=zhangmin] [service=smtp] [realm=sn-shrimp.com.tw] [mech=pam] [reason=PAM auth error]
Apr 14 16:29:53 jupiter saslauthd[15951]:                 : auth failure: [user=zhangmin] [service=smtp] [realm=sn-shrimp.com.tw] [mech=pam] [reason=PAM auth error]
Apr 14 16:29:57 jupiter saslauthd[15952]:                 : auth failure: [user=zhangmin] [service=smtp] [realm=sn-shrimp.com.tw] [mech=pam] [reason=PAM auth error]
Apr 14 16:30:00 jupiter saslauthd[15949]:                 : auth failure: [user=zhangmin] [service=smtp] [realm=sn-shrimp.com.tw] [mech=pam] [reason=PAM auth error]

查看系統的 /var/log/maillog 會出現以下

Apr 14 16:29:06 jupiter postfix/smtpd[5747]: connect from unknown[171.38.33.253]
Apr 14 16:29:09 jupiter postfix/smtpd[5747]: warning: unknown[171.38.33.253]: SASL LOGIN authentication failed: authentication failure
Apr 14 16:29:09 jupiter postfix/smtpd[5747]: lost connection after AUTH from unknown[171.38.33.253]
Apr 14 16:29:09 jupiter postfix/smtpd[5747]: disconnect from unknown[171.38.33.253]

似乎是被鎖定 Sasl 攻擊了,由於之前已經有安裝 fail2ban,可以打開相關的 sasl 防護功能
修改

vim /etc/fail2ban/jail.conf

將 sasl-iptables 打開,要特別注意 log 檔的位置與檔名是否正確

[sasl-iptables]
enabled  = true
filter   = sasl
backend  = polling
action   = iptables[name=sasl, port=smtp, protocol=tcp]
#          sendmail-whois[name=sasl, dest=you@example.com]
logpath  = /var/log/maillog

可以先行使用目前的 log 檔匹配看看是否可以抓到 IP

fail2ban-regex /var/log/maillog /etc/fail2ban/filter.d/sasl.conf

重啟 fail2ban 服務

service fail2ban restart

或者是重讀設定檔,但實驗後發現仍會清空已封鎖的 iptables IP 名單

fail2ban-client reload

使用 iptables 查看是否有相關的 Chain

iptables -n -L -v

比較要注意的是 fail2ban 裡的 jail.conf 預設的 log 檔名為

/var/log/mail.log

而實際上依據系統不同,mail 的 log 檔名會不太一樣,例如 CentOS 為

/var/log/maillog