Fail2Ban
1 前言
一个问题,一篇文章,一出故事。
笔者今天查看Nginx错误日志,发现大量的如下日志,
2026/04/08 08:54:36 [error] 1963298#1963298: *546901 "/var/www/cmdschool.org/index.html" is not found (2: No such file or directory), client: 216.180.246.180, server: cmdschool.org, request: "GET / HTTP/1.1", host: "47.90.98.232" 2026/04/08 08:56:45 [error] 1963298#1963298: *547457 "/var/www/cmdschool.org/index.html" is not found (2: No such file or directory), client: 142.248.80.163, server: cmdschool.org, request: "GET / HTTP/1.1", host: "47.90.98.232:80" 2026/04/08 08:59:32 [error] 1963298#1963298: *547506 "/var/www/cmdschool.org/index.html" is not found (2: No such file or directory), client: 165.245.235.19, server: cmdschool.org, request: "GET / HTTP/1.1", host: "47.90.98.232:80"
从日志判断,这属于恶意扫描,于是想拉黑这些IP地址。
本章为继续上次定义的Nginx Access日志规则的延续,
2 最佳实践
2.1 环境配置
2.2 配置Fail2Ban
2.2.1 创建过滤规则
vim /etc/fail2ban/filter.d/wordpress-error.conf
加入如下配置,
[Definition] failregex = ^.*No such file or directory.*client: .*$
然后,你可以使用如下命令来确认规则,
fail2ban-regex --print-all-matched /var/log/nginx/error.log /etc/fail2ban/filter.d/wordpress-error.conf
2.2.2 定义监视配置
vim /etc/fail2ban/jail.d/wordpress-error.local
加入如下配置,
[wordpress-error] enabled = true port = http,https filter = wordpress-error logpath = /var/log/nginx/error.log maxretry = 10 findtime = 5m bantime = 24h
配置修改后,你需要重启服务使配置生效,
systemctl restart fail2ban.service systemctl status fail2ban.service
2.2.3 查看服务状态
fail2ban-client status wordpress-error
可见如下显示,
Status for the jail: wordpress-error |- Filter | |- Currently failed: 2 | |- Total failed: 15 | `- File list: /var/log/nginx/error.log `- Actions |- Currently banned: 1 |- Total banned: 1 `- Banned IP list: 40.85.219.177
2.2.4 查看防火墙状态
iptables -L -v -n
可见如下显示,
#... Chain f2b-wordpress-error (1 references) pkts bytes target prot opt in out source destination 22 1462 REJECT all -- * * 40.85.219.177 0.0.0.0/0 reject-with icmp-port-unreachable 314 28070 RETURN all -- * * 0.0.0.0/0 0.0.0.0/0
参阅文档
====================
https://github.com/fail2ban/fail2ban/wiki/Developing-Regex-in-Fail2ban
https://wangdoc.com/ssh/fail2ban
没有评论