场景描述
服务器遭遇CC攻击,大量恶意请求占用连接资源。通过Fail2Ban动态封禁IP,结合Nginx限流策略,10分钟内恢复服务。
技术实现步骤
1. 配置Nginx请求频率限制
在nginx.conf
中设置全局限流规则:
http {
limit_req_zone $binary_remote_addr zone=cc_protection:10m rate=100r/m;
server {
location / {
limit_req zone=cc_protection burst=200 nodelay;
proxy_pass http://backend;
}
}
}
2. 使用Fail2Ban自动封禁恶意IP
创建自定义Jail规则/etc/fail2ban/jail.d/cc_attack.conf
:
[cc-attack]
enabled = true
filter = nginx-cc
action = iptables-multiport[name=CC, port="http,https", protocol=tcp]
logpath = /var/log/nginx/access.log
maxretry = 50 # 每分钟超过50次请求则封禁
findtime = 60
bantime = 3600
编写过滤器/etc/fail2ban/filter.d/nginx-cc.conf
:
[Definition]
failregex = ^<HOST> -.*"(GET|POST).*" (499|444) .*$
ignoreregex =
3. 自动化脚本监控与告警
使用Python脚本实时分析Nginx日志并触发封禁:
# monitor_cc.py
import subprocess
from pyinotify import WatchManager, Notifier, ProcessEvent
class CCWatcher(ProcessEvent):
def process_IN_MODIFY(self, event):
log_line = open(event.pathname).readlines()[-1]
ip = log_line.split()[0]
if "499" in log_line or "444" in log_line:
subprocess.run(["fail2ban-client", "set", "cc-attack", "banip", ip])
wm = WatchManager()
notifier = Notifier(wm, CCWatcher())
wm.add_watch('/var/log/nginx/access.log', 0x02) # 监控文件修改事件
notifier.loop()
恢复效果
- 0~3分钟:Nginx限流生效,恶意请求被延迟或丢弃。
- 4~7分钟:Fail2Ban动态封禁高频IP,释放服务器资源。
- 8~10分钟:服务响应时间恢复正常,生成攻击日志报告。
方案优势
- 零成本:完全依赖开源工具(Nginx + Fail2Ban)。
- 高灵活性:支持自定义规则匹配复杂攻击模式。
- 低误杀率:基于请求状态码(如499)精准识别攻击。