本文共计 2141 字,感谢您的耐心浏览与评论.
UPdate:使用效果很明显,就这么几天扫描快9W次,ban了八百多IP
简单介绍一下:
如果把vps的iptables比作是一把枪,那么fail2ban就是除了你之外的另一个忠心的手下,他可以拿着枪来枪毙或管理那些非法的探视,将他们拒之门外,将一些危险扼杀在萌芽阶段。但是,他也仅仅是个手下,不是超人,可况超人也不是万能的!所以也不要以为有了它就可以高枕无忧了,这就好比一个人在厉害,也不可能打过一群人。fail2ban可以防御一定范围的CC、暴力破解登录或者是恶意扫描等等。
安装:
推荐使用这个一键脚本(lnmp.org作者写的):
wget https://raw.githubusercontent.com/licess/lnmp/master/tools/fail2ban.sh && ./fail2ban.sh
第二种方法就是自己手动去fail2ban的GitHub下载解压安装,地址:
https://github.com/fail2ban/fail2ban
最后一种就是直接通过包安装,但是可能不是最新的:
Debian/Ubuntu:apt install fail2ban
centos:yum install fail2ban
安装完来配置使其监控我们的nginx、apache或其他服务的日志,从日志中提取我们需要屏蔽的一些恶意请求,比如大量的404—通过扫描器扫描产生,ssh暴力破解,v2ray的暴力尝试爆破ID等等。
如果是通过第一种,使用一键脚本安装的话,我们只需要修改 /etc/fail2ban/jail.local 这个文件然后在 /etc/fail2ban/filter.d/中添加自己的规则文件即可。
比如我的在/etc/fail2ban/jail.local 中追加如下内容,下面使用cat命令直接追加:
cat >>/etc/fail2ban/jail.local<<EOF
[sshd]
enabled = true
port = ssh
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
#mail-whois[name=SSH, [email protected]]
logpath = /var/log/auth.log
maxretry = 5
bantime = 604800
[deny-badcrawl]
enabled = true
port = http,https
filter = deny-badcrawl
action = iptables[name=Http, port=80, protocol=tcp]
action = iptables[name=Https, port=443, protocol=tcp]
logpath = /home/wwwlogs/*.log
maxretry = 4
findtime = 3600
bantime = 3600
[nginx-limit-req]
enabled = true
port = http,https
logpath = /usr/local/nginx/conf/nginx.conf
action = iptables[name=Http, port=80, protocol=tcp]
action = iptables[name=Https, port=443, protocol=tcp]
maxretry = 4
findtime = 600
bantime = 600
EOF
请注意SSH的port,如果你自己修改过端口号,那么请把port替换成你自己修改的端口号。nginx-limit-req需要你在你的nginx配置文件中配置了才能生效的。
因为nginx-limit-req新版本的fail2ban已经有了,具体的可以在 /etc/fail2ban/filter.d 目录下面查看。
好了,然后我们在 /etc/fail2ban/filter.d 目录下新建一个deny-badcrawl.conf:
touch deny-badcrawl.conf
然后将如下内容写进去(我依旧是使用的cat命令,你可以根据自己喜好,比如nano,vi等):
cat >>/etc/fail2ban/filter.d/deny-badcrawl.conf<<EOF
[Definition]
failregex = <HOST> -.*- .*HTTP/*.* 404 .*$
ignoreregex =
EOF
然后重启fail2ban即可:service fail2ban restart
然后查看状态:fail2ban-client status
查看某个规则的具体状态:fail2ban-client status deny-badcrawl
像我这里使用了几个小时后就封了好几个IP:
注意:一般修改配置文件后,我们只需要重新载入即可,不需要重启fail2ban:
fail2ban-client reload nginx-limit-req 如果不生效,就强制重新加载service fail2ban force-reload nginx-limit-req
OK
具体的fail2ban用法和详细参数设置这些,早有前辈写过很多,不过最好是去官网看英文原版。