mcpField
T
threat-modeling

threat-modeling

github.com/bagelhole安全1.2k359 次安装23 周前更新
代码仓库

关于 threat-modeling

threat-modeling 是一项用于系统设计阶段识别和缓解安全威胁的技能,适合开发、运维与安全团队协作使用。它提供 STRIDE、数据流图、威胁库和风险评分等结构化方法。

主要功能

  1. 01使用 STRIDE 分类威胁
  2. 02绘制数据流与信任边界
  3. 03维护可复用威胁库
  4. 04按可能性和影响评估风险
  5. 05记录风险处置与缓解措施

适用场景

  1. 01设计新系统或功能时评估威胁
  2. 02审查架构变更与第三方集成
  3. 03准备安全审计或合规审查
  4. 04根据安全事件改进防御

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill threat-modeling

安装后在 Claude Code 中输入/threat-modeling确认已加载。

附带文件references/threat-model-template.md

详细介绍

威胁建模

在系统设计期间识别并缓解安全威胁。

何时使用此技能

在以下情况下使用此技能:

  • 设计新系统、服务或功能
  • 对现有系统进行重大架构变更
  • 接入新的第三方集成或依赖项
  • 为安全审计或合规审查做准备
  • 响应安全事件并改进防御措施
  • 审查会影响信任边界的基础设施变更

前提条件

  • 系统架构文档或设计图
  • 可联系开发和运维团队以了解相关背景
  • 了解系统的数据分类(PII、PHI、财务数据等)
  • OWASP Threat Dragon 或 Microsoft Threat Modeling Tool(可选,但很有帮助)
  • 用于协作会议的白板或绘图工具

STRIDE 方法

威胁描述违反的属性缓解措施示例
S 欺骗冒充其他用户或系统身份验证MFA、mTLS、API 密钥验证、证书固定
T 篡改修改传输中或静态存储的数据完整性HMAC、数字签名、校验和、不可变日志
R 抵赖否认执行过某项操作不可抵赖性审计日志、数字签名、防篡改日志
I 信息泄露向未授权方暴露数据保密性加密(TLS、AES)、访问控制、数据脱敏
D 拒绝服务使服务不可用可用性速率限制、自动扩缩容、CDN、熔断器
E 权限提升获得未经授权的更高权限授权RBAC、最小权限原则、输入验证

STRIDE 工作表模板

# stride-worksheet.yaml - Fill out one per component/trust boundary crossing
component:
  name: "API Gateway"
  owner: "Platform Team"
  data_classification: "Confidential"
  trust_boundary: "External -> Internal"

threats:
  - id: T001
    category: Spoofing
    description: "Attacker forges JWT tokens to impersonate users"
    attack_vector: "Stolen signing key or weak algorithm (HS256 with guessable secret)"
    likelihood: Medium
    impact: Critical
    risk_score: 15  # likelihood(3) x impact(5)
    existing_controls:
      - "JWT validation on every request"
      - "RS256 algorithm with rotated keys"
    gaps:
      - "No token binding to device/IP"
    recommended_mitigations:
      - "Add token binding claims"
      - "Implement short-lived tokens (15 min) with refresh"
      - "Monitor for token reuse from different IPs"
    status: "Mitigated (partial)"
    owner: "Auth Team"

  - id: T002
    category: Tampering
    description: "Man-in-the-middle modifies API requests"
    attack_vector: "Compromised network between client and gateway"
    likelihood: Low
    impact: High
    risk_score: 8
    existing_controls:
      - "TLS 1.3 enforced"
      - "HSTS enabled"
    gaps: []
    recommended_mitigations:
      - "Certificate pinning for mobile clients"
    status: "Mitigated"
    owner: "Platform Team"

  - id: T003
    category: Information Disclosure
    description: "Verbose error messages leak internal details"
    attack_vector: "Triggering errors returns stack traces, internal IPs, DB schema"
    likelihood: High
    impact: Medium
    risk_score: 12
    existing_controls:
      - "Generic error pages in production"
    gaps:
      - "Some microservices return raw exceptions"
    recommended_mitigations:
      - "Centralized error handling middleware"
      - "Error response schema validation"
    status: "Open"
    owner: "Backend Team"

  - id: T004
    category: Denial of Service
    description: "API rate limiting bypass through distributed requests"
    attack_vector: "Botnet sending requests below per-IP threshold"
    likelihood: Medium
    impact: High
    risk_score: 12
    existing_controls:
      - "Per-IP rate limiting at WAF"
    gaps:
      - "No aggregate rate limiting"
      - "No bot detection"
    recommended_mitigations:
      - "Add aggregate rate limiting per endpoint"
      - "Deploy bot detection (Cloudflare Bot Management)"
      - "Implement circuit breaker pattern"
    status: "Open"
    owner: "Platform Team"

  - id: T005
    category: Elevation of Privilege
    description: "IDOR allows accessing other users' data"
    attack_vector: "Manipulating resource IDs in API calls"
    likelihood: Medium
    impact: Critical
    risk_score: 15
    existing_controls:
      - "Authentication required"
    gaps:
      - "Authorization checks inconsistent across endpoints"
    recommended_mitigations:
      - "Enforce ownership checks on all resource access"
      - "Use opaque IDs instead of sequential integers"
      - "Add authorization integration tests"
    status: "Open"
    owner: "Backend Team"

数据流图

基于文本的 DFD 表示法
                    Trust Boundary: Internet
                    ==========================
                           |
                    [External User]
                           |
                      HTTPS/443
                           |
                    ==========================
                    Trust Boundary: DMZ
                    ==========================
                           |
                    (WAF / CDN)
                           |
                    [API Gateway]---->[Auth Service]--->[Identity DB]
                           |
                    ==========================
                    Trust Boundary: Internal
                    ==========================
                           |
                    [App Service]
                       /       \
                      /         \
               [Cache]       [Message Queue]
                                  |
                           [Worker Service]
                                  |
                    ==========================
                    Trust Boundary: Data
                    ==========================
                                  |
                           [Primary DB]--->[Replica DB]
                                  |
                           [Object Store]

Legend:
  [Box]     = Process
  (Parens)  = External entity / proxy
  ====      = Trust boundary
  --->      = Data flow
Threat Dragon 模型(JSON)
{
  "summary": {
    "title": "E-Commerce Platform",
    "owner": "Security Team",
    "description": "Threat model for the e-commerce API platform"
  },
  "detail": {
    "diagrams": [
      {
        "title": "API Data Flow",
        "diagramType": "STRIDE",
        "cells": [
          {
            "type": "tm.Actor",
            "name": "Web Client",
            "threats": []
          },
          {
            "type": "tm.Process",
            "name": "API Gateway",
            "threats": ["T001", "T002", "T003", "T004"]
          },
          {
            "type": "tm.Process",
            "name": "Order Service",
            "threats": ["T005"]
          },
          {
            "type": "tm.Store",
            "name": "Orders Database",
            "threats": ["T006"]
          },
          {
            "type": "tm.Boundary",
            "name": "DMZ"
          },
          {
            "type": "tm.Boundary",
            "name": "Internal Network"
          }
        ]
      }
    ]
  }
}

威胁库

# threat-library.yaml - Reusable threat patterns
categories:
  authentication:
    - id: TL-AUTH-001
      name: "Credential stuffing"
      description: "Attacker uses leaked credential databases to attempt logins"
      applicable_to: ["login endpoints", "API authentication"]
      mitigations: ["MFA", "rate limiting", "credential breach monitoring", "CAPTCHA"]

    - id: TL-AUTH-002
      name: "Session hijacking"
      description: "Attacker steals session tokens via XSS or network sniffing"
      applicable_to: ["web applications", "APIs with session tokens"]
      mitigations: ["HttpOnly cookies", "TLS", "session binding", "short TTL"]

    - id: TL-AUTH-003
      name: "OAuth token theft"
      description: "Access tokens stolen from logs, URLs, or insecure storage"
      applicable_to: ["OAuth/OIDC integrations"]
      mitigations: ["PKCE", "short-lived tokens", "token binding", "secure storage"]

  injection:
    - id: TL-INJ-001
      name: "SQL injection"
      description: "Malicious SQL in user input executes unauthorized queries"
      applicable_to: ["database-backed endpoints", "search functionality"]
      mitigations: ["parameterized queries", "ORM", "input validation", "WAF"]

    - id: TL-INJ-002
      name: "Command injection"
      description: "User input passed to system commands without sanitization"
      applicable_to: ["file processing", "system administration features"]
      mitigations: ["avoid shell commands", "input allowlisting", "sandboxing"]

    - id: TL-INJ-003
      name: "SSRF (Server-Side Request Forgery)"
      description: "Attacker makes server send requests to internal resources"
      applicable_to: ["URL fetching features", "webhook handlers", "PDF generators"]
      mitigations: ["URL allowlisting", "network segmentation", "metadata endpoint blocking"]

  supply_chain:
    - id: TL-SC-001
      name: "Dependency confusion"
      description: "Malicious package with internal name published to public registry"
      applicable_to: ["npm, pip, maven projects using private packages"]
      mitigations: ["namespace scoping", "registry prioritization", "SBOM monitoring"]

    - id: TL-SC-002
      name: "Compromised CI/CD pipeline"
      description: "Attacker injects malicious code through build system compromise"
      applicable_to: ["all software builds"]
      mitigations: ["SLSA compliance", "signed commits", "ephemeral builders", "provenance"]

  data:
    - id: TL-DATA-001
      name: "Unencrypted data at rest"
      description: "Sensitive data stored without encryption on disk or in database"
      applicable_to: ["databases", "object storage", "backups"]
      mitigations: ["AES-256 encryption", "KMS-managed keys", "encrypted volumes"]

    - id: TL-DATA-002
      name: "PII exposure in logs"
      description: "Personal data written to application or infrastructure logs"
      applicable_to: ["all services handling PII"]
      mitigations: ["log sanitization", "structured logging", "PII detection scanning"]

风险评分矩阵

可能性评级
分数级别描述
1极低需要国家级资源;没有已知漏洞利用方式
2低需要丰富的专业知识和特定条件
3中技能中等的攻击者,且有现成工具可用
4高脚本小子级别;存在公开的漏洞利用方式
5极高利用极其简单;自动化扫描即可发现
影响评级
分数级别描述
1可忽略没有数据暴露;仅影响外观
2轻微少量数据暴露;影响单个用户
3中等大量数据暴露;服务性能下降
4重大大规模数据泄露;长时间服务中断
5严重系统完全遭到入侵;违反监管要求
风险矩阵
Impact ->     1        2        3        4        5
Likelihood
    5      Medium    High     High   Critical Critical
    4       Low     Medium    High    High   Critical
    3       Low      Low     Medium   High    High
    2      Info      Low      Low    Medium   High
    1      Info     Info      Low     Low    Medium
风险处置决策
risk_treatment:
  critical:  # Score >= 20
    action: "Immediate remediation required"
    sla: "24 hours"
    approval: "CISO"
  high:      # Score 12-19
    action: "Remediation in current sprint"
    sla: "1 week"
    approval: "Security Lead"
  medium:    # Score 6-11
    action: "Remediation in next sprint"
    sla: "1 month"
    approval: "Team Lead"
  low:       # Score 2-5
    action: "Track and address in backlog"
    sla: "1 quarter"
    approval: "Team Lead"
  info:      # Score 1
    action: "Accept risk and document"
    sla: "None"
    approval: "Team Lead"

OWASP Threat Dragon 设置

# Run Threat Dragon locally with Docker
docker run -d \
  --name threat-dragon \
  -p 3000:3000 \
  -e ENCRYPTION_KEYS='["threat-dragon-encryption-key-change-me"]' \
  -e NODE_ENV=production \
  owasp/threat-dragon:v2.2.0

# Access at http://localhost:3000

# Or install as desktop application
# Download from: https://github.com/OWASP/threat-dragon/releases
与 CI/CD 集成
# .github/workflows/threat-model-review.yml
name: Threat Model Review
on:
  pull_request:
    paths:
      - 'docs/threat-model/**'
      - 'architecture/**'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Validate threat model files
        run: |
          for model in docs/threat-model/*.yaml; do
            echo "Validating $model..."
            python -c "
          import yaml, sys
          with open('$model') as f:
              data = yaml.safe_load(f)
          required = ['component', 'threats']
          for r in required:
              if r not in data:
                  print(f'ERROR: Missing required field: {r}')
                  sys.exit(1)
          for t in data.get('threats', []):
              if t.get('status') == 'Open' and t.get('risk_score', 0) >= 12:
                  print(f'WARNING: High-risk open threat: {t[\"id\"]} - {t[\"description\"]}')
          print(f'OK: {len(data[\"threats\"])} threats documented')
          "
          done

      - name: Check for unaddressed critical threats
        run: |
          CRITICAL=$(grep -r "risk_score: \(1[5-9]\|2[0-5]\)" docs/threat-model/*.yaml | grep "status: \"Open\"" | wc -l)
          if [ "$CRITICAL" -gt 0 ]; then
            echo "WARNING: $CRITICAL critical/high-risk threats still open"
            echo "Review required before merging architectural changes"
          fi

故障排除

问题原因解决方案
威胁建模会议效率低下参与者不了解系统会前分享架构文档;安排系统导览
识别出的威胁过多范围过于宽泛每次会议聚焦一个组件或信任边界
威胁描述过于笼统缺少结构化方法针对每个元素使用 STRIDE;为每个元素填写工作表模板
团队没有跟进发现的问题缺少负责人或跟踪机制将每项威胁分配给一个团队并设定 SLA;在问题跟踪系统中跟进
威胁模型过时缺少更新触发条件要求在架构变更时进行审查(在 CI/CD 中设置图表变更门禁)
风险评分存在分歧评分主观始终使用评分矩阵;根据历史事件进行校准

最佳实践

  • 在设计阶段将威胁建模纳入 SDLC
  • 架构发生变化时,审查威胁模型
  • 邀请开发、运维和安全团队参与会议
  • 使用威胁库确保覆盖范围一致
  • 记录所有风险接受决策及其依据
  • 在与其他工作项相同的系统中跟踪威胁
  • 每年审查所有有效的威胁模型
  • 从最关键的数据流入手,再逐步扩展
  • 将会议时间限制在 90 分钟以内
  • 维护一个不断更新新模式的动态威胁库

相关技能

评论

支持 Markdown