DDoS (分布式拒绝服务) 攻击是常见的网络安全威胁,以下是在 Linux 系统上设置防御措施的详细方案:
# 编辑 /etc/sysctl.conf 添加以下参数
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
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
# 限制单个IP的连接数
iptables -A INPUT -p tcp --dport 80 -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
nft add table ip filter
nft add chain ip filter input { type filter hook input priority 0 \; }
nft add rule ip filter input ct state invalid drop
nft add rule ip filter input tcp flags syn tcp dport 80 meter syn-flood size 100000 { ip saddr limit rate 10/second burst 20 packets } accept
nft add rule ip filter input tcp flags syn tcp dport 80 drop
# 安装
sudo apt install fail2ban # Debian/Ubuntu
sudo yum install fail2ban # CentOS/RHEL
# 配置 /etc/fail2ban/jail.local
[DEFAULT]
bantime = 1h
findtime = 600
maxretry = 5
[sshd]
enabled = true
wget https://www.inetbase.com/scripts/ddos/install.sh
chmod +x install.sh
./install.sh
# 在 /etc/nginx/nginx.conf 的 http 块中添加
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
# 在具体server配置中使用
server {
limit_req zone=one burst=20 nodelay;
limit_conn addr 10;
}
# 在 /etc/apache2/apache2.conf 中添加
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 5
DOSSiteCount 100
DOSPageInterval 2
DOSSiteInterval 2
DOSBlockingPeriod 600
</IfModule>
# 安装iftop监控网络流量
sudo apt install iftop
iftop -nNP
# 使用nload
nload eth0
# 使用vnStat长期监控
vnstat -l -i eth0
# 分析被拒绝的连接
grep DROP /var/log/syslog
grep DROP /var/log/messages
# 分析Web服务器日志
goaccess /var/log/nginx/access.log -a
当攻击发生时: 1. 立即启用备份带宽资源 2. 联系上游ISP寻求帮助 3. 临时屏蔽攻击源国家/地区的IP段 4. 考虑暂时切换到维护页面
以上措施需要根据实际业务需求和服务器性能进行调整。建议在实施前进行测试,确保不会影响正常业务流量。