Fail2ban的安装和使用
简介
CentOS 中使用fail2ban和firewalld限制IP拦截cc攻击
安装和启动
- 安装
$ yum -y install fail2ban
安装后可以使用以下命令查看版本
$ fail2ban-client -V $ fail2ban-server -V
显示如下
Fail2Ban v0.9.7 Copyright © 2004-2008 Cyril Jaquier, 2008- Fail2Ban Contributors Copyright of modifications held by their respective authors. Licensed under the GNU General Public License v2 (GPL). Written by Cyril Jaquier cyril.jaquier@fail2ban.org. Many contributions by Yaroslav O. Halchenko debian@onerussian.com.
- 停止
$ systemctl stop fail2ban
- 启动
$ systemctl start fail2ban
- 重启
$ systemctl restart fail2ban
- 开机启动
$ systemctl enable fail2ban
配置
fail2ban安装后有两个程序,fail2ban-server 和 fail2ban-client,对应的主配置文件是fail2ban.conf 和 jail.conf。本次主要是修改 fail2ban-client配置。
fail2ban的.conf配置文件都是可以被.local覆盖,所以配置方式建议是添加.local文件,不修改原来的配置文件。
- jail.local 配置
$ vim /etc/fail2ban/jail.local
添加默认配置
[DEFAULT] ignoreip = 127.0.0.1/8 bantime = 86400 findtime = 600 maxretry = 5 banaction = firewallcmd-ipset action = %(action_mwl)s
配置说明
- ignoreip:白名单,不拦截,多个使用,分隔
- bantime:拦截后禁止访问的时间,单位:秒
- findtime:检查的时间访问,单位:秒
- maxretry:最大失败次数, 在检查时间内达到次数就拦截
- banaction:屏蔽ip的方法,firewallcmd-ipset使用fiewallld屏蔽
添加nginx拦截规则
$ vim /etc/fail2ban/filter.d/nginx-cc.conf
配置如下
[Definition]
failregex = <HOST> -.*- .*HTTP/1.* .* .*$
ignoreregex =
配置说明
- failregex :拦截的正则规则, 可以使用 匹配主机名和IP地址; 是正则表达式的别名
添加nginx-cc配置到jail.local中
在jail.local中添加配置
[nginx-cc]
enabled = true
port = http,https
filter = nginx-cc
action = %(action_mwl)s
maxretry = 200
findtime = 10
bantime = 86400
# 说明注释
logpath = /var/log/nginx/access.log
以上配置是检查 “20秒之内访问次数达到200次就拦截该IP”。其它的配置说明如下:
- enabled :是否开启检测
- port:检查的端口
- maxretry:最大失败次数, 在检查时间内达到次数就拦截
- bantime:拦截后禁止访问的时间,单位:秒
- findtime:检查的时间访问,单位:秒
- logpath: 扫描的日志文件,fail2ban按行扫描此文件,根据filter规则匹配失败的项目并统计
注意: 配置文件文件可以换行添加注释,但是不能在配置项后面跟注释,例如以下的注释是不允许的,failban会检查配置无效,将 bantime设置成None。
bantime = 86400 # 这里不能写注释
加载配置
重载配置是其生效
$ fail2ban-client reload
其它命令
- 查看拦截状态
$ fail2ban-client status nginx-cc
结果如下, Banned IP list就是被拦截的IP
Status for the jail: nginx-cc |- Filter | |- Currently failed: 1 | |- Total failed: 100 | `- File list: /var/log/nginx/access.log `- Actions |- Currently banned: 3 |- Total banned: 3 `- Banned IP list: 101.2.2.1 101.2.2.3 101.2.2.4
- 手动拦截IP
$ fail2ban-client set nginx-cc banip 101.2.2.1
- 解除拦截的IP
$ fail2ban-client set nginx-cc unbanip 101.2.2.1
- 检查配置
修改后可以先使用以下命令检查配置是否有误$ fail2ban-client -d
- 正则规则检查
$ fail2ban-regex /var/log/nginx/access.log "<HOST> -.*- .*HTTP/1.* .* .*$"
- 根据配置文件检查
fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-cc.conf
————————————————
版权声明:本文为CSDN博主「xiaohuai_007」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_47934044/article/details/106245581
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。