security-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Review

安全评审

You are a senior security engineer conducting a focused security review using LLM-powered reasoning and STRIDE threat modeling. This skill scans code for vulnerabilities and validates findings for exploitability.
你是一名资深安全工程师,正在使用LLM驱动的推理和STRIDE威胁建模进行针对性安全评审。该技能可扫描代码中的漏洞并验证漏洞的可利用性。

When to Use This Skill

何时使用该技能

  • PR security review - Analyze code changes before merge
  • Weekly scheduled scan - Review commits from the last 7 days
  • Full repository audit - Comprehensive security assessment
  • Manual trigger -
    @droid security
    in PR comments
  • PR安全评审 - 合并前分析代码变更
  • 每周定时扫描 - 检查过去7天的提交
  • 全仓库审计 - 全面安全评估
  • 手动触发 - 在PR评论中输入
    @droid security

Prerequisites

前置条件

  • Git repository with code to review
  • .factory/threat-model.md
    (auto-generated if missing via
    threat-model-generation
    skill)
  • 包含待评审代码的Git仓库
  • .factory/threat-model.md
    (若缺失可通过
    threat-model-generation
    技能自动生成)

Workflow Position

工作流位置

┌──────────────────────┐
│ threat-model-        │  ← Generates STRIDE threat model
│ generation           │
└─────────┬────────────┘
          ↓ .factory/threat-model.md
┌──────────────────────┐
│ security-review      │  ← THIS SKILL (scan + validate)
│ (commit-scan +       │
│  validation)         │
└─────────┬────────────┘
          ↓ validated-findings.json
┌──────────────────────┐
│ security-patch-      │  ← Generates fixes
│ generation           │
└──────────────────────┘
┌──────────────────────┐
│ threat-model-        │  ← 生成STRIDE威胁模型
│ generation           │
└─────────┬────────────┘
          ↓ .factory/threat-model.md
┌──────────────────────┐
│ security-review      │  ← 本技能(扫描+验证)
│ (commit-scan +       │
│  validation)         │
└─────────┬────────────┘
          ↓ validated-findings.json
┌──────────────────────┐
│ security-patch-      │  ← 生成修复补丁
│ generation           │
└──────────────────────┘

Inputs

输入参数

InputDescriptionRequiredDefault
Mode
pr
,
weekly
,
full
,
staged
,
commit-range
No
pr
(auto-detected)
Base branchBranch to diff againstNoAuto-detected from PR
CVE lookbackHow far back to check dependency CVEsNo12 months
Severity thresholdMinimum severity to reportNo
medium
输入项描述是否必填默认值
Mode
pr
,
weekly
,
full
,
staged
,
commit-range
pr
(自动检测)
Base branch用于对比的基准分支从PR中自动检测
CVE lookback检查依赖项CVE的回溯时长12个月
Severity threshold报告的最低漏洞级别
medium

Instructions

操作步骤

Step 1: Check Threat Model

步骤1:检查威胁模型

bash
undefined
bash
undefined

Check if threat model exists

Check if threat model exists

if [ -f ".factory/threat-model.md" ]; then echo "Threat model found"

Check age

LAST_MODIFIED=$(stat -f %m .factory/threat-model.md 2>/dev/null || stat -c %Y .factory/threat-model.md) DAYS_OLD=$(( ($(date +%s) - $LAST_MODIFIED) / 86400 )) if [ $DAYS_OLD -gt 90 ]; then echo "WARNING: Threat model is $DAYS_OLD days old. Consider regenerating." fi else echo "No threat model found. Generate one first using threat-model-generation skill." fi

**If missing:**
- PR mode: Auto-generate threat model, commit to PR branch, then proceed
- Weekly/Full mode: Auto-generate threat model, include in report PR, then proceed

**If outdated (>90 days):**
- PR mode: Warn in comment, proceed with existing
- Weekly/Full mode: Auto-regenerate before scan
if [ -f ".factory/threat-model.md" ]; then echo "Threat model found"

Check age

LAST_MODIFIED=$(stat -f %m .factory/threat-model.md 2>/dev/null || stat -c %Y .factory/threat-model.md) DAYS_OLD=$(( ($(date +%s) - $LAST_MODIFIED) / 86400 )) if [ $DAYS_OLD -gt 90 ]; then echo "WARNING: Threat model is $DAYS_OLD days old. Consider regenerating." fi else echo "No threat model found. Generate one first using threat-model-generation skill." fi

**若缺失:**
- PR模式:自动生成威胁模型,提交至PR分支后继续执行
- 每周/全量模式:自动生成威胁模型,包含在报告PR中后继续执行

**若已过期(超过90天):**
- PR模式:在评论中发出警告,使用现有模型继续执行
- 每周/全量模式:扫描前自动重新生成

Step 2: Determine Scan Scope

步骤2:确定扫描范围

bash
undefined
bash
undefined

PR mode - scan PR diff

PR mode - scan PR diff

git diff --name-only origin/HEAD... git diff --merge-base origin/HEAD
git diff --name-only origin/HEAD... git diff --merge-base origin/HEAD

Weekly mode - last 7 days on default branch

Weekly mode - last 7 days on default branch

git log --since="7 days ago" --name-only --pretty=format: | sort -u
git log --since="7 days ago" --name-only --pretty=format: | sort -u

Full mode - entire repository

Full mode - entire repository

find . -type f ( -name ".js" -o -name ".ts" -o -name ".py" -o -name ".go" -o -name "*.java" ) | head -500
find . -type f ( -name ".js" -o -name ".ts" -o -name ".py" -o -name ".go" -o -name "*.java" ) | head -500

Staged mode - staged changes only

Staged mode - staged changes only

git diff --staged --name-only

Document:
- Files to analyze
- Commit range (if applicable)
- Deployment context from threat model
git diff --staged --name-only

记录:
- 待分析文件
- 提交范围(如适用)
- 威胁模型中的部署上下文

Step 3: Security Scan (STRIDE-Based)

步骤3:基于STRIDE的安全扫描

Load the threat model and scan code for vulnerabilities in each STRIDE category:
加载威胁模型,针对每个STRIDE类别扫描代码漏洞:

S - Spoofing Identity

S - 身份伪造(Spoofing Identity)

Look for:
  • Weak authentication mechanisms
  • Session token vulnerabilities (storage in localStorage, missing httpOnly)
  • API key exposure
  • JWT vulnerabilities (none algorithm, weak secrets)
  • Missing MFA on sensitive operations
检查点:
  • 弱认证机制
  • Session令牌漏洞(存储在localStorage、缺失httpOnly属性)
  • API密钥泄露
  • JWT漏洞(none算法、弱密钥)
  • 敏感操作缺失MFA

T - Tampering with Data

T - 数据篡改(Tampering with Data)

Look for:
  • SQL Injection - String interpolation in queries
  • Command Injection - User input in system calls
  • XSS - Unescaped output, innerHTML, dangerouslySetInnerHTML
  • Mass Assignment - Unvalidated object updates
  • Path Traversal - User input in file paths
  • XXE - External entity processing in XML
检查点:
  • SQL注入 - 查询中的字符串插值
  • 命令注入 - 系统调用中使用用户输入
  • XSS - 未转义输出、innerHTML、dangerouslySetInnerHTML
  • 批量赋值 - 未验证的对象更新
  • 路径遍历 - 文件路径中使用用户输入
  • XXE - XML中的外部实体处理

R - Repudiation

R - 抵赖(Repudiation)

Look for:
  • Missing audit logs for sensitive operations
  • Insufficient logging of admin actions
  • No immutable audit trail
检查点:
  • 敏感操作缺失审计日志
  • 管理员操作日志记录不足
  • 无不可篡改的审计追踪

I - Information Disclosure

I - 信息泄露(Information Disclosure)

Look for:
  • IDOR - Direct object access without authorization
  • Verbose Errors - Stack traces, database details in responses
  • Hardcoded Secrets - API keys, passwords in code
  • Data Leaks - PII in logs, debug info exposure
检查点:
  • IDOR - 无授权直接访问对象
  • 详细错误信息 - 响应中包含堆栈跟踪、数据库细节
  • 硬编码密钥 - 代码中包含API密钥、密码
  • 数据泄露 - 日志中包含PII、调试信息暴露

D - Denial of Service

D - 拒绝服务(Denial of Service)

Look for:
  • Missing rate limiting
  • Unbounded file uploads
  • Regex DoS (ReDoS)
  • Resource exhaustion
检查点:
  • 缺失速率限制
  • 无限制文件上传
  • 正则表达式拒绝服务(ReDoS)
  • 资源耗尽

E - Elevation of Privilege

E - 权限提升(Elevation of Privilege)

Look for:
  • Missing authorization checks
  • Role/privilege manipulation via mass assignment
  • Privilege escalation paths
  • RBAC bypass
检查点:
  • 缺失授权检查
  • 通过批量赋值操纵角色/权限
  • 权限提升路径
  • RBAC绕过

Code Patterns to Detect

需检测的代码模式

python
undefined
python
undefined

SQL Injection (Tampering)

SQL Injection (Tampering)

sql = f"SELECT * FROM users WHERE id = {user_id}" # VULNERABLE cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) # SAFE
sql = f"SELECT * FROM users WHERE id = {user_id}" # VULNERABLE cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) # SAFE

Command Injection (Tampering)

Command Injection (Tampering)

os.system(f"ping {user_input}") # VULNERABLE subprocess.run(["ping", "-c", "1", user_input]) # SAFE
os.system(f"ping {user_input}") # VULNERABLE subprocess.run(["ping", "-c", "1", user_input]) # SAFE

XSS (Tampering)

XSS (Tampering)

element.innerHTML = userInput; // VULNERABLE element.textContent = userInput; // SAFE
element.innerHTML = userInput; // VULNERABLE element.textContent = userInput; // SAFE

IDOR (Information Disclosure)

IDOR (Information Disclosure)

def get_doc(doc_id): return Doc.query.get(doc_id) # VULNERABLE - no ownership check
def get_doc(doc_id): return Doc.query.get(doc_id) # VULNERABLE - no ownership check

Path Traversal (Tampering)

Path Traversal (Tampering)

file_path = f"/uploads/{user_filename}" # VULNERABLE filename = os.path.basename(user_input) # SAFE
undefined
file_path = f"/uploads/{user_filename}" # VULNERABLE filename = os.path.basename(user_input) # SAFE
undefined

Step 4: Dependency Vulnerability Scan

步骤4:依赖项漏洞扫描

Scan dependencies for known CVEs:
bash
undefined
扫描依赖项中的已知CVE:
bash
undefined

Node.js

Node.js

npm audit --json 2>/dev/null
npm audit --json 2>/dev/null

Python

Python

pip-audit --format json 2>/dev/null
pip-audit --format json 2>/dev/null

Go

Go

govulncheck -json ./... 2>/dev/null
govulncheck -json ./... 2>/dev/null

Rust

Rust

cargo audit --json 2>/dev/null

For each vulnerability:
1. Confirm version is affected
2. Search codebase for usage of vulnerable APIs
3. Classify reachability: `REACHABLE`, `POTENTIALLY_REACHABLE`, `NOT_REACHABLE`
cargo audit --json 2>/dev/null

针对每个漏洞:
1. 确认当前版本受影响
2. 在代码库中搜索易受攻击API的使用情况
3. 分类可达性:`REACHABLE`、`POTENTIALLY_REACHABLE`、`NOT_REACHABLE`

Step 5: Generate Initial Findings

步骤5:生成初始检测结果

Output
security-findings.json
:
json
{
  "scan_id": "scan-<timestamp>",
  "scan_date": "<ISO timestamp>",
  "scan_mode": "pr | weekly | full",
  "commit_range": "abc123..def456",
  "threat_model_version": "1.0.0",
  "findings": [
    {
      "id": "VULN-001",
      "severity": "HIGH",
      "stride_category": "Tampering",
      "vulnerability_type": "SQL Injection",
      "cwe": "CWE-89",
      "file": "src/api/users.js",
      "line_range": "45-49",
      "code_context": "const sql = `SELECT * FROM users WHERE name LIKE '%${query}%'`",
      "analysis": "User input from query parameter directly interpolated into SQL query without parameterization.",
      "exploit_scenario": "Attacker submits: test' OR '1'='1 to bypass search filter and retrieve all users.",
      "threat_model_reference": "Section 5.2 - SQL Injection",
      "recommended_fix": "Use parameterized queries: db.query('SELECT * FROM users WHERE name LIKE $1', [`%${query}%`])",
      "confidence": "HIGH"
    }
  ],
  "dependency_findings": [
    {
      "id": "DEP-001",
      "package": "lodash",
      "version": "4.17.20",
      "ecosystem": "npm",
      "vulnerability_id": "CVE-2021-23337",
      "severity": "HIGH",
      "cvss": 7.2,
      "fixed_version": "4.17.21",
      "reachability": "REACHABLE",
      "reachability_evidence": "lodash.template() called in src/utils/email.js:15"
    }
  ],
  "summary": {
    "total_findings": 5,
    "by_severity": {"CRITICAL": 0, "HIGH": 2, "MEDIUM": 2, "LOW": 1},
    "by_stride": {
      "Spoofing": 0,
      "Tampering": 2,
      "Repudiation": 0,
      "InfoDisclosure": 2,
      "DoS": 0,
      "ElevationOfPrivilege": 1
    }
  }
}
输出
security-findings.json
json
{
  "scan_id": "scan-<timestamp>",
  "scan_date": "<ISO timestamp>",
  "scan_mode": "pr | weekly | full",
  "commit_range": "abc123..def456",
  "threat_model_version": "1.0.0",
  "findings": [
    {
      "id": "VULN-001",
      "severity": "HIGH",
      "stride_category": "Tampering",
      "vulnerability_type": "SQL Injection",
      "cwe": "CWE-89",
      "file": "src/api/users.js",
      "line_range": "45-49",
      "code_context": "const sql = `SELECT * FROM users WHERE name LIKE '%${query}%'`",
      "analysis": "User input from query parameter directly interpolated into SQL query without parameterization.",
      "exploit_scenario": "Attacker submits: test' OR '1'='1 to bypass search filter and retrieve all users.",
      "threat_model_reference": "Section 5.2 - SQL Injection",
      "recommended_fix": "Use parameterized queries: db.query('SELECT * FROM users WHERE name LIKE $1', [`%${query}%`])",
      "confidence": "HIGH"
    }
  ],
  "dependency_findings": [
    {
      "id": "DEP-001",
      "package": "lodash",
      "version": "4.17.20",
      "ecosystem": "npm",
      "vulnerability_id": "CVE-2021-23337",
      "severity": "HIGH",
      "cvss": 7.2,
      "fixed_version": "4.17.21",
      "reachability": "REACHABLE",
      "reachability_evidence": "lodash.template() called in src/utils/email.js:15"
    }
  ],
  "summary": {
    "total_findings": 5,
    "by_severity": {"CRITICAL": 0, "HIGH": 2, "MEDIUM": 2, "LOW": 1},
    "by_stride": {
      "Spoofing": 0,
      "Tampering": 2,
      "Repudiation": 0,
      "InfoDisclosure": 2,
      "DoS": 0,
      "ElevationOfPrivilege": 1
    }
  }
}

Step 6: Validate Findings

步骤6:验证检测结果

For each finding, assess exploitability:
  1. Reachability Analysis - Is the vulnerable code path reachable from external input?
  2. Control Flow Tracing - Can attacker control the input that reaches the vulnerability?
  3. Mitigation Assessment - Are there existing controls (validation, sanitization, WAF)?
  4. Exploitability Check - How difficult is exploitation?
  5. Impact Analysis - What's the blast radius per threat model?
针对每个检测结果,评估可利用性:
  1. 可达性分析 - 易受攻击的代码路径是否可从外部输入访问?
  2. 控制流追踪 - 攻击者能否控制到达漏洞的输入?
  3. 缓解措施评估 - 是否存在现有控制措施(验证、 sanitization、WAF)?
  4. 可利用性检查 - 利用难度如何?
  5. 影响分析 - 根据威胁模型,影响范围有多大?

False Positive Filtering

误报过滤

HARD EXCLUSIONS - Automatically exclude:
  1. Denial of Service (DoS) without significant business impact
  2. Secrets stored on disk if properly secured
  3. Rate limiting concerns (informational only)
  4. Memory/CPU exhaustion without clear attack path
  5. Lack of input validation without proven impact
  6. GitHub Action vulnerabilities without specific untrusted input path
  7. Theoretical race conditions without practical exploit
  8. Memory safety issues in memory-safe languages (Rust, Go)
  9. Findings only in test files
  10. Log injection/spoofing concerns
  11. SSRF that only controls path (not host/protocol)
  12. User-controlled content in AI prompts
  13. ReDoS without demonstrated impact
  14. Findings in documentation files
  15. Missing audit logs (informational only)
PRECEDENTS:
  • Environment variables and CLI flags are trusted
  • UUIDs are unguessable
  • React/Angular are XSS-safe unless using
    dangerouslySetInnerHTML
    or
    bypassSecurityTrustHtml
  • Client-side code doesn't need auth checks (server responsibility)
  • Most ipython notebook findings are not exploitable
强制排除项 - 自动排除:
  1. 无显著业务影响的拒绝服务(DoS)
  2. 已妥善存储在磁盘上的密钥
  3. 速率限制问题(仅作信息提示)
  4. 无明确攻击路径的内存/CPU耗尽
  5. 无已证实影响的输入验证缺失
  6. 无特定不可信输入路径的GitHub Action漏洞
  7. 无实际利用方式的理论竞争条件
  8. 内存安全语言(Rust、Go)中的内存安全问题
  9. 仅在测试文件中出现的检测结果
  10. 日志注入/伪造问题
  11. 仅能控制路径的SSRF(无法控制主机/协议)
  12. AI提示中的用户可控内容
  13. 无已证实影响的ReDoS
  14. 文档文件中的检测结果
  15. 缺失审计日志(仅作信息提示)
判定先例:
  • 环境变量和CLI标记视为可信
  • UUID不可猜测
  • React/Angular默认XSS安全,除非使用
    dangerouslySetInnerHTML
    bypassSecurityTrustHtml
  • 客户端代码无需身份验证检查(由服务器负责)
  • 大多数ipython notebook检测结果不可利用

Confidence Scoring

置信度评分

  • 0.9-1.0: Certain exploit path, could generate working PoC
  • 0.8-0.9: Clear vulnerability pattern with known exploitation
  • 0.7-0.8: Suspicious pattern requiring specific conditions
  • Below 0.7: Don't report (too speculative)
Only report findings with confidence >= 0.8
  • 0.9-1.0:存在明确利用路径,可生成有效PoC
  • 0.8-0.9:存在清晰漏洞模式且已知利用方式
  • 0.7-0.8:存在可疑模式,但需特定条件触发
  • 低于0.7:不报告(过于推测性)
仅报告置信度≥0.8的检测结果

Step 7: Generate Proof of Concept

步骤7:生成概念验证(PoC)

For CONFIRMED HIGH/CRITICAL findings, generate minimal PoC:
json
{
  "proof_of_concept": {
    "payload": "' OR '1'='1",
    "request": "GET /api/users?search=test%27%20OR%20%271%27%3D%271",
    "expected_behavior": "Returns users matching 'test'",
    "actual_behavior": "Returns ALL users due to SQL injection"
  }
}
针对已确认的HIGH/CRITICAL级漏洞,生成最简PoC:
json
{
  "proof_of_concept": {
    "payload": "' OR '1'='1",
    "request": "GET /api/users?search=test%27%20OR%20%271%27%3D%271",
    "expected_behavior": "Returns users matching 'test'",
    "actual_behavior": "Returns ALL users due to SQL injection"
  }
}

Step 8: Generate Validated Findings

步骤8:生成已验证的检测结果

Output
validated-findings.json
:
json
{
  "validation_id": "val-<timestamp>",
  "validation_date": "<ISO timestamp>",
  "scan_id": "scan-<timestamp>",
  "threat_model_path": ".factory/threat-model.md",
  "validated_findings": [
    {
      "id": "VULN-001",
      "original_severity": "HIGH",
      "validated_severity": "HIGH",
      "status": "CONFIRMED",
      "stride_category": "Tampering",
      "vulnerability_type": "SQL Injection",
      "cwe": "CWE-89",
      "exploitability": "EASY",
      "reachability": "EXTERNAL",
      "file": "src/api/users.js",
      "line": 45,
      "existing_mitigations": [],
      "exploitation_path": [
        "User submits search query via GET /api/users?search=<payload>",
        "Express parses query string without validation",
        "Query passed directly to SQL template literal",
        "Database executes malicious SQL"
      ],
      "proof_of_concept": {
        "payload": "' OR '1'='1",
        "request": "GET /api/users?search=test%27%20OR%20%271%27%3D%271",
        "expected_behavior": "Returns users matching search",
        "actual_behavior": "Returns all users"
      },
      "cvss_vector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N",
      "cvss_score": 9.1,
      "recommendation": "Use parameterized queries",
      "references": [
        "https://cwe.mitre.org/data/definitions/89.html",
        "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"
      ]
    }
  ],
  "false_positives": [
    {
      "id": "VULN-003",
      "reason": "Input validated by Joi schema in middleware before reaching this endpoint",
      "evidence": "Validation in src/middleware/validate.js:12"
    }
  ],
  "dependency_findings": [
    {
      "id": "DEP-001",
      "status": "CONFIRMED",
      "package": "lodash",
      "version": "4.17.20",
      "vulnerability_id": "CVE-2021-23337",
      "severity": "HIGH",
      "reachability": "REACHABLE",
      "reachability_evidence": "lodash.template() called in src/utils/email.js:15",
      "fixed_version": "4.17.21"
    }
  ],
  "summary": {
    "total_scanned": 8,
    "confirmed": 5,
    "false_positives": 3,
    "by_severity": {
      "critical": 1,
      "high": 2,
      "medium": 1,
      "low": 1
    },
    "by_stride": {
      "Spoofing": 0,
      "Tampering": 3,
      "Repudiation": 0,
      "InfoDisclosure": 1,
      "DoS": 0,
      "ElevationOfPrivilege": 1
    }
  }
}
输出
validated-findings.json
json
{
  "validation_id": "val-<timestamp>",
  "validation_date": "<ISO timestamp>",
  "scan_id": "scan-<timestamp>",
  "threat_model_path": ".factory/threat-model.md",
  "validated_findings": [
    {
      "id": "VULN-001",
      "original_severity": "HIGH",
      "validated_severity": "HIGH",
      "status": "CONFIRMED",
      "stride_category": "Tampering",
      "vulnerability_type": "SQL Injection",
      "cwe": "CWE-89",
      "exploitability": "EASY",
      "reachability": "EXTERNAL",
      "file": "src/api/users.js",
      "line": 45,
      "existing_mitigations": [],
      "exploitation_path": [
        "User submits search query via GET /api/users?search=<payload>",
        "Express parses query string without validation",
        "Query passed directly to SQL template literal",
        "Database executes malicious SQL"
      ],
      "proof_of_concept": {
        "payload": "' OR '1'='1",
        "request": "GET /api/users?search=test%27%20OR%20%271%27%3D%271",
        "expected_behavior": "Returns users matching search",
        "actual_behavior": "Returns all users"
      },
      "cvss_vector": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N",
      "cvss_score": 9.1,
      "recommendation": "Use parameterized queries",
      "references": [
        "https://cwe.mitre.org/data/definitions/89.html",
        "https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"
      ]
    }
  ],
  "false_positives": [
    {
      "id": "VULN-003",
      "reason": "Input validated by Joi schema in middleware before reaching this endpoint",
      "evidence": "Validation in src/middleware/validate.js:12"
    }
  ],
  "dependency_findings": [
    {
      "id": "DEP-001",
      "status": "CONFIRMED",
      "package": "lodash",
      "version": "4.17.20",
      "vulnerability_id": "CVE-2021-23337",
      "severity": "HIGH",
      "reachability": "REACHABLE",
      "reachability_evidence": "lodash.template() called in src/utils/email.js:15",
      "fixed_version": "4.17.21"
    }
  ],
  "summary": {
    "total_scanned": 8,
    "confirmed": 5,
    "false_positives": 3,
    "by_severity": {
      "critical": 1,
      "high": 2,
      "medium": 1,
      "low": 1
    },
    "by_stride": {
      "Spoofing": 0,
      "Tampering": 3,
      "Repudiation": 0,
      "InfoDisclosure": 1,
      "DoS": 0,
      "ElevationOfPrivilege": 1
    }
  }
}

Step 9: Output Results (Mode-Dependent)

步骤9:输出结果(按模式区分)

PR Mode: Inline Comments

PR模式:内联评论

For each finding, post inline PR comment:
markdown
🔴 **CRITICAL: SQL Injection (CWE-89)**

**STRIDE Category:** Tampering
**Confidence:** High
**File:** `src/api/users.js:45-49`

**Analysis:**
User input from `req.query.search` is directly interpolated into SQL query without parameterization.

**Suggested Fix:**
```diff
- const query = `SELECT * FROM users WHERE name LIKE '%${search}%'`;
- const results = await db.query(query);
+ const query = `SELECT * FROM users WHERE name LIKE $1`;
+ const results = await db.query(query, [`%${search}%`]);

Post summary tracking comment:

```markdown
针对每个检测结果,发布PR内联评论:
markdown
🔴 **CRITICAL: SQL Injection (CWE-89)**

**STRIDE Category:** Tampering
**Confidence:** High
**File:** `src/api/users.js:45-49`

**Analysis:**
User input from `req.query.search` is directly interpolated into SQL query without parameterization.

**Suggested Fix:**
```diff
- const query = `SELECT * FROM users WHERE name LIKE '%${search}%'`;
- const results = await db.query(query);
+ const query = `SELECT * FROM users WHERE name LIKE $1`;
+ const results = await db.query(query, [`%${search}%`]);

发布汇总跟踪评论:

```markdown

🔒 Security Review Summary

🔒 安全评审汇总

SeverityCount
🔴 Critical1
🟠 High2
🟡 Medium3
🔵 Low0
漏洞级别数量
🔴 Critical1
🟠 High2
🟡 Medium3
🔵 Low0

Findings

检测结果

IDSeverityTypeFileStatus
VULN-001CriticalSQL Injectionsrc/api/users.js:45Action required
VULN-002HighXSSsrc/components/Comment.tsx:23Suggested fix

Reply
@droid dismiss VULN-XXX reason: <explanation>
to acknowledge a finding.
undefined
ID漏洞级别类型文件状态
VULN-001CriticalSQL Injectionsrc/api/users.js:45需要处理
VULN-002HighXSSsrc/components/Comment.tsx:23建议修复

回复
@droid dismiss VULN-XXX reason: <explanation>
确认检测结果。
undefined

Weekly/Full Mode: Security Report PR

每周/全量模式:安全报告PR

Create branch:
droid/security-report-{YYYY-MM-DD}
PR Title:
fix(security): Security scan report - {date} ({N} findings)
Include:
  • .factory/security/reports/security-report-{YYYY-MM-DD}.md
  • validated-findings.json
  • Updated
    .factory/threat-model.md
    (if regenerated)
创建分支:
droid/security-report-{YYYY-MM-DD}
PR标题:
fix(security): Security scan report - {date} ({N} findings)
包含内容:
  • .factory/security/reports/security-report-{YYYY-MM-DD}.md
  • validated-findings.json
  • 更新后的
    .factory/threat-model.md
    (若重新生成)

Step 10: Severity Actions

步骤10:按漏洞级别执行操作

SeverityPR ModeWeekly/Full Mode
CRITICAL
REQUEST_CHANGES
- blocks merge
Create HIGH priority issue, notify security team
HIGH
REQUEST_CHANGES
(configurable)
Create issue, require review
MEDIUM
COMMENT
only
Create issue
LOW
COMMENT
only
Include in report
漏洞级别PR模式每周/全量模式
CRITICAL
REQUEST_CHANGES
- 阻止合并
创建高优先级Issue,通知安全团队
HIGH
REQUEST_CHANGES
(可配置)
创建Issue,要求评审
MEDIUM
COMMENT
创建Issue
LOW
COMMENT
包含在报告中

Severity Definitions

漏洞级别定义

SeverityCriteriaExamples
CRITICALImmediately exploitable, high impact, no auth requiredRCE, hardcoded production secrets, auth bypass
HIGHExploitable with some conditions, significant impactSQL injection, stored XSS, IDOR
MEDIUMRequires specific conditions, moderate impactReflected XSS, CSRF, info disclosure
LOWDifficult to exploit, low impactVerbose errors, missing security headers
漏洞级别判定标准示例
CRITICAL可立即利用,影响范围大,无需身份验证RCE、硬编码生产环境密钥、身份验证绕过
HIGH需特定条件可利用,影响显著SQL注入、存储型XSS、IDOR
MEDIUM需特定条件触发,影响中等反射型XSS、CSRF、信息泄露
LOW难以利用,影响较小详细错误信息、缺失安全头

Vulnerability Coverage

漏洞覆盖范围

STRIDE CategoryVulnerability Types
SpoofingWeak auth, session hijacking, token exposure, credential stuffing
TamperingSQL injection, XSS, command injection, mass assignment, path traversal
RepudiationMissing audit logs, insufficient logging
Info DisclosureIDOR, verbose errors, hardcoded secrets, data leaks
DoSMissing rate limits, resource exhaustion, ReDoS
Elevation of PrivilegeMissing authz, role manipulation, RBAC bypass
STRIDE类别漏洞类型
Spoofing弱认证、会话劫持、令牌泄露、凭证填充
TamperingSQL注入、XSS、命令注入、批量赋值、路径遍历
Repudiation缺失审计日志、日志记录不足
Info DisclosureIDOR、详细错误信息、硬编码密钥、数据泄露
DoS缺失速率限制、资源耗尽、ReDoS
Elevation of Privilege缺失授权检查、角色操纵、RBAC绕过

Success Criteria

成功标准

  • Threat model checked/generated
  • All changed files scanned
  • Dependencies scanned for CVEs
  • Findings validated for exploitability
  • False positives filtered
  • validated-findings.json
    generated
  • Results output in appropriate format (PR comments or report)
  • Severity actions applied
  • 已检查/生成威胁模型
  • 已扫描所有变更文件
  • 已扫描依赖项CVE
  • 已验证检测结果的可利用性
  • 已过滤误报
  • 已生成
    validated-findings.json
  • 已按合适格式输出结果(PR评论或报告)
  • 已按漏洞级别执行对应操作

Example Invocations

调用示例

PR security review:
Scan PR #123 for security vulnerabilities.
Manual trigger in PR:
@droid security
Full repository scan:
@droid security --full
Weekly scan (last 7 days):
Scan commits from the last 7 days on main for security vulnerabilities.
Scan and patch:
Run full security analysis on PR #123: scan, validate, and generate patches.
PR安全评审:
Scan PR #123 for security vulnerabilities.
PR中手动触发:
@droid security
全仓库扫描:
@droid security --full
每周扫描(过去7天):
Scan commits from the last 7 days on main for security vulnerabilities.
扫描并生成补丁:
Run full security analysis on PR #123: scan, validate, and generate patches.

File Structure

文件结构

.factory/
├── threat-model.md              # STRIDE threat model
├── security-config.json         # Configuration
└── security/
    ├── acknowledged.json        # Dismissed findings
    └── reports/
        └── security-report-{date}.md
.factory/
├── threat-model.md              # STRIDE威胁模型
├── security-config.json         # 配置文件
└── security/
    ├── acknowledged.json        # 已确认的检测结果
    └── reports/
        └── security-report-{date}.md

Dismissing Findings

确认检测结果

PR Mode - Reply to inline comment:
@droid dismiss reason: Input is validated by Joi schema in middleware
Weekly/Full Mode - Comment on report PR:
@droid dismiss VULN-007 reason: Accepted risk for internal admin tool
Dismissed findings stored in
.factory/security/acknowledged.json
.
PR模式 - 回复内联评论:
@droid dismiss reason: Input is validated by Joi schema in middleware
每周/全量模式 - 在报告PR中评论:
@droid dismiss VULN-007 reason: Accepted risk for internal admin tool
已确认的检测结果存储在
.factory/security/acknowledged.json
中。

Limitations

局限性

Cannot detect:
  • Business logic vulnerabilities
  • Zero-days with no known patterns
  • Vulnerabilities in compiled/minified code
  • Issues requiring runtime analysis
May not fully validate:
  • Complex multi-service data flows
  • Vulnerabilities requiring authentication state
无法检测:
  • 业务逻辑漏洞
  • 无已知模式的零日漏洞
  • 编译/压缩代码中的漏洞
  • 需要运行时分析的问题
可能无法完全验证:
  • 复杂多服务数据流
  • 需要认证状态的漏洞

References

参考资料