一、端口被攻击的典型特征
当服务器出现以下迹象时,可能正在遭受端口攻击:
- 异常连接数激增
# 查看当前TCP连接状态 netstat -ant | awk '{print $6}' | sort | uniq -c # 输出示例: # 120 ESTABLISHED # 500 SYN_RECV ← 大量半连接请求(SYN Flood攻击)
- 日志中出现高频失败认证
# 检查SSH暴力破解日志(Ubuntu/Debian) grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr
- 带宽异常占用
# 实时监控指定端口流量(示例:监控22端口) iftop -i eth0 -f "port 22"
二、4步紧急响应流程
1. 快速定位攻击源
# 捕获当前活跃攻击IP(显示访问量前10的IP)
ss -ant | grep 'SYN-RECV' | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -n 10
2. 临时封禁高危IP
# 使用iptables封禁IP(示例:封禁192.168.1.100)
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
# 持久化规则(防止重启失效)
sudo iptables-save > /etc/iptables/rules.v4
3. 关闭非必要端口
# 查看所有开放端口
sudo ss -tuln
# 关闭3306端口(MySQL示例)
sudo ufw deny 3306/tcp
4. 启用端口访问频率限制
# 限制SSH端口(22)每分钟最多20次新连接
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 20 -j DROP
三、5个自动化防护脚本
1. 实时SYN洪水攻击检测(Python)
# 保存为 syn_flood_detect.py
from scapy.all import sniff, TCP, IP
from collections import defaultdict
syn_counter = defaultdict(int)
THRESHOLD = 100 # 每分钟100个SYN包触发告警
def packet_handler(pkt):
if pkt.haslayer(TCP) and pkt[TCP].flags == 'S':
src_ip = pkt[IP].src
syn_counter[src_ip] += 1
if syn_counter[src_ip] > THRESHOLD:
print(f"[!] SYN洪水攻击检测: {src_ip}")
# 自动封禁IP(需root权限)
os.system(f"iptables -A INPUT -s {src_ip} -j DROP")
# 启动嗅探(需sudo运行)
sniff(filter="tcp", prn=packet_handler, store=0)
2. 自动封禁SSH暴力破解IP(Fail2ban增强版)
# 创建自定义Fail2ban规则(/etc/fail2ban/jail.d/ssh-custom.conf)
[ssh-custom]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3 # 3次失败后封禁
findtime = 300 # 5分钟内
bantime = 86400 # 封禁24小时
action = iptables-allports[name=SSH, port=all] # 封禁所有端口访问
3. 高危端口流量监控(Bash)
# 保存为 port_monitor.sh
#!/bin/bash
HIGH_RISK_PORTS="22 3306 6379 27017" # SSH、MySQL、Redis、MongoDB
for port in $HIGH_RISK_PORTS; do
count=$(ss -ant | grep ":$port" | grep -v "LISTEN" | wc -l)
if [ $count -gt 50 ]; then
echo "$(date) - 端口 ${port} 异常连接数: ${count}" >> /var/log/port_attack.log
# 可选:触发防火墙封禁
fi
done
# 添加到cron每分钟执行
* * * * * root /path/to/port_monitor.sh
四、防御加固建议
- 修改默认端口:
# 修改SSH端口为59222 sudo sed -i 's/#Port 22/Port 59222/' /etc/ssh/sshd_config sudo systemctl restart sshd
- 禁用协议弱加密:
# 禁用SSH的密码认证 echo "PasswordAuthentication no" | sudo tee -a /etc/ssh/sshd_config
- 网络层防御工具:
- Cloudflare Spectrum:保护任意TCP/UDP端口
- Suricata:实时入侵检测(IDS)