系统:Ubuntu 12.04
1.安装fail2ban
apt-get install fail2ban -y


fail2ban可以监视你的系统日志,然后匹配日志的错误信息(正则式匹配)执行相应的屏蔽动作(一般情况下是调用防火墙屏蔽),如:当有人在试探你的SSH、SMTP、FTP密码,只要达到你预设的次数,fail2ban就会调用防火墙屏蔽这个IP,而且可以发送e-mail通知系统管理员,是一款很实用、很强大的软件!其实fail2ban就是用来监控,具体是调用iptables来实现动作!

介绍:

/etc/fail2ban/action.d #动作文件夹,内含默认文件。iptables以及mail等动作配置
/etc/fail2ban/fail2ban.conf #定义了fai2ban日志级别、日志位置及sock文件位置
/etc/fail2ban/filter.d #条件文件夹,内含默认文件。过滤日志关键内容设置
/etc/fail2ban/jail.conf #主要配置文件,模块化。主要设置启用ban动作的服务及动作阀值
/etc/rc.d/init.d/fail2ban #启动脚本文件


[DEFAULT]为默认的配置配置参数很多,主要介绍几个常用的吧:
ignoreip = 127.0.0.1/8 白名单地址,支持网段,多个地址之间用空格隔开。此地址段的地址不会被封堵。
我们用默认的[ssh]服务来介绍针对于某一个服务的配置:
enabled = true 是否启用,没什么好说的
port = ssh 封堵端口,支持端口号和协议名两种方式,多个端口用逗号隔开
filter = sshd 过滤器名称,默认的过滤器在/etc/fail2ban/filter.d目录下,以.conf结尾,本例中针对/etc/fail2ban/filter.d/sshd.conf
logpath = /var/log/auth.log 日志路径
failregex = reject: RCPT from (.*)[]: 554 过滤的正则表达式,可以通过多行表示多个规则


2.修改配置
在/etc/fail2ban/jail.conf最后一行增加以下内容:
[nginx-get-dos]
enabled = true
port = http,https
filter = nginx-bansniffer
action = iptables[name=nginx, port=http, protocol=tcp]
        sendmail-whois[name=nginx, dest=zhangkai1@yy.com jiangtaoye@yy.com, sender=root]   #配置禁止IP后通知邮件,多个人以空格隔开
logpath = /data2/log/nginx/dylogin-dylogin-web-access.log #设置nginx访问日志
maxretry = 300   #测试可设置小一点,例如:3
findtime = 60    
bantime = 3600   #测试可设置小一点,例如:120

在上面的配置中,我们对每60秒有超过300次访问的ip,封禁1小时


然后创建文件/etc/fail2ban/filter.d/nginx-bansniffer.conf,内容如下:
[Definition]
failregex = <HOST> -.*- .*HTTP/1.* .* .*$
ignoreregex =

最后重启fail2ban服务即可(/etc/init.d/fail2ban restart)


3.配置发送邮件功能
apt-get install sendmail -y
apt-get install mailutils -y
启动服务
/etc/init.d/sendmail start


4.测试fail2ban的效果

curl http://dylogin.duowan.com/   #设置maxretry = 3后,执行3次后可以看/var/log/fail2ban.log 日志


2014-08-15 18:33:48,097 fail2ban.filter : INFO   Set maxRetry = 3
2014-08-15 18:33:48,100 fail2ban.filter : INFO   Set findtime = 60
2014-08-15 18:33:48,100 fail2ban.actions: INFO   Set banTime = 120
2014-08-15 18:33:48,112 fail2ban.jail   : INFO   Jail 'ssh' started
2014-08-15 18:33:48,120 fail2ban.jail   : INFO   Jail 'nginx-get-dos' started
2014-08-15 19:22:19,109 fail2ban.actions: WARNING [nginx-get-dos] Ban 113.106.251.83
2014-08-15 19:22:20,953 fail2ban.actions: WARNING [nginx-get-dos] 113.106.251.83 already banned

#设置的bantime = 120,可以看到2分钟后解禁了
2014-08-15 19:24:20,103 fail2ban.actions: WARNING [nginx-get-dos] Unban 113.106.251.83


用iptables命令看fail2ban添加的IP封禁规则:

# iptables -nL