{T}

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

Node.js HTTPS 服务器

javascript
// HTTPS 服务器配置
const https = require('https')
const fs = require('fs')
 
const options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('certificate.pem'),
  ca: fs.readFileSync('ca-bundle.pem')
}
 
const server = https.createServer(options, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html' })
  res.end('<h1>HTTPS 安全连接</h1>')
})
 
server.listen(443, () => {
  console.log('HTTPS 服务器运行在 https://localhost:443')
})
 
// 强制 HTTPS 跳转
const http = require('http')
 
const httpServer = http.createServer((req, res) => {
  res.writeHead(301, {
    Location: `https://${req.headers.host}${req.url}`
  })
  res.end()
})
 
httpServer.listen(80, () => {
  console.log('HTTP 服务器运行在 http://localhost:80(自动跳转 HTTPS)')
})

3.4 数据保护

javascript
// 数据保护策略
class DataProtection {
  constructor() {
    this.backupSchedule = '0 2 * * *'  // 每天凌晨2点备份
  }
  
  // 数据脱敏
  maskSensitiveData(data, fields) {
    const masked = { ...data }
    
    for (const field of fields) {
      if (masked[field]) {
        masked[field] = this.maskValue(masked[field])
      }
    }
    
    return masked
  }
  
  // 脱敏规则
  maskValue(value) {
    const str = String(value)
    
    // 手机号:138****1234
    if (/^\d{11}$/.test(str)) {
      return str.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }
    
    // 身份证:110***********1234
    if (/^\d{17}[\dXx]$/.test(str)) {
      return str.replace(/^(.{3})(.{12})(.{3})$/, '$1************$3')
    }
    
    // 邮箱:a***@example.com
    if (/@/.test(str)) {
      const [local, domain] = str.split('@')
      const maskedLocal = local[0] + '***'
      return `${maskedLocal}@${domain}`
    }
    
    // 银行卡:6222 **** **** 1234
    if (/^\d{16,19}$/.test(str)) {
      return str.replace(/(\d{4})\d+(\d{4})/, '$1 **** **** $2')
    }
    
    // 默认:保留前2位和后2位
    if (str.length > 4) {
      return str[0] + str[1] + '***' + str[str.length - 2] + str[str.length - 1]
    }
    
    return '***'
  }
  
  // 数据备份
  async backup(data, location) {
    const backup = {
      id: this.generateBackupId(),
      timestamp: Date.now(),
      data: this.encryptData(data),
      checksum: this.calculateChecksum(data),
      location
    }
    
    await this.saveBackup(backup)
    
    return backup
  }
  
  // 数据恢复
  async restore(backupId) {
    const backup = await this.loadBackup(backupId)
    
    // 验证校验和
    const decrypted = this.decryptData(backup.data)
    const checksum = this.calculateChecksum(decrypted)
    
    if (checksum !== backup.checksum) {
      throw new Error('备份数据校验失败,可能已被篡改')
    }
    
    return decrypted
  }
  
  // 辅助方法
  generateBackupId() {
    return `backup-${Date.now()}`
  }
  
  encryptData(data) {
    // 使用加密算法加密数据
    return JSON.stringify(data)
  }
  
  decryptData(encrypted) {
    return JSON.parse(encrypted)
  }
  
  calculateChecksum(data) {
    const crypto = require('crypto')
    return crypto.createHash('sha256').update(JSON.stringify(data)).digest('hex')
  }
  
  async saveBackup(backup) {
    console.log('保存备份:', backup.id)
  }
  
  async loadBackup(backupId) {
    console.log('加载备份:', backupId)
    return {}
  }
}
 
// 使用示例
const protection = new DataProtection()
 
// 数据脱敏
const userData = {
  name: '张三',
  phone: '13812345678',
  idCard: '110101199001011234',
  email: 'zhangsan@example.com',
  bankCard: '6222021234567890123'
}
 
const maskedData = protection.maskSensitiveData(userData, ['phone', 'idCard', 'email', 'bankCard'])
 
console.log('原始数据:', userData)
console.log('脱敏数据:', maskedData)
/*
脱敏数据:
{
  name: '张三',
  phone: '138****5678',
  idCard: '110***********234',
  email: 'z***@example.com',
  bankCard: '6222 **** **** 0123'
}
*/

四、通信安全

4.1 常见网络攻击类型

plaintext
常见网络攻击:
 
┌─────────────────────────────────┐
│  DDoS 攻击                       │
│  分布式拒绝服务攻击               │
│  - 大量请求耗尽服务器资源         │
│  - 目标:使服务不可用             │
└─────────────────────────────────┘
 
┌─────────────────────────────────┐
│  DNS 劫持                        │
│  篡改 DNS 解析结果                │
│  - 将域名解析到错误 IP           │
│  - 目标:钓鱼、窃取信息           │
└─────────────────────────────────┘
 
┌─────────────────────────────────┐
│  重放攻击                        │
│  重复发送合法请求                 │
│  - 截获并重复发送请求             │
│  - 目标:重复执行操作             │
└─────────────────────────────────┘
 
┌─────────────────────────────────┐
│  ARP 欺骗                        │
│  伪造 ARP 响应                    │
│  - 篡改 MAC 地址映射             │
│  - 目标:中间人攻击               │
└─────────────────────────────────┘
 
┌─────────────────────────────────┐
│  中间人攻击 (MITM)               │
│  拦截通信双方消息                 │
│  - 窃听、篡改通信内容             │
│  - 目标:窃取敏感信息             │
└─────────────────────────────────┘