fail2ban 防CC

#防火墙常规检查操作

#如果您已经安装iptables建议先关闭
service iptables stop
#查看firewalld状态
firewall-cmd --state
#启动firewalld
systemctl start firewalld
#设置开机启动
systemctl enable firewalld.service
启用firewalld后会禁止所有端口连接,因此请务必放行常用的端口,以免被阻挡在外,以下是放行SSH端口
#放行22端口
firewall-cmd --zone=public --add-port=22/tcp --permanent
#放行80端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
#重载配置
firewall-cmd --reload
#查看已放行端口
firewall-cmd --zone=public --list-ports

#CentOS内置源并未包含fail2ban,需要先安装epel源

yum -y install epel-release

#安装fial2ban

yum -y install fail2ban

#安装成功后fail2ban配置文件位于/etc/fail2ban,其中jail.conf为主配置文件,相关的匹配规则位于filter.d目录,其它目录/文件一般很少用到,如果需要详细了解可自行搜索。

#fail2ban 结构

/etc/fail2ban ## fail2ban 服务配置目录
/etc/fail2ban/action.d ## iptables 、mail 等动作文件目录
/etc/fail2ban/filter.d ## 条件匹配文件目录,过滤日志关键内容
/etc/fail2ban/jail.conf ## fail2ban 防护配置文件
/etc/fail2ban/fail2ban.conf ## fail2ban 配置文件,定义日志级别、日志、sock 文件位置等

#在etc/fail2ban中新建jail.local来覆盖fail2ban的一些默认规则,并给最高权限,然后编辑内容如下:

[DEFAULT]
ignoreip = 127.0.0.1/8
bantime = 7200
findtime = 600
maxretry = 5
banaction = firewallcmd-ipset
action = %(action_mwl)s

[sshd]
enabled = true
filter = sshd
port = 22
action = %(action_mwl)s
logpath = /var/log/secure

[nginx-cc]
enabled = true
port = http,https
filter = nginx-cc
action = %(action_mwl)s
maxretry = 5
findtime = 60 
bantime = 3600
logpath = /var/log/nginx/access.log

#在filter.d中新建nginx-cc.conf,编辑内容如下:

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

#fail2ban常规命令操作

#停止
systemctl stop fail2ban
#启动
systemctl restart fail2ban
#开机启动
systemctl enable fail2ban
#是配置立即生效
systemctl daemon-reload
#查看是否开机启动
systemctl is-enabled fail2ban
#查看被ban IP,其中sshd为名称,比如上面的[wordpress]
fail2ban-client status sshd
#删除被ban IP
fail2ban-client set sshd unbanip 192.168.111.111
或
fail2ban-client set sshd delignoreip 192.168.111.111
#如果用以上命令删除被ban IP发现这个IP还是无法连接,是因为在临时策略中的ipset集合,只有电脑重启或者从这里面删除IP才行。
#查看临时策略中的ipset集合:“ipset list”,删除ipset集合中IP:“ipset del fail2ban-sshd 192.168.111.111 -exist”
#查看日志
tail /var/log/fail2ban.log
#用命令用来查看在fail2ban黑名单里的IP是否已经加到了firewall中
ipset list
#修改配置好重启(重启需要点时间,要耐心)
fail2ban-client reload或systemctl restart fail2ban
#解除黑名单ip(nginx-cc是规则文件名跟上面设置要一致)
fail2ban-client set nginx-cc unbanip 8.8.8.8
#增加黑名单ip(nginx-cc是规则文件名跟上面设置要一致)
fail2ban-client set nginx-cc banip 8.8.8.8
#查黑名单ip(如果想查sshd,把nginx-cc改为sshd)
fail2ban-client status nginx-cc
#查看版本
fail2ban-client -server -V

注意1-时间文件: 当我们更改了时区后,然后日志的时间并没有修改过来,导致两者的时间不一致,这样fail2ban的工作就失效了。

解决办法:重启日志服务:systemctl restart rsyslog,保证两者的时间一致。 

注意2-修改端口问题:sshd更改端口号后使用fail2ban需要注意在填写配置的时候也需要更改端口号。否则会出现就算会将ip添加到防火墙,但是由于我更改了端口号,是起不到禁止作用的。

解决办法:在配置文件/etc/fail2ban/jail.local中修改新的端口号。

posted @ 2019-04-19 17:37  代码家园  阅读(736)  评论(0编辑  收藏  举报