Hugo博客公告弹窗

nginx防御教程之fail2ban(一)

基于 nginx 基础上,非docker nginx

测试系统:debian12

防CC攻击过滤器基于nginx的limit速率限制配置,判断403和429状态码

使用ufw封禁

注意:日志要存在,避免报错

fail2ban脚本

curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/f2.sh && chmod +x f2.sh && ./f2.sh

相关命令

# 查看 Fail2Ban 服务状态
sudo systemctl status fail2ban

# 重启
sudo systemctl restart fail2ban

# 查看所有监狱
sudo fail2ban-client status

# 查看 Nginx 相关监狱
sudo fail2ban-client status sshd
sudo fail2ban-client status nginx-bad-request
sudo fail2ban-client status nginx-cc

# 测试 Fail2Ban 配置语法
sudo fail2ban-server -t

# Fail2Ban 实时日志
sudo tail -f /var/log/fail2ban.log

# 日志
sudo journalctl -u fail2ban -f -n 50

编辑过滤器

sudo nano /etc/fail2ban/filter.d/nginx-bad-request.conf

查看jail配置

sudo cat /etc/fail2ban/jail.local

模拟 SSH 暴力尝试

在另外一台服务器上安装 sshpass

sudo apt install sshpass

模拟5次登录

for i in {1..5}; do
    sshpass -p 'wrongpassword' ssh \
        -o StrictHostKeyChecking=no \
        -p 5533 fakeuser@目标IP
    echo "尝试 $i 次"
done

查询封禁情况

sudo fail2ban-client status sshd

解封

sudo fail2ban-client unban IP地址

模拟cc攻击

重点:先修改nginx限流配置

nano /etc/nginx/nginx.conf

修改,例如

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=example_zone:50m rate=2r/s;
    limit_req zone=example_zone burst=8 nodelay;
    limit_req_status 429;

重点参数:rate=2r/sburst=8 数值要小,太大检测不到,之后再改回来

然后,在另外一台服务器上测试攻击,代码如下(假设你的站点是www.xxxx.com)

while true; do
    curl -i https://www.xxxx.com/
    sleep 0.1  # 设置请求间隔,确保超出限速
done

查看站点包含429状态码的日志,

grep ' 429 ' /var/log/nginx/www.xxxx.com.access.log

再查看是否封禁

sudo fail2ban-client status nginx-cc

解封

sudo fail2ban-client unban IP地址

错误排查

  1. 停止服务并清理现有配置
sudo systemctl stop fail2ban
sudo rm -f /etc/fail2ban/jail.d/*
  1. 仅配置最基础的 SSH 防护(jail.local)
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime  = 3600
findtime = 600
maxretry = 5
ignoreip = 127.0.0.1/8

[sshd]
enabled  = true
port     = ssh
logpath  = /var/log/auth.log
maxretry = 3
EOF
  1. 启动 / 重启服务
sudo systemctl start fail2ban
sudo systemctl restart fail2ban
  1. 验证配置是否生效
sudo fail2ban-client status

移除allowipv6警告

去掉WARNING ‘allowipv6’ not defined in ‘Definition’. Using default one: ‘auto’

nano /etc/fail2ban/fail2ban.local

内容:

[DEFAULT]
allowipv6 = auto

重启

sudo systemctl restart fail2ban

验证

sudo fail2ban-client status
CC BY-NC-SA 4.0 转载请注明
最后更新于 2025-12-20 16:22