插件窝 干货文章 Nginx中防止HTTP暴力破解攻击

Nginx中防止HTTP暴力破解攻击

Nginx zone HTTP limit 740    来源:    2025-04-20

Nginx中防止HTTP暴力破解攻击的防护措施

HTTP暴力破解攻击(如针对登录页面的密码猜测攻击)是常见的Web安全威胁。以下是Nginx中可实施的多层防护策略:

1. 基础速率限制

http {
    limit_req_zone $binary_remote_addr zone=auth_limit:10m rate=5r/m;

    server {
        location /login {
            limit_req zone=auth_limit burst=10 nodelay;
            # 其他配置...
        }
    }
}
  • 创建10MB内存区域存储客户端IP状态
  • 限制每分钟5个请求,允许突发10个请求
  • nodelay表示立即执行限制而不延迟

2. 基于地理位置的访问控制

geo $blocked_country {
    default 0;
    # 添加高风险国家代码
    CN 1;
    RU 1;
    KP 1;
}

server {
    if ($blocked_country) {
        return 403;
    }
}

3. 高级防护模块

3.1 ngx_http_limit_req_module + Fail2Ban组合

  1. Nginx日志格式配置:
log_format security '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
  1. Fail2Ban配置(/etc/fail2ban/jail.d/nginx-http-auth.conf):
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
action = iptables-multiport[name=NoHttpAuth, port="http,https"]
logpath = /var/log/nginx/security.log
maxretry = 5
findtime = 600
bantime = 3600

3.2 使用ModSecurity WAF

location / {
    ModSecurityEnabled on;
    ModSecurityConfig modsecurity.conf;
}

4. 增强型防护措施

4.1 动态黑名单

map $remote_addr $blocked_ip {
    default 0;
    include /etc/nginx/blocked_ips.conf;
}

server {
    if ($blocked_ip) {
        return 403;
    }
}

4.2 验证码集成

location = /login {
    # 首次访问返回验证码
    if ($cookie_sessionid = "") {
        return 302 /captcha?return=/login;
    }

    # 验证码验证通过后处理登录
    proxy_pass http://backend;
}

5. 高级速率限制策略

limit_req_zone $binary_remote_addr zone=low_zone:10m rate=30r/m;
limit_req_zone $binary_remote_addr zone=med_zone:10m rate=10r/m;
limit_req_zone $binary_remote_addr zone=high_zone:10m rate=3r/m;

location /login {
    # 分阶段限制
    limit_req zone=low_zone burst=20;
    limit_req zone=med_zone burst=10;
    limit_req zone=high_zone burst=5;

    # 错误次数记录
    error_page 403 = @toomanyrequests;
}

location @toomanyrequests {
    # 记录到黑名单
    return 444; # 直接关闭连接
}

6. 监控与日志分析

# 专用日志格式
log_format bruteforce '$time_iso8601 $remote_addr '
                     '$request_method $request_uri $status '
                     '$http_user_agent $http_referer';

# 单独记录登录尝试
location /login {
    access_log /var/log/nginx/bruteforce.log bruteforce;
    # 其他配置...
}

最佳实践建议

  1. 分层防护:组合使用速率限制、WAF和行为分析
  2. 敏感端点保护:特别保护/login、/admin等关键路径
  3. 监控响应:对可疑行为返回非标准响应(如444直接关闭连接)
  4. 定期审计:分析日志模式调整防护阈值
  5. 后端协调:确保Nginx限制与应用程序安全措施一致

以上措施可根据实际业务需求和安全级别进行组合调整,建议在生产环境部署前进行充分测试。