DDoS (分布式拒绝服务) 攻击是常见的网络安全威胁,以下是针对 Linux 系统的多层次防御方案:
# 编辑 /etc/sysctl.conf 添加以下参数
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
# 应用配置
sysctl -p
# 使用 iptables 限制单个 IP 的连接数
iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 50 -j REJECT
iptables -A INPUT -p tcp --dport 443 -m connlimit --connlimit-above 50 -j REJECT
# 阻止无效数据包
iptables -A INPUT -m state --state INVALID -j DROP
# 限制 SYN 洪水攻击
iptables -N SYN_FLOOD
iptables -A INPUT -p tcp --syn -j SYN_FLOOD
iptables -A SYN_FLOOD -m limit --limit 10/s --limit-burst 20 -j RETURN
iptables -A SYN_FLOOD -j DROP
# 限制 ICMP 洪水
iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 10 -j ACCEPT
iptables -A INPUT -p icmp -j DROP
# 安装 fail2ban
sudo apt-get install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # CentOS/RHEL
# 配置 /etc/fail2ban/jail.local 添加自定义规则
# Nginx 示例配置
http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m;
server {
limit_conn addr 10;
limit_req zone=one burst=5;
}
}
wget https://www.inetbase.com/scripts/ddos/install.sh
chmod +x install.sh
./install.sh
# 安装
sudo apt-get install libapache2-mod-evasive # Debian/Ubuntu
# 配置 /etc/apache2/mods-enabled/evasive.conf
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 10
</IfModule>
# 查看网络连接状态
netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
# 使用 iftop 监控流量
iftop -nNP
# 使用 nload 监控带宽
nload
#!/bin/bash
# 自动封禁异常IP
netstat -anp | grep 'tcp\|udp' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n | \
while read count ip; do
if [ "$count" -gt 50 ]; then
iptables -I INPUT -s "$ip" -j DROP
echo "$(date) Banned $ip with $count connections" >> /var/log/ddos.log
fi
done
以上措施需要根据实际业务需求进行调整,对于大规模 DDoS 攻击,建议结合专业防护设备和云防护服务。