环境:
系统: CentOS 7
fail2ban: 0.11.1-10.el7
安装fail2ban
yum install fail2ban
配置/etc/fail2ban/jail.local
[DEFAULT]
ignoreip = 127.0.0.1 172.18.0.0/16
findtime = 10m
bantime = 24h
banaction = iptables-multiport
[sshd]
enabled = true
port = 592
logpath = /var/log/secure
maxretry = 3
功能测试
IP加入黑名单及禁用时间到期后自动解除黑名单
以nginx + naxis为例
- 在/etc/fail2ban下创建ip.blacklist
- 修改/etc/fail2ban/action.d/iptables-multiport.conf
# Fail2Ban configuration file
#
# Author: Cyril Jaquier
# Modified by Yaroslav Halchenko for multiport banning
#
[INCLUDES]
before = iptables-common.conf
[Definition]
# Option: actionstart
# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false).
# Values: CMD
#
actionstart = <iptables> -N f2b-<name>
<iptables> -A f2b-<name> -j <returntype>
<iptables> -I <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>
cat /etc/fail2ban/ip.blacklist | sort -u | while read IP; do iptables -I f2b-<name> 1 -s $IP -j DROP; done
# Option: actionstop
# Notes.: command executed at the stop of jail (or at the end of Fail2Ban)
# Values: CMD
#
actionstop = <iptables> -D <chain> -p <protocol> -m multiport --dports <port> -j f2b-<name>
<actionflush>
<iptables> -X f2b-<name>
# Option: actioncheck
# Notes.: command executed once before each actionban command
# Values: CMD
#
actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
# Option: actionban
# Notes.: command executed when banning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
echo <ip> >> /etc/fail2ban/ip.blacklist
# Option: actionunban
# Notes.: command executed when unbanning an IP. Take care that the
# command is executed with Fail2Ban user rights.
# Tags: See jail.conf(5) man page
# Values: CMD
#
actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>
/usr/bin/sed -i "/<ip>/d" /etc/fail2ban/ip.blacklist
[Init]
- 在/etc/fail2ban/filter.d/nginx-naxsi.conf添加过滤规则
[INCLUDES]
before = common.conf
[Definition]
failregex = NAXSI_FMT: ip=<HOST>&server=.*&uri=.*&learning=0
NAXSI_FMT: ip=<HOST>.*&config=block
ignoreregex = NAXSI_FMT: ip=<HOST>.*&config=learning
- 编辑/etc/fail2ban/jail.local并添加监控项
[nginx-naxsi]
enabled = true
port = http,https
filter = nginx-naxsi
logpath = /var/log/nginx/*error.log
findtime = 20m
#bantime = 600m # 封禁ip 10小时
bantime = 480h # 封禁ip 480小时
#bantime = -1 # 永久封禁非法访问ip
maxretry = 3