# 安全加固实施指南 ## 🎯 解决方案概述 本方案采用**多层防护**策略,不依赖IP黑名单,而是基于**行为模式检测**来阻止攻击。 ## 📋 已实现的安全功能 ### 1. ✅ 速率限制(Rate Limiting) - **文件**:`lib/security/rate-limiter.ts` - **功能**: - API请求:每分钟100次 - 认证请求:每分钟5次 - 严格模式:每分钟10次 - **优势**:自动阻止异常请求,不依赖IP黑名单 ### 2. ✅ 可疑请求检测 - **文件**:`lib/security/request-monitor.ts` - **功能**: - 检测可疑路径(/.env, /.git等) - 检测可疑User-Agent - 记录所有可疑请求 - **优势**:基于行为模式,适用于所有攻击者 ### 3. ✅ 输入清理和验证 - **文件**:`lib/security/input-sanitizer.ts` - **功能**: - 移除命令注入字符(; | ` $等) - 移除危险关键词(wget, curl, bash等) - 防止路径遍历(../) - 防止XSS攻击 - **优势**:在数据进入应用前就清理,防止命令注入 ### 4. ✅ 中间件集成 - **文件**:`middleware.ts` - **功能**: - 自动应用速率限制 - 检测可疑请求 - 记录安全事件 - **优势**:所有请求都经过安全检查 ## 🚀 实施步骤 ### 步骤1:部署代码更新 ```bash # 1. 提交代码更改 git add lib/security/ middleware.ts scripts/ git commit -m "feat: 添加多层安全防护机制" git push # 2. 在服务器上拉取更新 cd /var/www/ai-chatbot git pull # 3. 重新构建 pnpm install pnpm build # 4. 重启应用 pm2 restart ai-chatbot ``` ### 步骤2:安装fail2ban(SSH防护) ```bash # 在服务器上执行 bash scripts/install-fail2ban.sh # 或手动安装 dnf install -y epel-release fail2ban systemctl enable fail2ban systemctl start fail2ban ``` ### 步骤3:在API路由中应用输入验证 在关键的API路由中添加输入验证: ```typescript import { validateRequestBody } from "@/lib/security/input-sanitizer"; export async function POST(request: Request) { const body = await request.json(); // 验证和清理请求体 const validation = await validateRequestBody(body); if (!validation.valid) { return NextResponse.json( { error: "Invalid request", details: validation.errors }, { status: 400 } ); } // 使用清理后的数据 const sanitizedBody = validation.sanitized; // ... 处理请求 } ``` ## 🔍 监控和日志 ### 查看安全日志 ```bash # 查看应用日志中的安全事件 tail -f /var/log/pm2/ai-chatbot-out.log | grep "Security" # 查看fail2ban日志 tail -f /var/log/fail2ban.log # 查看被封禁的IP fail2ban-client status sshd ``` ### 监控指标 - 速率限制触发次数 - 可疑请求检测次数 - 输入验证失败次数 - fail2ban封禁的IP数量 ## 🛡️ 防护效果 ### 防止的攻击类型 1. ✅ **命令注入**:通过输入清理和验证 2. ✅ **暴力破解**:通过速率限制和fail2ban 3. ✅ **DDoS攻击**:通过速率限制 4. ✅ **路径遍历**:通过输入清理 5. ✅ **XSS攻击**:通过输入清理 6. ✅ **异常请求**:通过可疑请求检测 ### 优势 - 🌍 **不依赖IP黑名单**:适用于所有攻击者 - 🔄 **自动适应**:基于行为模式检测 - 📊 **可监控**:详细的安全日志 - ⚡ **高性能**:轻量级实现,不影响性能 ## 📚 进一步优化建议 ### 短期(1-2周) 1. 在所有API路由中应用输入验证 2. 配置fail2ban监控更多服务(Nginx、PostgreSQL等) 3. 设置安全告警(邮件/短信通知) ### 中期(1-2月) 1. 集成CrowdSec获取社区威胁情报 2. 实施更细粒度的速率限制策略 3. 添加请求签名验证 ### 长期(3-6月) 1. 部署ModSecurity WAF 2. 实施SELinux策略 3. 建立安全审计流程 ## 🆘 应急响应 如果发现新的攻击: 1. 检查应用日志:`tail -f /var/log/pm2/ai-chatbot-error.log` 2. 检查fail2ban状态:`fail2ban-client status` 3. 手动封禁IP:`fail2ban-client set sshd banip ` 4. 更新可疑模式:编辑 `lib/security/request-monitor.ts` 5. 更新输入清理规则:编辑 `lib/security/input-sanitizer.ts`