Fail2ban scans log files like /var/log/pwdfail or /var/log/apache/error_log and bans IP that makes too many password failures. It updates firewall rules to reject the IP address.
fail2ban就是一个监视系统日志文件的服务,发现有可疑并符合设定值的IP访问,就更新防火墙(iptables) 来阻止该IP的访问,常见的应用场合如 ssh、ftp登陆日志监控等。根据原理,还可以自定义很多监控出来。另外支持发送警告信息到管理员邮箱(需要sendmail支持)。
此处介绍的安装配置过程主要参考了:用fail2ban阻止SSH和VSFTP暴力破解密码。fail2ban中Webmin的相关配置可以参考:fail2ban – webmin filter。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #Step1: 安装 yum install fail2ban gamin #Step2: 配置 cp /etc/fail2ban/fail2ban.conf /etc/fail2ban/fail2ban.conf_$(date +%Y%m%d).bak cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.conf_$(date +%Y%m%d).bak #vim /etc/fail2ban/fail2ban.conf logtarget = /var/log/fail2ban.log #vim /etc/fail2ban/jail.conf [vsftpd-iptables] enabled = true ... logpath = /var/log/secure ... #Webmin [webmin-iptables] enabled = true filter = webmin-auth action = iptables[name=Webmin, port=10000, protocol=tcp] sendmail-whois[name=Webmin, dest=XXX@gmail.com] logpath = /var/webmin/webmin.log #Step3: 启动 chkconfig --add fail2ban chkconfig --level 345 fail2ban on service fail2ban start |
fail2ban服务管理涉及的命令主要有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #检查某个服务的过滤规则是否可以匹配某个日志文件 fail2ban-regex /var/log/secure /etc/fail2ban/filter.d/sshd.conf #启动 service fail2ban start #关闭 service fail2ban stop #查看状态 service fail2ban status fail2ban-client status #查看阻止状态 fail2ban-client status ssh-iptables #查看日志 less /var/log/fail2ban.log #查看iptables iptables -L -n |
默认情况下有可能会出现“WARNING: Unable to find a corresponding IP address for ***”的错误,解决办法可以参考pure-ftpd and apache ban fails with DNS error。详述如下:
1 2 3 4 5 6 7 8 9 10 11 12 | #Step1: 修改vsftpd的配置 vim /etc/vsftpd/vsftpd.conf #添加如下一句 dual_log_enable=YES #Step2: 修改fail2ban的配置 vim /etc/fail2ban/jail.conf #修改以下内容 [vsftpd-iptables] ... logpath = /var/log/vsftpd.log ... |
如果加入的过滤规则太多,有可能会出现某个或某些iptables规则启动失败的现象,在fail2ban.log中可以看到相关的出错信息:
1 2 3 4 5 6 | iptables -I INPUT -p tcp --dport http -j fail2ban-NoScript returned 400 iptables -I INPUT -p tcp --dport 10000 -j fail2ban-Webmin returned 400 iptables -I INPUT -p tcp --dport ftp -j fail2ban-VSFTPD returned 200 iptables -I INPUT -p tcp -m multiport --dports http,https -j fail2ban-OverFolws returned 200 iptables -I INPUT -p tcp --dport http -j fail2ban-phpMyAdmin returned 200 iptables -I INPUT -p tcp --dport ssh -j fail2ban-SSH returned 400 |
出现上述错误的原因可能是程序运行太快以致于反应不过来……(天下之大什么原因没有?长见识了!),下面是解决办法:
1 2 3 4 5 6 7 | vim /usr/bin/fail2ban-client #在for c in cmd:和beautifier.setInputCmd(c)之间添加一行:time.sleep(0.1);最终如下: def __processCmd(self, cmd, showRet = True): beautifier = Beautifier() for c in cmd: time.sleep(0.1) beautifier.setInputCmd(c) |
关于此问题以及其解决方案可以参看:fail2ban startup iptables error和What are fail2ban’s log iptables “returned NNN”entries? (Fail2ban is failing to ban)。