{T}

高安全架构 学习笔记(第 8 部分)

4.4 重放攻击防护

javascript
// 重放攻击防护
class ReplayProtection {
  constructor() {
    this.nonceStore = new Map()
    this.timestampWindow = 60000  // 60秒时间窗口
  }
  
  // 生成请求签名
  generateSignature(request) {
    const crypto = require('crypto')
    
    // 构造签名字符串
    const signString = [
      request.method,
      request.path,
      request.timestamp,
      request.nonce,
      JSON.stringify(request.body || {})
    ].join('\n')
    
    // 使用密钥签名
    const signature = crypto
      .createHmac('sha256', this.getSecretKey())
      .update(signString)
      .digest('hex')
    
    return signature
  }
  
  // 验证请求
  verifyRequest(request) {
    // 1. 检查时间戳
    const timestampValid = this.checkTimestamp(request.timestamp)
    
    if (!timestampValid.valid) {
      return {
        valid: false,
        reason: timestampValid.reason
      }
    }
    
    // 2. 检查 nonce(防重放)
    const nonceValid = this.checkNonce(request.nonce, request.timestamp)
    
    if (!nonceValid.valid) {
      return {
        valid: false,
        reason: nonceValid.reason
      }
    }
    
    // 3. 验证签名
    const expectedSignature = this.generateSignature(request)
    
    if (request.signature !== expectedSignature) {
      return {
        valid: false,
        reason: '签名验证失败'
      }
    }
    
    return { valid: true }
  }
  
  // 检查时间戳
  checkTimestamp(timestamp) {
    const now = Date.now()
    const diff = Math.abs(now - timestamp)
    
    if (diff > this.timestampWindow) {
      return {
        valid: false,
        reason: `请求时间戳超出有效范围(${diff}ms > ${this.timestampWindow}ms)`
      }
    }
    
    return { valid: true }
  }
  
  // 检查 nonce
  checkNonce(nonce, timestamp) {
    // 检查 nonce 是否已使用
    if (this.nonceStore.has(nonce)) {
      return {
        valid: false,
        reason: 'Nonce 已使用,可能是重放攻击'
      }
    }
    
    // 存储 nonce
    this.nonceStore.set(nonce, timestamp)
    
    // 清理过期的 nonce
    this.cleanExpiredNonces()
    
    return { valid: true }
  }
  
  // 清理过期 nonce
  cleanExpiredNonces() {
    const now = Date.now()
    const expireTime = this.timestampWindow * 2
    
    for (const [nonce, timestamp] of this.nonceStore) {
      if (now - timestamp > expireTime) {
        this.nonceStore.delete(nonce)
      }
    }
  }
  
  // 获取密钥
  getSecretKey() {
    return 'your-secret-key'
  }
  
  // 生成 nonce
  generateNonce() {
    const crypto = require('crypto')
    return crypto.randomBytes(16).toString('hex')
  }
}
 
// 使用示例
const replayProtection = new ReplayProtection()
 
// 客户端发送请求
const request = {
  method: 'POST',
  path: '/api/payment',
  timestamp: Date.now(),
  nonce: replayProtection.generateNonce(),
  body: {
    amount: 100,
    userId: 'user123'
  }
}
 
// 生成签名
request.signature = replayProtection.generateSignature(request)
 
console.log('请求:', request)
 
// 服务器验证请求
const result = replayProtection.verifyRequest(request)
 
console.log('验证结果:', result)  // { valid: true }

4.5 安全防护措施总结

javascript
// 综合安全防护
const securityMeasures = {
  // WAF (Web 应用防火墙)
  waf: {
    features: [
      'SQL 注入防护',
      'XSS 攻击防护',
      'CSRF 防护',
      '恶意爬虫识别',
      '敏感信息泄露防护'
    ],
    implementation: 'ModSecurity / 云 WAF'
  },
  
  // IDS/IPS (入侵检测/防御系统)
  ids_ips: {
    ids: {
      name: '入侵检测系统',
      function: '检测并告警可疑行为',
      mode: '被动'
    },
    ips: {
      name: '入侵防御系统',
      function: '主动阻止攻击行为',
      mode: '主动'
    },
    tools: ['Snort', 'Suricata', 'OSSIM']
  },
  
  // VPN (虚拟专用网络)
  vpn: {
    protocols: ['IPSec', 'OpenVPN', 'WireGuard'],
    useCase: '远程安全访问',
    encryption: '端到端加密'
  },
  
  // 加密传输
  encryption: {
    https: 'SSL/TLS 加密',
    ssh: 'SSH 隧道加密',
    vpn: 'VPN 隧道加密'
  }
}

五、身份安全

5.1 身份安全三要素

plaintext
身份安全三要素:
 
1. 认证 (Authentication)
   ├── 验证用户身份
   ├── JWT、OAuth 2.0
   └── 多因素认证 (MFA)
 
2. 授权 (Authorization)
   ├── 权限控制
   ├── RBAC、ABAC
   └── 细粒度权限管理
 
3. 审计 (Audit)
   ├── 操作日志记录
   ├── 异常行为检测
   └── 合规性审计