Fail2ban是一个非常好用的工具,可以用来作为简单的防火墙辅助工具使用,抵挡一些暴力攻击等非常好用。
以postfix的log为范例: /var/log/mail.log
Aug 24 16:37:04 mx1 postfix/smtpd[7431]: NOQUEUE: reject: RCPT from ms521.mot.deated.server-hosting.eert[89.163.220.14]:49322 554 5.7.1 <[email protected]>: Recipient address rejected: Rejected by SPF: 89.163.220.14 is not a designated mailserver for admin46%40post.com (context mfrom, on mx1.abc.net); from=<[email protected]> to=<[email protected]> proto=ESMTP helo=
Aug 24 16:37:04 mx1 postfix/smtpd[7431]: disconnect from ms521.mot.deated.server-hosting.eert[89.163.220.14] ehlo=1 mail=1 rcpt=0/1 quit=1 commands=3/4
分析以上log文件中,
reject: RCPT from ms521.mot.deated.server-hosting.eert[89.163.220.14]:49322 554 5.7.1
IP地址: 89.163.220.14 是我们需要执行封锁的IP地址
错误代码: 554 5.7.1 为判断是否执行规则的条件
匹配格式为:
reject: RCPT from [89.163.220.14]:49322: 550.5.7.1 Service unavailable
匹配表达式为:
failregex = reject: RCPT from \[<HOST>\]:.*: 550.5.7.1 Service unavailable
匹配提取解释:
- 89.163.220.14 使用’ \[<HOST>\] ‘提取,留意log中IP地址是用'[ ]’ 括起来的,所以这里要使用 ‘ \[ ‘和 ‘ \] ‘匹配,如果log中没有'[ ]’ 直接用 ” 匹配即可。
- 49322是对方连接的端口,即是变量,但这里不需要提取和匹配,直接用 ‘.*’ 匹配即可。
- 其他的字符和空格作为固定的匹配条件和匹配格式,必须与log中一致。
以下是配置自定义规则的使用方法和流程:
一、 在建立一个新的过滤器名为 test-rules.conf
#vi /etc/fail2ban/filter.d/test-rules.conf
内容为:
[INCLUDES]
before = common.conf
[Definition]
failregex = reject: RCPT from \[<HOST>\]:.*: 550.5.7.1 Service unavailable
ignoreregex =
二、 建立规则
#vi /etc/fail2ban/jail.conf
在文件最后加入以下内容:
[test-rules]
enabled = true <-- 表示启用规则
filter = test-rules <-- 这里是上面过滤器的名称
action = iptables <-- 执行actions名为iptables的动作
port = smtp,ssmtp <-- 端口号
logpath = /var/log/mail.log <-- 要匹配的log文件路径
bantime = 43200 <-- 封锁时间为43200秒
maxretry = 2 <-- 匹配次数为2次,即log中匹配表达式两次执行action
三、 重启Fail2ban加载新规则
# /etc/init.d/./fail2ban restart
或者 fail2ban-client reload 加载规则
检查新规则匹配情况:
fail2ban-regex /etc/fail2ban/filter.d/test-rules.conf /var/log/mail.log
检查新规则运行状态:
fail2ban-client status
Status
|- Number of jail: 3
`- Jail list: postfix, test-rules, sshd
iptables -L
Chain f2b-test-rules (1 references)
target prot opt source destination
REJECT all -- 89.162.220.14 anywhere reject-with icmp-port-unreachable
RETURN all -- anywhere anywhere