IOTXING

记录技术学习之路

0%

Nginx动态黑名单

最近一台服务器上面,经常有人恶意调用接口,从开始的几s一次到后来的1次/s,简直是在浪费自己的性能以及流量。 这里使用fail2ban来对nginx的access日志访问,并且自动使用iptables进行屏蔽相关ip

安装fail2ban

yum install fail2ban

可以直接使用yum进行安装

配置fail2jan

jail文件

/etc/fail2ban/jail.d/nginx.conf


[DEFAULT]
banaction = firewallcmd-ipset
[nginx]
enabled=true
port=http
filter=nginx-filter    
action=iptables[name=nginx,port=http,protocol=tcp]
logpath=/var/log/nginx/access.log
maxretry=20
findtime=200
bantime=36000

其中的filter是我们之后要进行创建的匹配规则 action是我们队匹配到的恶意ip实行的规则,这里是直接通过iptable来禁止链接 logpath是fail2ban需要扫描的日志文件,这里选取nginx的access文件 这里我设置的规则是在200s内访问20次的ip为恶意ip bantime为限制的时间

filter

vi /etc/fail2ban/filter.d/nginx-filter.conf

这里filter文件的名字需要 跟 我们上面filter里面填写的名字一样

[Definition]
failregex =<HOST> -.*- .*HTTP/1.* .* .*$

重启服务

/sbin/service fail2ban restart

查看日志

tail -200f /var/log/fail2ban.log


2018-05-09 17:09:44,980 fail2ban.server         [30879]: INFO    Changed logging target to /var/log/fail2ban.log for Fail2ban v0.9.7
2018-05-09 17:09:44,981 fail2ban.database       [30879]: INFO    Connected to fail2ban persistent database '/var/lib/fail2ban/fail2ban.sqlite3'
2018-05-09 17:09:44,983 fail2ban.database       [30879]: WARNING New database created. Version '2'
2018-05-09 17:09:44,984 fail2ban.jail           [30879]: INFO    Creating new jail 'nginx'
2018-05-09 17:09:45,001 fail2ban.jail           [30879]: INFO    Jail 'nginx' uses poller {}
2018-05-09 17:09:45,022 fail2ban.jail           [30879]: INFO    Initiated 'polling' backend
2018-05-09 17:09:45,024 fail2ban.filter         [30879]: INFO    Added logfile = /var/log/nginx/access.log
2018-05-09 17:09:45,025 fail2ban.filter         [30879]: INFO    Set maxRetry = 10
2018-05-09 17:09:45,025 fail2ban.filter         [30879]: INFO    Set jail log file encoding to UTF-8
2018-05-09 17:09:45,026 fail2ban.actions        [30879]: INFO    Set banTime = 36000
2018-05-09 17:09:45,027 fail2ban.filter         [30879]: INFO    Set findtime = 200
2018-05-09 17:09:45,390 fail2ban.jail           [30879]: INFO    Jail 'nginx' started
2018-05-09 17:12:37,271 fail2ban.filter         [30879]: INFO    [nginx] Found 60.12.241.194
2018-05-09 17:12:37,271 fail2ban.filter         [30879]: INFO    [nginx] Found 60.12.241.194
2018-05-09 17:12:37,272 fail2ban.filter         [30879]: INFO    [nginx] Found 60.12.241.194

总结

通过对fail2ban的配置,所有在200s内连续访问数达到20次的ip,会被认为恶意ip,然后通过iptablse设置规则,来限制该ip10小时内不能链接。这样有效的避免了CC攻击