实战DDoS攻击防御:基于Nginx的流量清洗方案

发布于:2025-05-09 ⋅ 阅读:(14) ⋅ 点赞:(0)

一、DDoS攻击原理分析

SYN洪水攻击是常见的DDoS攻击方式,攻击者通过伪造大量TCP连接请求耗尽服务器资源。根据Cloudflare的统计报告,2023年全球DDoS攻击峰值达到每秒7100万次请求。

二、防御方案实现

# /etc/nginx/nginx.conf 核心配置
http {
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=100r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

    server {
        listen 80;
        location / {
            limit_req zone=req_limit burst=200 nodelay;
            limit_conn conn_limit 50;
            proxy_pass http://backend;
            
            # 验证User-Agent合法性
            if ($http_user_agent ~* "(wget|curl|python|nikto|scan|burp)") {
                return 403;
            }
        }
    }
}

三、IP黑名单自动更新

#!/usr/bin/python3
# ddos_defender.py
import subprocess
import requests
from datetime import datetime, timedelta

def update_iptables():
    # 获取最新威胁情报
    threat_feeds = [
        "https://lists.blocklist.de/lists/ssh.txt",
        "https://rules.emergingthreats.net/blockrules/compromised-ips.txt"
    ]
    
    # 清空旧规则
    subprocess.run(["iptables -F INPUT"], shell=True)
    
    for feed in threat_feeds:
        response = requests.get(feed)
        for ip in response.text.split('\n'):
            if ip.strip() and len(ip.split('.')) == 4:
                # 添加iptables规则
                cmd = f"iptables -A INPUT -s {ip} -j DROP"
                subprocess.run(cmd, shell=True)
                
if __name__ == "__main__":
    update_iptables()
    print(f"[{datetime.now()}] IP黑名单更新完成")

四、验证与测试

# 压力测试工具验证防御效果
ab -n 10000 -c 500 http://your-server.com/

# 查看Nginx状态
tail -f /var/log/nginx/access.log | grep '503 503'

# 监控连接数
watch -n 1 "netstat -ant | awk '{print \$6}' | sort | uniq -c"



网站公告

今日签到

点亮在社区的每一天
去签到