senior-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Senior Security Engineer

高级安全工程师

Expert-level security engineering and application security.
专业级安全工程与应用安全相关内容。

Core Competencies

核心能力

  • Application security (OWASP)
  • Infrastructure security
  • Threat modeling
  • Security code review
  • Penetration testing
  • Incident response
  • Compliance (SOC 2, GDPR, HIPAA)
  • Security architecture
  • 应用安全(OWASP)
  • 基础设施安全
  • 威胁建模
  • 安全代码审查
  • 渗透测试
  • 事件响应
  • 合规性(SOC 2、GDPR、HIPAA)
  • 安全架构

OWASP Top 10

OWASP Top 10

1. Broken Access Control

1. 访问控制失效

Vulnerabilities:
  • IDOR (Insecure Direct Object Reference)
  • Missing function-level access control
  • Privilege escalation
Prevention:
typescript
// Bad: Direct ID access
app.get('/api/users/:id', (req, res) => {
  const user = await db.user.findUnique({ where: { id: req.params.id } });
  res.json(user);
});

// Good: Authorization check
app.get('/api/users/:id', authorize(), (req, res) => {
  if (req.user.role !== 'admin' && req.user.id !== req.params.id) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  const user = await db.user.findUnique({ where: { id: req.params.id } });
  res.json(user);
});
漏洞类型:
  • IDOR(不安全的直接对象引用)
  • 缺失功能级访问控制
  • 权限提升
防范措施:
typescript
// Bad: Direct ID access
app.get('/api/users/:id', (req, res) => {
  const user = await db.user.findUnique({ where: { id: req.params.id } });
  res.json(user);
});

// Good: Authorization check
app.get('/api/users/:id', authorize(), (req, res) => {
  if (req.user.role !== 'admin' && req.user.id !== req.params.id) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  const user = await db.user.findUnique({ where: { id: req.params.id } });
  res.json(user);
});

2. Cryptographic Failures

2. 加密机制失效

Vulnerabilities:
  • Weak encryption
  • Exposed secrets
  • Missing TLS
Prevention:
typescript
// Password hashing
import bcrypt from 'bcrypt';

const SALT_ROUNDS = 12;

async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, SALT_ROUNDS);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}

// Encryption
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';

function encrypt(text: string, key: Buffer): string {
  const iv = randomBytes(16);
  const cipher = createCipheriv('aes-256-gcm', key, iv);
  const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();
  return Buffer.concat([iv, tag, encrypted]).toString('base64');
}
漏洞类型:
  • 弱加密
  • 密钥泄露
  • 缺失TLS
防范措施:
typescript
// Password hashing
import bcrypt from 'bcrypt';

const SALT_ROUNDS = 12;

async function hashPassword(password: string): Promise<string> {
  return bcrypt.hash(password, SALT_ROUNDS);
}

async function verifyPassword(password: string, hash: string): Promise<boolean> {
  return bcrypt.compare(password, hash);
}

// Encryption
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';

function encrypt(text: string, key: Buffer): string {
  const iv = randomBytes(16);
  const cipher = createCipheriv('aes-256-gcm', key, iv);
  const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();
  return Buffer.concat([iv, tag, encrypted]).toString('base64');
}

3. Injection

3. 注入攻击

Vulnerabilities:
  • SQL injection
  • NoSQL injection
  • Command injection
  • XSS
Prevention:
typescript
// SQL Injection - Use parameterized queries
// Bad
const query = `SELECT * FROM users WHERE email = '${email}'`;

// Good - Prisma (parameterized by default)
const user = await db.user.findUnique({ where: { email } });

// Good - Raw SQL with parameters
const user = await db.$queryRaw`SELECT * FROM users WHERE email = ${email}`;

// Command Injection
// Bad
exec(`convert ${filename} output.png`);

// Good - Use array form
execFile('convert', [filename, 'output.png']);

// XSS Prevention
// Bad
element.innerHTML = userInput;

// Good - Text content
element.textContent = userInput;

// Good - Sanitization
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
漏洞类型:
  • SQL注入
  • NoSQL注入
  • 命令注入
  • XSS
防范措施:
typescript
// SQL Injection - Use parameterized queries
// Bad
const query = `SELECT * FROM users WHERE email = '${email}'`;

// Good - Prisma (parameterized by default)
const user = await db.user.findUnique({ where: { email } });

// Good - Raw SQL with parameters
const user = await db.$queryRaw`SELECT * FROM users WHERE email = ${email}`;

// Command Injection
// Bad
exec(`convert ${filename} output.png`);

// Good - Use array form
execFile('convert', [filename, 'output.png']);

// XSS Prevention
// Bad
element.innerHTML = userInput;

// Good - Text content
element.textContent = userInput;

// Good - Sanitization
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);

4. Insecure Design

4. 不安全设计

Prevention:
  • Threat modeling in design phase
  • Security requirements
  • Abuse case testing
  • Defense in depth
防范措施:
  • 设计阶段开展威胁建模
  • 明确安全需求
  • 滥用场景测试
  • 深度防御

5. Security Misconfiguration

5. 安全配置错误

Checklist:
  • Remove default credentials
  • Disable directory listing
  • Configure security headers
  • Remove stack traces in production
  • Keep dependencies updated
Security Headers:
typescript
import helmet from 'helmet';

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:"],
      connectSrc: ["'self'", "https://api.example.com"],
    },
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true,
  },
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
检查清单:
  • 移除默认凭证
  • 禁用目录列表
  • 配置安全头
  • 生产环境移除堆栈跟踪
  • 保持依赖更新
安全头配置:
typescript
import helmet from 'helmet';

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:"],
      connectSrc: ["'self'", "https://api.example.com"],
    },
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true,
  },
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));

Threat Modeling

威胁建模

STRIDE Framework

STRIDE框架

ThreatPropertyExamples
SpoofingAuthenticationSession hijacking, credential theft
TamperingIntegritySQL injection, MITM attacks
RepudiationNon-repudiationMissing audit logs
Information DisclosureConfidentialityData breaches, verbose errors
Denial of ServiceAvailabilityDDoS, resource exhaustion
Elevation of PrivilegeAuthorizationPrivilege escalation
威胁类型影响属性示例
Spoofing(仿冒)身份认证会话劫持、凭证窃取
Tampering(篡改)完整性SQL注入、中间人攻击
Repudiation(抵赖)不可抵赖性缺失审计日志
Information Disclosure(信息泄露)保密性数据泄露、详细错误信息暴露
Denial of Service(拒绝服务)可用性DDoS攻击、资源耗尽
Elevation of Privilege(权限提升)授权权限提升

Threat Model Template

威胁模型模板

markdown
undefined
markdown
undefined

Threat Model: [System Name]

威胁模型:[系统名称]

System Overview

系统概述

[Description of system and its components]
[系统及其组件的描述]

Assets

资产

  1. User credentials
  2. Payment information
  3. Personal data
  1. 用户凭证
  2. 支付信息
  3. 个人数据

Trust Boundaries

信任边界

  1. Internet → Load Balancer
  2. Load Balancer → Application
  3. Application → Database
  1. 互联网 → 负载均衡器
  2. 负载均衡器 → 应用程序
  3. 应用程序 → 数据库

Data Flows

数据流

[Diagram of data flows]
[数据流图]

Threats Identified

已识别威胁

Threat 1: SQL Injection

威胁1:SQL注入

  • Category: Tampering
  • Asset: Database
  • Attack Vector: User input to search functionality
  • Impact: High (full database access)
  • Likelihood: Medium
  • Mitigation: Parameterized queries, input validation
  • 类别:篡改
  • 资产:数据库
  • 攻击向量:搜索功能的用户输入
  • 影响:高(完全访问数据库)
  • 可能性:中
  • 缓解措施:参数化查询、输入验证

Risk Assessment Matrix

风险评估矩阵

[High/Medium/Low ratings for each threat]
[每个威胁的高/中/低评级]

Recommended Controls

推荐控制措施

[Prioritized list of mitigations]
undefined
[按优先级排序的缓解措施列表]
undefined

Security Testing

安全测试

Automated Scanning

自动化扫描

SAST (Static Analysis):
bash
undefined
SAST(静态分析):
bash
undefined

Semgrep

Semgrep

semgrep --config=p/owasp-top-ten ./src
semgrep --config=p/owasp-top-ten ./src

npm audit

npm audit

npm audit --audit-level=high
npm audit --audit-level=high

Trivy

Trivy

trivy fs --severity HIGH,CRITICAL .

**DAST (Dynamic Analysis):**
```bash
trivy fs --severity HIGH,CRITICAL .

**DAST(动态分析):**
```bash

OWASP ZAP

OWASP ZAP

zap-cli quick-scan --self-contained -t https://target.com
zap-cli quick-scan --self-contained -t https://target.com

Nuclei

Nuclei

nuclei -u https://target.com -t cves/
undefined
nuclei -u https://target.com -t cves/
undefined

Manual Testing Checklist

手动测试检查清单

Authentication:
  • Brute force protection
  • Account lockout
  • Password complexity
  • MFA implementation
  • Session management
  • Password reset flow
Authorization:
  • IDOR testing
  • Privilege escalation
  • Function-level access
  • Data-level access
Input Validation:
  • SQL injection
  • XSS (stored, reflected, DOM)
  • Command injection
  • Path traversal
  • SSRF
API Security:
  • Rate limiting
  • Input validation
  • Authentication
  • Mass assignment
  • Excessive data exposure
身份认证:
  • 暴力破解防护
  • 账户锁定
  • 密码复杂度
  • MFA实现
  • 会话管理
  • 密码重置流程
授权控制:
  • IDOR测试
  • 权限提升测试
  • 功能级访问控制测试
  • 数据级访问控制测试
输入验证:
  • SQL注入测试
  • XSS(存储型、反射型、DOM型)测试
  • 命令注入测试
  • 路径遍历测试
  • SSRF测试
API安全:
  • 速率限制验证
  • 输入验证
  • 身份认证
  • 批量赋值测试
  • 过度数据暴露测试

Incident Response

事件响应

Response Phases

响应阶段

1. Preparation:
  • Incident response plan
  • Contact lists
  • Runbooks
  • Tools and access
2. Identification:
  • Alert triage
  • Scope assessment
  • Initial classification
3. Containment:
  • Short-term (isolate)
  • Long-term (patch)
  • Evidence preservation
4. Eradication:
  • Root cause removal
  • System hardening
  • Vulnerability patching
5. Recovery:
  • System restoration
  • Monitoring enhancement
  • Verification testing
6. Lessons Learned:
  • Incident review
  • Process improvement
  • Documentation update
1. 准备阶段:
  • 事件响应计划
  • 联系人列表
  • 运行手册
  • 工具与权限
2. 识别阶段:
  • 告警分诊
  • 范围评估
  • 初始分类
3. 遏制阶段:
  • 短期遏制(隔离)
  • 长期遏制(补丁修复)
  • 证据留存
4. 根除阶段:
  • 移除根本原因
  • 系统加固
  • 漏洞补丁
5. 恢复阶段:
  • 系统恢复
  • 监控增强
  • 验证测试
6. 经验总结:
  • 事件复盘
  • 流程改进
  • 文档更新

Incident Severity

事件严重程度

SeverityDescriptionResponse TimeExamples
CriticalActive breachImmediateData exfiltration, ransomware
HighImminent threat1 hourUnpatched critical CVE
MediumPotential risk24 hoursSuspicious activity
LowMinor issue72 hoursFailed login attempts
严重程度描述响应时间示例
关键正在发生的数据泄露立即响应数据外泄、勒索软件攻击
迫在眉睫的威胁1小时内响应未修复的关键CVE
潜在风险24小时内响应可疑活动
轻微问题72小时内响应登录失败尝试

Compliance

合规性

SOC 2 Controls

SOC 2控制要求

Security:
  • Access controls
  • Encryption
  • Vulnerability management
  • Incident response
Availability:
  • System monitoring
  • Disaster recovery
  • Capacity planning
Confidentiality:
  • Data classification
  • Encryption at rest
  • Access logging
安全:
  • 访问控制
  • 加密
  • 漏洞管理
  • 事件响应
可用性:
  • 系统监控
  • 灾难恢复
  • 容量规划
保密性:
  • 数据分类
  • 静态数据加密
  • 访问日志

GDPR Requirements

GDPR要求

  • Data inventory
  • Legal basis for processing
  • Privacy notices
  • Data subject rights
  • Data protection impact assessment
  • Breach notification procedures
  • Data processing agreements
  • Cross-border transfer mechanisms
  • 数据清单
  • 数据处理的法律依据
  • 隐私声明
  • 数据主体权利
  • 数据保护影响评估
  • 数据泄露通知流程
  • 数据处理协议
  • 跨境传输机制

Security Architecture

安全架构

Zero Trust Principles

零信任原则

  1. Verify explicitly: Always authenticate and authorize
  2. Least privilege: Minimal access required
  3. Assume breach: Design for compromise containment
  1. 持续验证:始终进行身份认证与授权
  2. 最小权限:仅授予必要的最小权限
  3. 假设 breach:按已被入侵的场景设计防御

Defense in Depth

深度防御

Layer 1: Perimeter
├── WAF
├── DDoS protection
└── Network firewall

Layer 2: Network
├── Segmentation
├── IDS/IPS
└── Network monitoring

Layer 3: Application
├── Input validation
├── Authentication
└── Authorization

Layer 4: Data
├── Encryption
├── Access controls
└── Backup/recovery

Layer 5: Endpoint
├── EDR
├── Patching
└── Configuration management
Layer 1: 边界层
├── WAF
├── DDoS防护
└── 网络防火墙

Layer 2: 网络层
├── 网络分段
├── IDS/IPS
└── 网络监控

Layer 3: 应用层
├── 输入验证
├── 身份认证
└── 授权控制

Layer 4: 数据层
├── 加密
├── 访问控制
└── 备份/恢复

Layer 5: 终端层
├── EDR
├── 补丁管理
└── 配置管理

Reference Materials

参考资料

  • references/owasp_testing.md
    - OWASP testing guide
  • references/threat_modeling.md
    - Threat modeling methodology
  • references/incident_response.md
    - IR procedures
  • references/compliance_checklist.md
    - Compliance requirements
  • references/owasp_testing.md
    - OWASP测试指南
  • references/threat_modeling.md
    - 威胁建模方法论
  • references/incident_response.md
    - 事件响应流程
  • references/compliance_checklist.md
    - 合规性检查清单

Scripts

脚本工具

bash
undefined
bash
undefined

Security scanner

安全扫描工具

python scripts/security_scan.py --target ./src --type sast
python scripts/security_scan.py --target ./src --type sast

Dependency audit

依赖审计工具

python scripts/dep_audit.py --manifest package.json
python scripts/dep_audit.py --manifest package.json

Compliance checker

合规性检查工具

python scripts/compliance_check.py --framework soc2
python scripts/compliance_check.py --framework soc2

Threat model generator

威胁模型生成工具

python scripts/threat_model.py --diagram architecture.yaml
undefined
python scripts/threat_model.py --diagram architecture.yaml
undefined