# Nginx + ModSecurity配置示例
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
- rule: Unauthorized Process in Web Server
desc: Detect processes not normally part of web server operations
condition: >
proc.name in (web_server_processes) and
not proc.cmdline in (expected_web_server_commands)
output: >
Unexpected process in web server (user=%user.name command=%proc.cmdline)
priority: WARNING
from sklearn.ensemble import IsolationForest
# 训练异常检测模型
model = IsolationForest(n_estimators=100, contamination=0.01)
model.fit(normal_traffic_features)
# 实时检测
def detect_anomaly(request_features):
prediction = model.predict([request_features])
return prediction[0] == -1 # -1表示异常
威胁等级 | 响应措施 |
---|---|
低 | 记录日志,发送通知 |
中 | 临时限制请求速率 |
高 | 立即阻断IP,隔离服务 |
[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2
bantime = 86400
#!/bin/bash
# 自动响应Web攻击脚本
ATTACKER_IP=$1
ATTACK_TYPE=$2
# 1. 立即封锁IP
iptables -A INPUT -s $ATTACKER_IP -j DROP
# 2. 发送警报
echo "攻击警报: $ATTACK_TYPE 来自 $ATTACKER_IP" | \
mail -s "安全警报" admin@example.com
# 3. 创建事件记录
echo "$(date) - $ATTACK_TYPE - $ATTACKER_IP" >> /var/log/web_attacks.log
# 4. 可选: 触发取证快照
lvcreate -s -n webserver_snapshot_$(date +%s) -L 2G /dev/vg0/webdata
深度防御策略:
最小权限原则:
# Web服务器用户权限限制示例
chown -R www-data:www-data /var/www
chmod -R 750 /var/www
find /var/www -type d -exec chmod 2750 {} \;
持续更新:
# 自动更新规则脚本
# ModSecurity规则更新
git -C /etc/modsecurity/ pull origin master
# Suricata规则更新
suricata-update
红蓝对抗:
备份与恢复:
# 关键配置备份
tar -czvf /backups/web_config_$(date +%F).tar.gz /etc/nginx /etc/modsecurity
通过以上多层次的检测与响应机制,可以显著提高Linux服务器对Web接口攻击的防御能力,实现从检测到响应的全自动化安全防护。