josemlopez avatar

threat-modeling-toolkit

AI-powered threat modeling toolkit with STRIDE/PASTA framework support. Analyze architecture, discover threats, verify controls, and generate comprehensive security reports.

version
1.0.0
GitHub stars
11

Install

/plugin install threat-modeling-toolkit@threat-modeling-toolkit

Run it inside Claude Code after adding the marketplace with /plugin marketplace add josemlopez/threat-modeling-toolkit.

Contents

Discovered from source

Skills 9

Compliance Mapping

Purpose

Map your threat model to compliance frameworks to:

  • Calculate compliance coverage percentages
  • Identify compliance gaps
  • Generate audit-ready documentation
  • Track requirements across multiple frameworks

Usage

/tm-compliance [--framework <name>] [--policy <path>] [--gaps-only]

Arguments:

  • --framework: Framework(s) to map: owasp, soc2, pci-dss, hipaa, gdpr, custom
  • --policy: Path to custom policy document
  • --gaps-only: Only show gaps/non-compliance

Supported Frameworks

OWASP Top 10 2021

IDName
A01Broken Access Control
A02Cryptographic Failures
A03Injection
A04Insecure Design
A05Security Misconfiguration
A06Vulnerable and Outdated Components
A07Identification and Authentication Failures
A08Software and Data Integrity Failures
A09Security Logging and Monitoring Failures
A10Server-Side Request Forgery (SSRF)

SOC2 Trust Services Criteria

CategoryDescription
CC6.1Logical and Physical Access Controls
CC6.2System Access Authentication
CC6.3Access Restriction and Privileges
CC6.6System Boundaries
CC6.7Transmission Integrity
CC6.8Data Integrity
CC7.1Configuration Management
CC7.2Change Management

PCI-DSS v4.0

RequirementDescription
1Install and maintain network security controls
2Apply secure configurations
3Protect stored account data
4Protect cardholder data during transmission
5Protect from malicious software
6Develop and maintain secure systems
7Restrict access by business need
8Identify users and authenticate access
9Restrict physical access
10Log and monitor access
11Test security regularly
12Support information security with policies

Mapping Process

For Each Framework Requirement

  1. Identify related threats

    • Match requirement to STRIDE categories
    • Find threats in those categories
  2. Identify related controls

    • Find controls that mitigate related threats
    • Check control implementation status
  3. Assess compliance status

    • compliant: All related controls implemented
    • partial: Some controls implemented
    • non-compliant: No controls or all missing
  4. Document evidence

    • Link to verified controls
    • Note gaps

Output Files

compliance.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "frameworks": [
    {
      "name": "OWASP Top 10 2021",
      "version": "2021",
      "overall_compliance": 82,
      "mappings": [
        {
          "requirement_id": "A01:2021",
          "requirement_name": "Broken Access Control",
          "description": "Restrictions on authenticated users not properly enforced",
          "stride_categories": ["elevation-of-privilege", "information-disclosure"],
          "related_threats": ["threat-010", "threat-011"],
          "related_controls": ["control-020", "control-021"],
          "status": "partial",
          "coverage": 85,
          "gaps": ["gap-005"],
          "evidence": [
            "RBAC implemented in src/middleware/authorize.ts",
            "Missing: Object-level authorization"
          ]
        }
      ]
    }
  ]
}

compliance-report.md (Visual Report)

# Compliance Report

**Generated**: [Date]
**Frameworks**: OWASP Top 10 2021, SOC2

## Executive Summary

COMPLIANCE OVERVIEW ═══════════════════════════════════════════════════════════

OWASP Top 10 2021 ───────────────────────────────────────────────────────── A01 Broken Access Control: ████████░░ 85% (1 gap) A02 Cryptographic Failures: ██████████ 100% A03 Injection: ███████░░░ 70% (3 gaps) A04 Insecure Design: ██████░░░░ 55% (5 gaps) A05 Security Misconfiguration: █████████░ 95% (1 gap) A06 Vulnerable Components: █████████░ 90% (1 gap) A07 Auth Failures: ████████░░ 75% (4 gaps) A08 Data Integrity Failures: ████████░░ 85% (2 gaps) A09 Logging Failures: ████████░░ 80% (2 gaps) A10 SSRF: ██████████ 100% ───────────────────────────────────────────────────────── OVERALL: ████████░░ 82%

SOC2 Trust Services ───────────────────────────────────────────────────────── CC6.1 Logical Access: █████████░ 90% (1 gap) CC6.2 Authentication: ████████░░ 80% (2 gaps) CC6.3 Access Restriction: █████████░ 95% (1 gap) ───────────────────────────────────────────────────────── OVERALL: █████████░ 88%


## OWASP Top 10 2021

### A01:2021 - Broken Access Control

┌─────────────────────────────────────────────────────────┐ │ STATUS: ⚠ Partial (85%) │ ├─────────────────────────────────────────────────────────┤ │ RELATED THREATS: │ │ • THREAT-010: IDOR in user profile │ │ • THREAT-011: Missing function-level access control │ │ │ │ CONTROLS: │ │ ✓ RBAC implementation │ │ ⚠ Object-level authorization (partial) │ │ │ │ GAPS: │ │ • GAP-005: Missing object-level checks │ │ │ │ EVIDENCE: │ │ src/middleware/authorize.ts:15-89 │ └─────────────────────────────────────────────────────────┘


### A02:2021 - Cryptographic Failures

┌─────────────────────────────────────────────────────────┐ │ STATUS: ✓ Compliant (100%) │ ├─────────────────────────────────────────────────────────┤ │ CONTROLS: │ │ ✓ TLS 1.3 enforced │ │ ✓ AES-256 encryption at rest │ │ ✓ Bcrypt password hashing │ │ │ │ EVIDENCE: │ │ src/config/tls.ts:5 │ │ src/db/encryption.ts:12 │ └─────────────────────────────────────────────────────────┘


[Additional requirements...]

STRIDE to Framework Mapping

OWASP Top 10

STRIDE CategoryOWASP Requirements
SpoofingA07
TamperingA03, A08
RepudiationA09
Information DisclosureA01, A02
Denial of ServiceA05
Elevation of PrivilegeA01, A04

SOC2

STRIDE CategorySOC2 Criteria
SpoofingCC6.1, CC6.2
TamperingCC6.7, CC6.8
RepudiationCC7.2
Information DisclosureCC6.1, CC6.3
Denial of ServiceCC6.6
Elevation of PrivilegeCC6.3

Instructions for Claude

When executing this skill:

  1. Load threat model state:

    • Read .threatmodel/state/threats.json
    • Read .threatmodel/state/controls.json
    • Read .threatmodel/state/gaps.json
  2. Load framework definitions:

    • Reference built-in framework mappings
    • Load custom policies if specified
  3. For each framework:

    • Map requirements to STRIDE categories
    • Find related threats
    • Find related controls
    • Assess coverage
  4. Calculate compliance:

    • Per-requirement status
    • Per-framework percentage
    • Overall score
  5. Generate reports with visuals IN THE FILES:

    • JSON for programmatic use
    • Markdown with ASCII progress bars, status boxes, and visual indicators
    • The compliance-report.md MUST include:
      • Visual progress bars: ████████░░ 85%
      • Status indicators: ✓, ⚠, ✗
      • Visual box frames for each requirement
    • These visuals go in the written file, not just console output
  6. Console summary (also display to user):

    Compliance Mapping Complete
    ===========================
    
    Frameworks Analyzed: 2
    
    OWASP Top 10 2021:
      A01 Broken Access Control:     ████████░░ 85%  (1 gap)
      A02 Cryptographic Failures:    ██████████ 100%
      A03 Injection:                 ███████░░░ 70%  (3 gaps)
      ...
      Overall: 82%
    
    SOC2 Trust Services:
      CC6.1 Logical Access:          █████████░ 90%  (1 gap)
      CC6.2 Authentication:          ████████░░ 80%  (2 gaps)
      ...
      Overall: 88%
    
    Total Gaps: 11
      High Priority: 4
      Medium Priority: 5
      Low Priority: 2
    
    Files Created:
      .threatmodel/state/compliance.json
      .threatmodel/reports/compliance-report.md
    
    Next Steps:
      Run /tm-report to generate full risk report
    

Reference Files

Drift Detection

Purpose

Compare current threat model state against a baseline to:

  • Identify new or removed assets
  • Detect changed data flows
  • Find new attack surface entries
  • Track control status changes
  • Highlight new potential threats

Usage

/tm-drift [--baseline <path>] [--create-baseline] [--watch]

Arguments:

  • --baseline: Specific baseline file to compare against
  • --create-baseline: Create new baseline after comparison
  • --watch: Continuous monitoring mode (future feature)

Drift Categories

Asset Changes

  • Added: New components discovered
  • Removed: Components no longer present
  • Modified: Properties changed (classification, owner, etc.)

Data Flow Changes

  • Added: New data flows between components
  • Removed: Flows no longer present
  • Modified: Protocol, encryption, or authentication changed

Attack Surface Changes

  • Added: New entry points exposed
  • Removed: Entry points removed
  • Modified: Authentication or configuration changed

Trust Boundary Changes

  • Added: New boundaries defined
  • Removed: Boundaries removed
  • Modified: Controls or scope changed

Control Status Changes

  • Implemented → Partial: Control degraded
  • Implemented → Missing: Control removed
  • Missing → Implemented: Control added
  • Verification status changed

Baseline Structure

Baselines are snapshots of the complete threat model state:

{
  "version": "1.0",
  "created": "ISO-8601",
  "project": "Project Name",
  "snapshot": {
    "assets": [...],
    "dataflows": [...],
    "trust_boundaries": [...],
    "attack_surface": [...],
    "threats": [...],
    "controls": [...],
    "gaps": [...]
  },
  "metadata": {
    "commit": "git-commit-hash",
    "author": "name",
    "reason": "baseline reason"
  }
}

Drift Report Format

drift-report.md

# Threat Model Drift Report

**Baseline**: 2025-01-15 (snapshot-20250115.json)
**Current**: 2025-01-20
**Period**: 5 days

---

## Summary

| Category | Added | Removed | Modified |
|----------|-------|---------|----------|
| Assets | 2 | 0 | 1 |
| Data Flows | 3 | 1 | 0 |
| Attack Surface | 2 | 0 | 1 |
| Trust Boundaries | 0 | 0 | 0 |
| Controls | 1 | 0 | 2 |

**Risk Impact**: New assets and attack surfaces require threat analysis.

---

## Asset Changes

### Added Assets

#### asset-015: Redis Cache
- **Type**: data-store
- **Classification**: internal
- **Added in**: commit abc123
- **Risk**: Cache poisoning, data exposure

#### asset-016: Email Service Integration
- **Type**: integration
- **Classification**: confidential
- **Added in**: commit def456
- **Risk**: Email injection, SSRF

### Modified Assets

#### asset-005: User Database
- **Change**: Classification upgraded from internal to restricted
- **Reason**: Now stores payment data
- **Impact**: Additional controls required

---

## Attack Surface Changes

### Added Entry Points

#### as-010: Cache Invalidation API
- **Asset**: asset-015
- **Exposure**: internal
- **Authentication**: none ⚠️
- **Risk**: Unauthenticated cache manipulation

#### as-011: Email Webhook Receiver
- **Asset**: asset-016
- **Exposure**: public
- **Authentication**: signature validation
- **Risk**: Webhook forgery

### Modified Entry Points

#### as-003: Admin API
- **Change**: New endpoints added
- **Endpoints**: /api/admin/cache, /api/admin/email
- **Risk**: Expanded attack surface

---

## Control Status Changes

### Degraded Controls

#### control-005: Input Validation
- **Previous**: implemented
- **Current**: partial
- **Reason**: New endpoints missing validation
- **Files Changed**: src/routes/admin.ts

### Improved Controls

#### control-012: Rate Limiting
- **Previous**: missing
- **Current**: implemented
- **Evidence**: src/middleware/rateLimiter.ts

---

## New Potential Threats

Based on changes, the following new threats should be analyzed:

1. **Cache Poisoning** (asset-015)
   - Unauthenticated cache invalidation
   - Data corruption via cache

2. **Email Header Injection** (asset-016)
   - Malicious email content
   - SSRF via email service

3. **Admin API Abuse** (as-003)
   - New endpoints may lack authorization

---

## Recommendations

1. **Immediate**: Add authentication to cache invalidation endpoint
2. **Immediate**: Run /tm-threats --focus asset-015,asset-016
3. **Short-term**: Review admin API authorization
4. **Short-term**: Update threat model with new components

---

## Baseline Created

New baseline: `.threatmodel/baseline/snapshot-20250120.json`

Instructions for Claude

When executing this skill:

  1. Load current state:

    • Read all files from .threatmodel/state/
  2. Load baseline:

    • If --baseline specified, use that file
    • Otherwise, find most recent in .threatmodel/baseline/
    • If no baseline exists, report and offer to create one
  3. Compare each category:

    • Assets: Compare by ID, check all properties
    • Data Flows: Compare by ID, check configuration
    • Attack Surface: Compare by ID, check endpoints
    • Trust Boundaries: Compare by ID, check scope
    • Controls: Compare by ID, check status
  4. Identify changes:

    • New items (in current, not in baseline)
    • Removed items (in baseline, not in current)
    • Modified items (in both, but different)
  5. Assess risk impact:

    • New assets may introduce threats
    • New attack surface expands exposure
    • Degraded controls increase risk
    • Removed flows may indicate architectural change
  6. Generate recommendations:

    • Run threat analysis on new components
    • Review authorization on modified surfaces
    • Investigate degraded controls
  7. Create baseline if requested:

    • Snapshot current state
    • Include metadata (timestamp, commit, author)
    • Save to baseline directory
  8. Report summary:

    Drift Detection Complete
    ========================
    
    Compared against: baseline/snapshot-20250115.json (5 days ago)
    
    Changes Detected:
      + 2 new assets
      + 3 new data flows
      + 2 new attack surface entries
      ~ 2 controls changed status
    
    Risk Impact: MEDIUM
      - New unauthenticated endpoint detected
      - Control degradation in admin routes
    
    New Potential Threats: 3
      - Cache poisoning
      - Email header injection
      - Admin API abuse
    
    Recommendations:
      1. Run /tm-threats --focus asset-015,asset-016
      2. Review authentication on as-010
      3. Update input validation for admin routes
    
    Files Created:
      .threatmodel/reports/drift-report.md
      .threatmodel/baseline/snapshot-20250120.json (new baseline)
    
    Next Steps:
      Address identified changes
      Re-run /tm-verify after fixes
    

Full Threat Modeling Workflow

Purpose

Orchestrate the complete threat modeling workflow in a single command:

  1. Initialize - Discover assets and architecture
  2. Analyze - Identify and assess threats
  3. Verify - Check control implementations
  4. Comply - Map to frameworks
  5. Report - Generate comprehensive documentation

Usage

/tm-full [--docs <path>] [--framework stride|pasta] [--compliance <list>] [--output <path>] [--report-level executive|standard|detailed]

Arguments:

  • --docs: Path to architecture documentation (default: ./docs)
  • --framework: Threat framework (default: stride)
  • --compliance: Compliance frameworks, comma-separated (default: owasp)
  • --output: Output directory (default: .threatmodel)
  • --report-level: Report detail level (default: standard)

Workflow Steps

┌─────────────────────────────────────────────────────────────┐
│                    FULL WORKFLOW                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  [1/5] INITIALIZATION                                       │
│  ─────────────────────                                      │
│  • Read architecture documentation                          │
│  • Extract assets and classify                              │
│  • Map data flows                                           │
│  • Identify trust boundaries                                │
│  • Catalog attack surface                                   │
│  • Generate architecture diagrams                           │
│                                                             │
│  Output: assets.json, dataflows.json, trust-boundaries.json │
│          attack-surface.json, diagrams/*.mmd                │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  [2/5] THREAT ANALYSIS                                      │
│  ─────────────────────                                      │
│  • Apply STRIDE to each component                           │
│  • Enumerate threats per attack surface                     │
│  • Build attack trees for critical threats                  │
│  • Assess likelihood and impact                             │
│  • Calculate risk scores                                    │
│  • Create risk register                                     │
│                                                             │
│  Output: threats.json, attack-trees.json, risk-register.json│
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  [3/5] CONTROL VERIFICATION                                 │
│  ─────────────────────────                                  │
│  • Identify required controls                               │
│  • Search codebase for implementations                      │
│  • Verify configurations                                    │
│  • Collect evidence                                         │
│  • Document gaps                                            │
│                                                             │
│  Output: controls.json, gaps.json, verification.json        │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  [4/5] COMPLIANCE MAPPING                                   │
│  ───────────────────────                                    │
│  • Map threats to framework requirements                    │
│  • Map controls to requirements                             │
│  • Calculate coverage percentages                           │
│  • Identify compliance gaps                                 │
│                                                             │
│  Output: compliance.json, compliance-report.md              │
│                                                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  [5/5] REPORT GENERATION                                    │
│  ───────────────────────                                    │
│  • Aggregate all findings                                   │
│  • Prioritize risks                                         │
│  • Generate countermeasures                                 │
│  • Create executive summary                                 │
│  • Compile detailed report                                  │
│  • Create baseline snapshot                                 │
│                                                             │
│  Output: risk-report.md, executive-summary.md,              │
│          baseline/snapshot-{date}.json                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Progress Display

═══════════════════════════════════════════════════════════════
            THREAT MODELING - FULL WORKFLOW
═══════════════════════════════════════════════════════════════

Project: My Application
Documentation: ./docs/architecture
Framework: STRIDE
Compliance: OWASP, SOC2

───────────────────────────────────────────────────────────────

[1/5] Initializing...
      ├── Scanning documentation...
      ├── Extracting assets... found 14
      ├── Mapping data flows... found 22
      ├── Identifying trust boundaries... found 5
      ├── Cataloging attack surface... found 12 entries
      └── Generating diagrams... done
      ✓ Initialization complete

[2/5] Analyzing threats...
      ├── Applying STRIDE framework...
      ├── Processing 14 assets...
      ├── Analyzing 8 trust boundary crossings...
      ├── Building attack trees for critical threats...
      └── Creating risk register...
      ✓ Threat analysis complete (47 threats identified)

[3/5] Verifying controls...
      ├── Identifying required controls... 29 needed
      ├── Searching codebase...
      ├── Verifying implementations...
      └── Documenting gaps...
      ✓ Verification complete (18 verified, 7 partial, 4 missing)

[4/5] Mapping compliance...
      ├── Mapping to OWASP Top 10...
      ├── Mapping to SOC2...
      └── Calculating coverage...
      ✓ Compliance mapping complete (OWASP: 82%, SOC2: 88%)

[5/5] Generating reports...
      ├── Aggregating findings...
      ├── Prioritizing risks...
      ├── Generating countermeasures...
      ├── Creating executive summary...
      ├── Compiling detailed report...
      └── Creating baseline snapshot...
      ✓ Reports generated

───────────────────────────────────────────────────────────────
                         SUMMARY
───────────────────────────────────────────────────────────────

Discovery:
  • 14 assets discovered
  • 22 data flows mapped
  • 5 trust boundaries identified
  • 12 attack surface entries cataloged

Threats:
  • 47 threats identified
  • 5 critical, 12 high, 18 medium, 12 low
  • 3 unmitigated critical threats

Controls:
  • 29 controls required
  • 62% fully implemented
  • 11 gaps identified (2 critical)

Compliance:
  • OWASP Top 10: 82%
  • SOC2: 88%

───────────────────────────────────────────────────────────────
                    CRITICAL FINDINGS
───────────────────────────────────────────────────────────────

1. [CRITICAL] Credential Stuffing Attack
   Risk: 8.5 | Target: Auth API | Gap: Rate limiting insufficient

2. [CRITICAL] SQL Injection in Legacy Module
   Risk: 8.2 | Target: Reports API | Gap: Queries not parameterized

3. [CRITICAL] JWT Token Theft via XSS
   Risk: 8.0 | Target: Session | Gap: HttpOnly not set

───────────────────────────────────────────────────────────────
                       FILES CREATED
───────────────────────────────────────────────────────────────

.threatmodel/
├── config.yaml
├── state/
│   ├── assets.json
│   ├── dataflows.json
│   ├── trust-boundaries.json
│   ├── attack-surface.json
│   ├── threats.json
│   ├── controls.json
│   ├── gaps.json
│   ├── risk-register.json
│   └── compliance.json
├── diagrams/
│   ├── architecture.mmd
│   ├── dataflow.mmd
│   └── trust-boundaries.mmd
├── reports/
│   ├── risk-report.md
│   ├── executive-summary.md
│   └── compliance-report.md
└── baseline/
    └── snapshot-20250120.json

───────────────────────────────────────────────────────────────
                      NEXT STEPS
───────────────────────────────────────────────────────────────

1. Review risk report: .threatmodel/reports/risk-report.md
2. Address critical findings immediately
3. Share executive summary with stakeholders
4. Create Jira tickets for gaps
5. Schedule follow-up assessment

═══════════════════════════════════════════════════════════════
                  THREAT MODEL COMPLETE
═══════════════════════════════════════════════════════════════

Error Handling

Documentation Not Found

[1/5] Initializing...
      └── ERROR: No documentation found at ./docs

Please specify documentation path:
  /tm-full --docs /path/to/architecture/docs

Or create documentation first.

Partial Failure

[3/5] Verifying controls...
      └── WARNING: Could not access codebase at ./src

Continuing with available information...
Control verification skipped.

To include verification:
  /tm-verify --thorough

Continuing to next step...

Instructions for Claude

When executing this skill:

  1. Parse arguments:

    • Extract --docs, --framework, --compliance, --output, --report-level
    • Use defaults for missing values
  2. Execute Step 1 - Initialize:

    • Follow /tm-init process
    • Display progress
    • Report findings
  3. Execute Step 2 - Threat Analysis:

    • Follow /tm-threats process
    • Use specified framework
    • Include abuse cases
    • Display progress
  4. Execute Step 3 - Verification:

    • Follow /tm-verify process
    • Use thorough mode
    • Collect evidence
    • Display progress
  5. Execute Step 4 - Compliance:

    • Follow /tm-compliance process
    • Map to specified frameworks
    • Display progress
  6. Execute Step 5 - Reporting:

    • Follow /tm-report process
    • Use specified detail level
    • Create baseline
    • Display progress
  7. Handle errors gracefully:

    • Continue if possible
    • Report what couldn't be completed
    • Suggest remediation
  8. Display final summary:

    • Key statistics
    • Critical findings
    • Files created
    • Next steps

Timing Guidance

The full workflow processes multiple phases. Between phases:

  • Display clear progress indicators
  • Show intermediate results
  • Allow for interruption if needed

Reference

This skill orchestrates:

Threat Model Initialization

Purpose

Initialize a comprehensive threat model by analyzing your system's architecture documentation. This skill discovers and catalogs:

  • Assets: Systems, data stores, services, and integrations
  • Data Flows: How data moves between components
  • Trust Boundaries: Where privilege levels change
  • Attack Surface: Entry points exposed to potential attackers

Usage

/tm-init [--docs <path>] [--scope <pattern>] [--framework stride|pasta]

Arguments (parsed from $ARGUMENTS):

  • --docs <path>: Path to architecture documentation (default: ./docs)
  • --scope <pattern>: Limit analysis to matching components
  • --framework: Threat framework to use (default: stride)

Process

Step 1: Discover Documentation

Scan the documentation directory for architecture artifacts:

Glob patterns to search:
- **/*.md (Markdown documentation)
- **/README* (Project readmes)
- **/openapi.yaml, **/openapi.json (API specs)
- **/swagger.* (Swagger specs)
- **/*.mmd, **/*.puml (Diagrams)
- **/docker-compose.* (Infrastructure)
- **/Dockerfile* (Containerization)
- **/*.tf (Terraform)
- **/k8s/**, **/kubernetes/** (Kubernetes)

Step 2: Extract Assets

For each component found, identify and classify:

Asset Types:

TypeDescriptionLook For
data-storePersists dataPostgreSQL, MySQL, MongoDB, Redis, S3, etc.
serviceBackend logicAPI servers, microservices, workers
clientUser interfacesWeb apps, mobile apps, CLIs
integrationExternal systemsPayment gateways, email services, third-party APIs
infrastructurePlatform componentsLoad balancers, CDN, DNS, queues
identityAuth systemsIdP, OAuth providers, SSO
secretSensitive materialAPI keys, certificates, credentials

Data Classifications:

  • public: Publicly available information
  • internal: Internal business data
  • confidential: Sensitive business data
  • restricted: PII, PHI, financial data, credentials

Step 3: Map Data Flows

Identify how data moves between components:

  • Source and destination assets
  • Data types being transmitted
  • Protocol (HTTP, HTTPS, gRPC, WebSocket, etc.)
  • Authentication method
  • Encryption status
  • Whether it crosses a trust boundary

Step 4: Define Trust Boundaries

Identify where security context changes:

Trust Boundary Types:

  • network: Public/DMZ/Internal network segmentation
  • process: Process/container isolation
  • privilege: User/admin/system privilege changes
  • environment: Dev/staging/prod boundaries
  • organizational: Third-party/vendor boundaries
  • data-classification: Sensitivity level changes

Step 5: Catalog Attack Surface

Document all entry points:

Attack Surface Types:

  • api: REST, GraphQL, gRPC endpoints
  • web-ui: Web application interfaces
  • mobile: Mobile application entry points
  • cli: Command-line interfaces
  • admin: Administrative interfaces
  • integration: Webhooks, callbacks
  • file-upload: File upload functionality
  • message-queue: Message queue consumers

Step 6: Generate Diagrams

Create Mermaid diagrams for visualization.

Output Structure

Create the following directory structure:

.threatmodel/
├── config.yaml
├── state/
│   ├── assets.json
│   ├── dataflows.json
│   ├── trust-boundaries.json
│   ├── attack-surface.json
│   └── sequences.json
├── diagrams/
│   ├── architecture.mmd
│   ├── dataflow.mmd
│   └── trust-boundaries.mmd
├── reports/
├── baseline/
└── policies/

Config File Template

Create .threatmodel/config.yaml:

project:
  name: "[Project Name]"
  version: "1.0.0"
  description: "[Description]"

analysis:
  framework: "stride"
  depth: "standard"

documentation:
  paths:
    - "./docs"
  patterns:
    - "**/*.md"
    - "**/openapi.yaml"

verification:
  code_paths:
    - "./src"
  exclude_paths:
    - "./node_modules"
    - "./**/*.test.*"

compliance:
  frameworks:
    - owasp

JSON Output Format

assets.json

{
  "version": "1.0",
  "generated": "ISO-8601 timestamp",
  "assets": [
    {
      "id": "asset-001",
      "name": "User Database",
      "type": "data-store",
      "classification": "restricted",
      "description": "PostgreSQL database storing user data",
      "owner": "platform-team",
      "data_types": ["pii", "credentials"],
      "code_references": ["src/db/connection.ts"]
    }
  ]
}

dataflows.json

{
  "version": "1.0",
  "generated": "ISO-8601 timestamp",
  "dataflows": [
    {
      "id": "flow-001",
      "name": "User Login",
      "source": {"asset_id": "asset-001", "component": "LoginPage"},
      "destination": {"asset_id": "asset-002", "component": "AuthService"},
      "data_types": ["credentials"],
      "protocol": "HTTPS",
      "encryption": {"in_transit": true},
      "crosses_trust_boundary": true,
      "trust_boundary_id": "tb-001"
    }
  ]
}

Instructions for Claude

When executing this skill:

  1. Ask for documentation path if not provided in arguments

  2. Explore the documentation:

    • Use Glob to find all relevant files
    • Read architecture docs, README files, API specs
    • Look for existing diagrams or system descriptions
  3. Build understanding of the system:

    • List all named components
    • Understand how they connect
    • Note external dependencies
    • Identify where data enters/exits
  4. Create the threat model structure:

    • Create .threatmodel/ directory
    • Write config.yaml with project info
    • Write each state file with discovered data
    • Generate Mermaid diagrams
  5. Validate completeness:

    • Every asset should have at least one data flow
    • Every external-facing component should be in attack surface
    • Trust boundaries should be identified
  6. Write visual discovery report (.threatmodel/reports/discovery-report.md):

    # Discovery Report
    
    **Project**: [Name]
    **Generated**: [Date]
    
    ## System Overview
    
    

    DISCOVERY SUMMARY ═══════════════════════════════════════════════════════════

    ASSETS DISCOVERED: 14 ───────────────────────────────────────────────────────── Services │████████████████░░░░░░░░░░░░░░░░░░░░░░░░│ 4 Data Stores │████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 3 Clients │████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 2 Integrations │████████████████████░░░░░░░░░░░░░░░░░░░░│ 5

    DATA FLOWS: 22 (8 cross trust boundaries) TRUST BOUNDARIES: 5 ATTACK SURFACE ENTRIES: 12

    
    ## Assets by Classification
    
    | Asset | Type | Classification |
    |-------|------|----------------|
    | User Database | data-store | Restricted |
    | API Gateway | service | Internal |
    ...
    
  7. Console summary (also display to user):

    Threat Model Initialized
    ========================
    
    Project: [Name]
    Framework: STRIDE
    
    Discovered:
      - X assets (breakdown by type)
      - Y data flows (Z cross trust boundaries)
      - N trust boundaries
      - M attack surface entries
    
    Created:
      .threatmodel/config.yaml
      .threatmodel/state/assets.json
      .threatmodel/state/dataflows.json
      .threatmodel/state/trust-boundaries.json
      .threatmodel/state/attack-surface.json
      .threatmodel/reports/discovery-report.md
      .threatmodel/diagrams/architecture.mmd
      .threatmodel/diagrams/dataflow.mmd
    
    Next Steps:
      Run /tm-threats to analyze threats
    

Reference Files

Risk Report Generation

Purpose

Generate comprehensive risk reports that:

  • Prioritize risks by severity and business impact
  • Provide actionable countermeasures
  • Include executive summaries for leadership
  • Document evidence for audit compliance

Usage

/tm-report [--format markdown|html|json] [--level executive|standard|detailed] [--output <path>]

Arguments:

  • --format: Output format (default: markdown)
  • --level: Detail level (default: standard)
  • --output: Custom output path

Report Sections

Executive Summary

  • High-level risk overview
  • Critical findings count
  • Compliance status
  • Top 3-5 recommendations

Risk Overview

  • Risk distribution by severity
  • Risk heat map
  • Trend indicators (if baseline exists)

Critical Findings

  • Detailed threat descriptions
  • Attack scenarios
  • Business impact
  • Recommended countermeasures

Gap Analysis

  • Missing controls
  • Partial implementations
  • Remediation priorities

Compliance Status

  • Framework coverage percentages
  • Key compliance gaps

Recommendations

  • Prioritized action items
  • Effort estimates
  • Quick wins vs strategic improvements

Technical Appendix

  • Full threat catalog
  • Control inventory
  • Architecture diagrams

Report Templates

Executive Level

# Security Risk Report - Executive Summary

**Project**: [Name]
**Date**: [Date]
**Classification**: Confidential

## Overview

This assessment identified [X] security risks across [Y] system components.
[N] risks are rated as **critical** and require immediate attention.

## Key Findings

| Finding | Risk Level | Business Impact |
|---------|------------|-----------------|
| [Title] | Critical | [Impact] |
| [Title] | High | [Impact] |
| [Title] | High | [Impact] |

## Compliance Status

- OWASP Top 10: [X]%
- SOC2: [Y]%

## Recommendations

1. **Immediate** (0-30 days): [Action]
2. **Short-term** (30-90 days): [Action]
3. **Strategic** (90+ days): [Action]

## Resource Requirements

[Brief estimate of resources needed]

Standard Level

# Threat Model Risk Report

**Project**: [Name]
**Version**: [Version]
**Generated**: [Date]
**Framework**: STRIDE

---

## Executive Summary

[2-3 paragraphs summarizing findings]

## Risk Overview

### At a Glance

RISK POSTURE: [LEVEL] ═══════════════════════════════════════════════════════════

Threats: 47 identified Controls: 29 analyzed Gaps: 11 found

SEVERITY DISTRIBUTION ───────────────────────────────────────────────────────── CRITICAL │██████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 5 HIGH │████████████████████████░░░░░░░░░░░░░░░░│ 12 MEDIUM │████████████████████████████████████░░░░│ 18 LOW │████████████████████████░░░░░░░░░░░░░░░░│ 12

CONTROL STATUS ───────────────────────────────────────────────────────── ✓ Verified: 18 controls ⚠ Partial: 7 controls ✗ Missing: 4 controls

COMPLIANCE ───────────────────────────────────────────────────────── OWASP Top 10: ████████░░ 82% SOC2: █████████░ 88%


### Risk Distribution Table

| Severity | Count | Mitigated | Unmitigated |
|----------|-------|-----------|-------------|
| Critical | X | Y | Z |
| High | X | Y | Z |
| Medium | X | Y | Z |
| Low | X | Y | Z |

---

## Critical Findings

### THREAT-001: [Title]

**Risk Score**: X/25 (Critical)
**Category**: [STRIDE category]
**Target**: [Component]

#### Description
[Detailed description of the threat]

#### Attack Scenario
1. [Step 1]
2. [Step 2]
3. [Step 3]

#### Business Impact
- **Confidentiality**: [Impact]
- **Integrity**: [Impact]
- **Availability**: [Impact]

#### Current Controls
| Control | Status | Effectiveness |
|---------|--------|---------------|
| [Name] | [Status] | [%] |

#### Gaps
- [Gap description]

#### Recommended Countermeasures
1. **[Priority]**: [Recommendation]
   - Effort: [Low/Medium/High]
   - Implementation: [Details]

---

## Gap Analysis

### Critical Gaps

#### GAP-001: [Title]

**Severity**: [Level]
**Control**: [Control ID]

**Expected**: [What should exist]
**Actual**: [What was found]

**Remediation**:
[Recommendation]

---

## Compliance Status

### OWASP Top 10 2021

| Requirement | Coverage | Gaps |
|-------------|----------|------|
| A01 | X% | N |
| ... | | |

---

## Recommendations

### Immediate Actions (0-30 days)

1. [Action with details]

### Short-term Improvements (30-90 days)

1. [Action with details]

### Strategic Initiatives (90+ days)

1. [Action with details]

---

## Appendix A: Threat Catalog

[Full list of threats]

## Appendix B: Control Inventory

[Full list of controls]

## Appendix C: Architecture Diagrams

[Mermaid diagrams]

Output Files

  • .threatmodel/reports/risk-report.md
  • .threatmodel/reports/executive-summary.md
  • .threatmodel/reports/risk-report.json (if JSON format)

Instructions for Claude

When executing this skill:

  1. Load all threat model state:

    • Read all files from .threatmodel/state/
    • Read diagrams from .threatmodel/diagrams/
  2. Aggregate and analyze:

    • Count threats by severity
    • Count controls by status
    • Count gaps by priority
    • Calculate compliance percentages
  3. Prioritize findings:

    • Sort threats by risk score
    • Identify top critical findings
    • Group recommendations by urgency
  4. Generate report sections:

    • Write executive summary first
    • Detail critical findings
    • Document gaps
    • Provide recommendations
  5. Include visualizations IN THE REPORT FILES (not just console):

    • Use ASCII progress bars: ████████░░ 82%
    • Use status indicators: ✓, ⚠, ✗
    • Use box-drawing characters for visual separation
    • Include Mermaid diagrams for architecture
    • The "At a Glance" section with visual bars MUST be in the written report file
  6. Write report files:

    • Create reports directory if needed
    • Write main report
    • Write executive summary separately
  7. Report summary:

    Report Generated
    ================
    
    Reports Created:
      .threatmodel/reports/risk-report.md
      .threatmodel/reports/executive-summary.md
    
    Report Contents:
      - Executive Summary
      - X Critical Findings detailed
      - Y Gaps documented
      - Z Recommendations provided
      - Compliance status for N frameworks
      - Full appendices
    
    Report Statistics:
      Total Threats: X
      Total Controls: Y
      Total Gaps: Z
      Overall Risk Level: [Level]
    
    The report is ready for review.
    

Threat Model Status

Purpose

Display a comprehensive overview of the current threat model state:

  • Asset and component counts
  • Threat distribution by severity
  • Control verification status
  • Gap summary
  • Compliance coverage
  • Baseline comparison

Usage

/tm-status [--format text|json] [--section <name>]

Arguments:

  • --format: Output format (default: text)
  • --section: Show specific section only (discovery, threats, controls, compliance)

Status Sections

Discovery Summary

  • Total assets by type
  • Total data flows
  • Trust boundaries defined
  • Attack surface entries

Threat Summary

  • Total threats
  • Distribution by severity
  • Distribution by STRIDE category
  • Unmitigated threats count

Control Summary

  • Total required controls
  • Implemented vs partial vs missing
  • Verification status
  • Recent changes

Gap Summary

  • Total gaps
  • Distribution by severity
  • Top priority gaps

Compliance Summary

  • Coverage by framework
  • Critical compliance gaps

Baseline Comparison

  • Days since last baseline
  • Changes since baseline

Output Format

Text Output

═══════════════════════════════════════════════════════════════
                    THREAT MODEL STATUS
═══════════════════════════════════════════════════════════════

Project: My Application v1.0.0
Framework: STRIDE
Last Updated: 2025-01-20 14:30:00
Baseline: 2025-01-15 (5 days ago)

───────────────────────────────────────────────────────────────
                       DISCOVERY
───────────────────────────────────────────────────────────────

Assets: 14 total
  ├── Data Stores:    3  ████████████░░░░░░░░  21%
  ├── Services:       6  ████████████████████░  43%
  ├── Clients:        3  ████████████░░░░░░░░  21%
  └── Integrations:   2  ████████░░░░░░░░░░░░  14%

Data Flows: 22 total
  └── Crossing trust boundaries: 8 (36%)

Trust Boundaries: 5
  ├── Network:     2
  ├── Privilege:   2
  └── Environment: 1

Attack Surface: 12 entries
  ├── Public:     5  ████████████████░░░░  42%
  ├── Internal:   5  ████████████████░░░░  42%
  └── Restricted: 2  ██████░░░░░░░░░░░░░░  17%

───────────────────────────────────────────────────────────────
                        THREATS
───────────────────────────────────────────────────────────────

Total: 47 threats

By Severity:
  ├── Critical:  5  ██████░░░░░░░░░░░░░░  11%
  ├── High:     12  ████████████░░░░░░░░  26%
  ├── Medium:   18  ██████████████████░░  38%
  └── Low:      12  ████████████░░░░░░░░  26%

By STRIDE Category:
  ├── Spoofing:              8
  ├── Tampering:            10
  ├── Repudiation:           4
  ├── Information Disclosure: 9
  ├── Denial of Service:     7
  └── Elevation of Privilege: 9

Unmitigated Critical Threats: 3
  1. THREAT-001: Credential Stuffing (8.5)
  2. THREAT-002: SQL Injection (8.2)
  3. THREAT-003: JWT Token Theft (8.0)

───────────────────────────────────────────────────────────────
                       CONTROLS
───────────────────────────────────────────────────────────────

Total Required: 29

Implementation Status:
  ├── Implemented: 18  ████████████████████░  62%
  ├── Partial:      7  ████████░░░░░░░░░░░░  24%
  └── Missing:      4  █████░░░░░░░░░░░░░░░  14%

Verification Status:
  ├── Verified:   18  ████████████████████░  62%
  ├── Unverified:  7  ████████░░░░░░░░░░░░  24%
  └── Failed:      4  █████░░░░░░░░░░░░░░░  14%

───────────────────────────────────────────────────────────────
                         GAPS
───────────────────────────────────────────────────────────────

Total: 11 gaps

By Severity:
  ├── Critical: 2  ████░░░░░░░░░░░░░░░░  18%
  ├── High:     4  ████████░░░░░░░░░░░░  36%
  ├── Medium:   3  ██████░░░░░░░░░░░░░░  27%
  └── Low:      2  ████░░░░░░░░░░░░░░░░  18%

Top Priority Gaps:
  1. [CRITICAL] GAP-001: MFA not enforced
  2. [CRITICAL] GAP-002: SQL injection in legacy
  3. [HIGH] GAP-003: Rate limiting missing
  4. [HIGH] GAP-004: Session fixation

───────────────────────────────────────────────────────────────
                      COMPLIANCE
───────────────────────────────────────────────────────────────

OWASP Top 10 2021:
  Overall: 82%
  ├── A01 Access Control:    85%  █████████░░░
  ├── A02 Crypto Failures:  100%  ████████████
  ├── A03 Injection:         70%  ████████░░░░
  ├── A04 Insecure Design:   55%  ██████░░░░░░
  └── ...

SOC2:
  Overall: 88%
  ├── CC6.1 Access:          90%  ███████████░
  ├── CC6.2 Auth:            80%  ██████████░░
  └── ...

───────────────────────────────────────────────────────────────
                     RECOMMENDATIONS
───────────────────────────────────────────────────────────────

Immediate Actions:
  1. [CRITICAL] Implement MFA enforcement
  2. [CRITICAL] Fix SQL injection in legacy module
  3. [HIGH] Add rate limiting to password reset
  4. [HIGH] Fix session fixation vulnerability

───────────────────────────────────────────────────────────────
                      QUICK ACTIONS
───────────────────────────────────────────────────────────────

/tm-threats --focus asset-015    Analyze new assets
/tm-verify --thorough            Deep verification
/tm-report                       Generate full report
/tm-drift --create-baseline      Create new baseline

═══════════════════════════════════════════════════════════════

JSON Output

{
  "project": {
    "name": "My Application",
    "version": "1.0.0",
    "framework": "STRIDE",
    "last_updated": "2025-01-20T14:30:00Z"
  },
  "discovery": {
    "assets": {
      "total": 14,
      "by_type": {
        "data-store": 3,
        "service": 6,
        "client": 3,
        "integration": 2
      }
    },
    "dataflows": {
      "total": 22,
      "crossing_boundaries": 8
    },
    "trust_boundaries": 5,
    "attack_surface": {
      "total": 12,
      "by_exposure": {
        "public": 5,
        "internal": 5,
        "restricted": 2
      }
    }
  },
  "threats": {
    "total": 47,
    "by_severity": {
      "critical": 5,
      "high": 12,
      "medium": 18,
      "low": 12
    },
    "by_category": {
      "spoofing": 8,
      "tampering": 10,
      "repudiation": 4,
      "information-disclosure": 9,
      "denial-of-service": 7,
      "elevation-of-privilege": 9
    },
    "unmitigated_critical": 3
  },
  "controls": {
    "total": 29,
    "by_status": {
      "implemented": 18,
      "partial": 7,
      "missing": 4
    },
    "verification": {
      "verified": 18,
      "unverified": 7,
      "failed": 4
    }
  },
  "gaps": {
    "total": 11,
    "by_severity": {
      "critical": 2,
      "high": 4,
      "medium": 3,
      "low": 2
    }
  },
  "compliance": {
    "owasp": {
      "overall": 82,
      "gaps": 5
    },
    "soc2": {
      "overall": 88,
      "gaps": 3
    }
  },
  "baseline": {
    "date": "2025-01-15",
    "days_ago": 5,
    "changes_since": {
      "assets_added": 2,
      "threats_added": 5,
      "controls_changed": 2
    }
  }
}

Instructions for Claude

When executing this skill:

  1. Check for threat model:

    • Look for .threatmodel/ directory
    • If not found, report and suggest /tm-init
  2. Load all state files:

    • Read assets.json, dataflows.json, etc.
    • Read config.yaml for project info
    • Check for baseline files
  3. Calculate statistics:

    • Count items in each category
    • Calculate percentages
    • Identify top items
  4. Format output:

    • Use box drawing characters for text
    • Include progress bars for percentages
    • Highlight critical items
  5. Provide recommendations:

    • Based on current state
    • Suggest next actions
  6. Display status:

    [Display formatted status output as shown above]
    

Edge Cases

No Threat Model

═══════════════════════════════════════════════════════════════
                    THREAT MODEL STATUS
═══════════════════════════════════════════════════════════════

No threat model found in current directory.

───────────────────────────────────────────────────────────────
                     GETTING STARTED
───────────────────────────────────────────────────────────────

OPTION 1: Run everything at once (recommended)

  /tm-full --docs ./path/to/docs

OPTION 2: Run step by step

  1. /tm-init --docs ./path/to/docs    Initialize & discover assets
  2. /tm-threats                        Analyze threats (STRIDE)
  3. /tm-verify                         Check controls in code
  4. /tm-compliance --framework owasp   Map to compliance frameworks
  5. /tm-report                         Generate reports

───────────────────────────────────────────────────────────────
                     WHAT IS --docs?
───────────────────────────────────────────────────────────────

Point --docs to a folder containing your architecture documentation:

  - README.md with system overview
  - Architecture diagrams or descriptions
  - API specifications (OpenAPI, GraphQL schemas)
  - Infrastructure-as-code (Terraform, CloudFormation)
  - Database schemas
  - Any markdown files describing your system

Examples:
  /tm-init --docs ./docs
  /tm-init --docs ./architecture
  /tm-init --docs ./design

The toolkit will read these files to understand your system
and automatically discover assets, data flows, and trust boundaries.

═══════════════════════════════════════════════════════════════

Partial State

═══════════════════════════════════════════════════════════════
                    THREAT MODEL STATUS
═══════════════════════════════════════════════════════════════

Warning: Incomplete threat model

───────────────────────────────────────────────────────────────
                        COMPLETED
───────────────────────────────────────────────────────────────
  ✓ assets.json: 14 assets
  ✓ dataflows.json: 22 flows

───────────────────────────────────────────────────────────────
                      NOT YET RUN
───────────────────────────────────────────────────────────────
  ✗ threats.json     → Run /tm-threats
  ✗ controls.json    → Run /tm-verify
  ✗ compliance.json  → Run /tm-compliance

───────────────────────────────────────────────────────────────
                       NEXT STEP
───────────────────────────────────────────────────────────────

Run the next phase:
  /tm-threats

Or run everything remaining:
  /tm-full --continue

═══════════════════════════════════════════════════════════════

Security Test Generation

Purpose

Generate security test cases from your threat model to:

  • Create attack scenario tests for each threat
  • Generate control verification tests
  • Build security regression test suites
  • Map test coverage to threats and controls

Usage

/tm-tests [--format markdown|jest|pytest|playwright] [--category <name>] [--control <id>] [--output <path>]

Arguments:

  • --format: Test output format (default: markdown)
  • --category: Filter by threat category
  • --control: Generate tests for specific control
  • --output: Output directory

Test Categories

Attack Tests (Negative Tests)

Tests that attempt to exploit vulnerabilities:

  • Verify threat is blocked/detected
  • Simulate attack scenarios
  • Test security boundaries

Control Tests (Positive Tests)

Tests that verify security controls work:

  • Verify control is active
  • Test expected behavior
  • Validate configuration

Regression Tests

Tests that prevent security regressions:

  • Run on every commit/PR
  • Verify fixes remain in place
  • Detect control degradation

Test Output Formats

Markdown Documentation

# Security Test Cases

## Authentication Tests

### TEST-001: Credential Stuffing Prevention

**Threat**: THREAT-001 - Credential Stuffing Attack
**Control**: CONTROL-001 - Rate Limiting

#### Test Scenario
1. Attempt 6 failed logins from same IP within 1 minute
2. Expected: 6th request should be blocked (429 Too Many Requests)

#### Steps
1. POST /api/auth/login with invalid credentials
2. Repeat 5 more times
3. Verify 6th request returns 429

#### Expected Results
- First 5 requests: 401 Unauthorized
- 6th request: 429 Too Many Requests
- Response includes retry-after header

#### Pass Criteria
- Rate limit enforced at configured threshold
- Appropriate error response returned
- Event logged for security monitoring

Jest/TypeScript

// security-tests/auth-security.test.ts

describe('Authentication Security', () => {
  describe('Credential Stuffing Prevention', () => {
    // THREAT-001: Credential Stuffing Attack
    // CONTROL-001: Rate Limiting

    it('should block after 5 failed attempts from same IP', async () => {
      const loginAttempt = () =>
        request(app)
          .post('/api/auth/login')
          .send({ email: 'test@example.com', password: 'wrong' });

      // Make 5 failed attempts
      for (let i = 0; i < 5; i++) {
        const response = await loginAttempt();
        expect(response.status).toBe(401);
      }

      // 6th attempt should be blocked
      const blocked = await loginAttempt();
      expect(blocked.status).toBe(429);
      expect(blocked.headers['retry-after']).toBeDefined();
    });

    it('should return consistent error messages', async () => {
      // Test with valid email, wrong password
      const validEmail = await request(app)
        .post('/api/auth/login')
        .send({ email: 'existing@example.com', password: 'wrong' });

      // Test with invalid email
      const invalidEmail = await request(app)
        .post('/api/auth/login')
        .send({ email: 'nonexistent@example.com', password: 'wrong' });

      // Messages should be identical to prevent enumeration
      expect(validEmail.body.message).toBe(invalidEmail.body.message);
    });

    it('should log failed authentication attempts', async () => {
      const spy = jest.spyOn(logger, 'warn');

      await request(app)
        .post('/api/auth/login')
        .send({ email: 'test@example.com', password: 'wrong' });

      expect(spy).toHaveBeenCalledWith(
        expect.objectContaining({
          event: 'authentication_failure',
          email: 'test@example.com',
        })
      );
    });
  });

  describe('Session Management', () => {
    // THREAT-003: Session Hijacking
    // CONTROL-003: Secure Session Configuration

    it('should invalidate session on password change', async () => {
      const { sessionId } = await login('user@example.com', 'password');

      await changePassword('user@example.com', 'newpassword');

      const response = await request(app)
        .get('/api/profile')
        .set('Cookie', `session=${sessionId}`);

      expect(response.status).toBe(401);
    });

    it('should enforce session timeout', async () => {
      const { sessionId } = await login('user@example.com', 'password');

      // Fast-forward time past session timeout
      jest.advanceTimersByTime(31 * 60 * 1000); // 31 minutes

      const response = await request(app)
        .get('/api/profile')
        .set('Cookie', `session=${sessionId}`);

      expect(response.status).toBe(401);
    });
  });
});

Pytest

# tests/security/test_auth_security.py

import pytest
from fastapi.testclient import TestClient

class TestAuthenticationSecurity:
    """
    Security tests for authentication threats.
    """

    class TestCredentialStuffingPrevention:
        """
        THREAT-001: Credential Stuffing Attack
        CONTROL-001: Rate Limiting
        """

        def test_blocks_after_failed_attempts(self, client: TestClient):
            """Should block after 5 failed login attempts from same IP."""
            for i in range(5):
                response = client.post(
                    "/api/auth/login",
                    json={"email": "test@example.com", "password": "wrong"}
                )
                assert response.status_code == 401

            # 6th attempt should be blocked
            response = client.post(
                "/api/auth/login",
                json={"email": "test@example.com", "password": "wrong"}
            )
            assert response.status_code == 429
            assert "retry-after" in response.headers

        def test_returns_consistent_error_messages(self, client: TestClient):
            """Should return identical messages for valid/invalid emails."""
            valid_email = client.post(
                "/api/auth/login",
                json={"email": "existing@example.com", "password": "wrong"}
            )
            invalid_email = client.post(
                "/api/auth/login",
                json={"email": "nonexistent@example.com", "password": "wrong"}
            )

            assert valid_email.json()["message"] == invalid_email.json()["message"]


    class TestInputValidation:
        """
        THREAT-002: SQL Injection
        CONTROL-002: Parameterized Queries
        """

        @pytest.mark.parametrize("payload", [
            "' OR '1'='1",
            "'; DROP TABLE users; --",
            "' UNION SELECT * FROM users --",
        ])
        def test_sql_injection_blocked(self, client: TestClient, payload: str):
            """Should block SQL injection attempts."""
            response = client.get(f"/api/users?search={payload}")
            assert response.status_code in [400, 200]
            # If 200, verify no SQL error in response
            if response.status_code == 200:
                assert "sql" not in response.text.lower()
                assert "error" not in response.text.lower()

Test Matrix

test-matrix.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "coverage": {
    "threats_with_tests": 42,
    "threats_without_tests": 5,
    "controls_with_tests": 25,
    "controls_without_tests": 4
  },
  "matrix": [
    {
      "threat_id": "threat-001",
      "threat_title": "Credential Stuffing",
      "test_ids": ["test-001", "test-002", "test-003"],
      "controls_tested": ["control-001", "control-002"],
      "coverage": "full"
    }
  ],
  "untested": {
    "threats": ["threat-045", "threat-046"],
    "controls": ["control-028"]
  }
}

Instructions for Claude

When executing this skill:

  1. Load threat model:

    • Read .threatmodel/state/threats.json
    • Read .threatmodel/state/controls.json
  2. Group tests by category:

    • Authentication tests
    • Authorization tests
    • Input validation tests
    • Cryptography tests
    • Session management tests
    • Error handling tests
  3. For each threat:

    • Create attack scenario test
    • Describe test steps
    • Define expected results
    • Link to mitigating controls
  4. For each control:

    • Create verification test
    • Test both positive and negative cases
    • Validate configuration
  5. Generate in requested format:

    • Markdown for documentation
    • Jest/Pytest for automation
    • Include proper test structure
  6. Create coverage matrix:

    • Map tests to threats
    • Map tests to controls
    • Identify gaps
  7. Report summary:

    Test Generation Complete
    ========================
    
    Format: jest
    
    Tests Generated:
      Authentication: 12 tests
      Authorization: 8 tests
      Input Validation: 15 tests
      Session Management: 6 tests
      Error Handling: 4 tests
      Total: 45 tests
    
    Coverage:
      Threats with tests: 42/47 (89%)
      Controls with tests: 25/29 (86%)
    
    Untested:
      - THREAT-045: Complex attack scenario
      - THREAT-046: Requires manual testing
      - CONTROL-028: Infrastructure control
    
    Files Created:
      .threatmodel/tests/auth-security.test.ts
      .threatmodel/tests/authz-security.test.ts
      .threatmodel/tests/input-validation.test.ts
      .threatmodel/tests/test-matrix.json
    
    Next Steps:
      1. Review generated tests
      2. Add to CI/CD pipeline
      3. Create manual test procedures for untested items
    

Threat Analysis

Purpose

Systematically identify and analyze threats against your system using established threat modeling frameworks. This skill:

  • Applies STRIDE methodology to each component
  • Generates comprehensive threat catalog
  • Builds attack trees for critical threats
  • Identifies abuse cases from legitimate functionality
  • Creates prioritized risk register

Usage

/tm-threats [--framework stride|pasta] [--focus <asset-id>] [--depth quick|standard|deep] [--include-abuse]

Arguments:

  • --framework: Threat framework (default: stride)
  • --focus: Analyze specific asset only
  • --depth: Analysis depth
  • --include-abuse: Generate abuse cases from sequences

Prerequisites

Requires initialized threat model. Run /tm-init first if .threatmodel/ doesn't exist.

STRIDE Analysis Process

For Each Asset

Apply STRIDE categories based on asset type:

Asset TypeSTRIDE
External Entity✓✓
Process/Service✓✓✓✓✓✓
Data Store✓✓✓✓
Data Flow✓✓✓

For Each Trust Boundary Crossing

Analyze threats for data flows crossing trust boundaries:

  1. Spoofing: Can the source be impersonated?
  2. Tampering: Can the data be modified in transit?
  3. Repudiation: Can the action be denied?
  4. Information Disclosure: Can the data be intercepted?
  5. Denial of Service: Can the flow be disrupted?
  6. Elevation of Privilege: Can privileges be escalated?

For Each Attack Surface Entry

Analyze exposed entry points:

  1. What authentication is required?
  2. What authorization is enforced?
  3. What input validation exists?
  4. What rate limiting is applied?
  5. What data is exposed?

Risk Scoring

Likelihood Scale (1-5)

ScoreLevelDescription
1RareRequires significant resources, unlikely to occur
2UnlikelyDifficult but possible with moderate resources
3PossibleAchievable with common tools and moderate skill
4LikelyEasy to exploit with readily available tools
5Almost CertainTrivial to exploit, may already be happening

Impact Scale (1-5)

ScoreLevelDescription
1NegligibleMinor inconvenience, no data loss
2MinorLimited data exposure, quick recovery
3ModerateSignificant data exposure, business disruption
4MajorLarge scale data breach, major business impact
5SevereComplete system compromise, existential threat

Risk Score = Likelihood × Impact

Risk ScoreLevel
1-4Low
5-9Medium
10-15High
16-25Critical

Output Files

threats.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "framework": "STRIDE",
  "threats": [
    {
      "id": "threat-001",
      "title": "Credential Stuffing Attack",
      "category": "spoofing",
      "framework": "STRIDE",
      "description": "Attacker uses leaked credentials to gain unauthorized access",
      "target": {
        "asset_id": "asset-002",
        "attack_surface_id": "as-001",
        "entry_point": "/api/auth/login"
      },
      "threat_actor": "external-attacker",
      "prerequisites": ["Leaked credential database", "Knowledge of login endpoint"],
      "impact": {
        "confidentiality": "high",
        "integrity": "medium",
        "availability": "low"
      },
      "likelihood": "likely",
      "risk_score": 16,
      "risk_level": "critical",
      "mitre_attack": ["T1110.004"],
      "cwe": ["CWE-307", "CWE-521"],
      "countermeasures": ["control-001", "control-002"]
    }
  ]
}

attack-trees.json

{
  "version": "1.0",
  "trees": [
    {
      "id": "at-001",
      "threat_id": "threat-001",
      "goal": "Gain unauthorized access to user accounts",
      "root": {
        "description": "Compromise user account",
        "type": "or",
        "children": [
          {
            "description": "Credential stuffing",
            "type": "and",
            "children": [
              {"description": "Obtain leaked credentials", "type": "leaf", "difficulty": "low"},
              {"description": "Bypass rate limiting", "type": "leaf", "difficulty": "medium"}
            ]
          },
          {"description": "Phishing attack", "type": "leaf", "difficulty": "medium"}
        ]
      }
    }
  ]
}

risk-register.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "entries": [
    {
      "id": "risk-001",
      "threat_id": "threat-001",
      "title": "Credential Stuffing Attack",
      "category": "authentication",
      "likelihood": {"score": 4, "rationale": "Common attack, tools readily available"},
      "impact": {"score": 4, "rationale": "Account takeover leads to data breach"},
      "inherent_risk_score": 16,
      "inherent_risk_level": "critical",
      "treatment": "mitigate",
      "treatment_plan": "Implement MFA and improve rate limiting",
      "owner": "security-team",
      "status": "open"
    }
  ]
}

Common Threat Patterns

Authentication Threats (Spoofing)

  • Credential stuffing
  • Brute force attacks
  • Session hijacking
  • Token theft
  • Password spraying

Data Integrity Threats (Tampering)

  • SQL injection
  • Parameter tampering
  • Man-in-the-middle
  • File upload attacks
  • Configuration tampering

Audit Threats (Repudiation)

  • Missing audit logs
  • Log tampering
  • Insufficient logging

Confidentiality Threats (Information Disclosure)

  • Data leaks in errors
  • Directory traversal
  • Insecure direct object references
  • Excessive data exposure

Availability Threats (Denial of Service)

  • Resource exhaustion
  • Algorithmic complexity
  • DDoS attacks

Authorization Threats (Elevation of Privilege)

  • Broken access control
  • Privilege escalation
  • IDOR vulnerabilities

Instructions for Claude

When executing this skill:

  1. Load existing threat model state:

    • Read .threatmodel/state/assets.json
    • Read .threatmodel/state/dataflows.json
    • Read .threatmodel/state/trust-boundaries.json
    • Read .threatmodel/state/attack-surface.json
  2. Apply STRIDE systematically:

    • For each asset, consider applicable STRIDE categories
    • For each trust boundary crossing, analyze all categories
    • For each attack surface entry, identify threats
  3. Generate threat entries:

    • Create unique IDs (threat-001, threat-002, etc.)
    • Write clear descriptions
    • Identify prerequisites
    • Assess impact (CIA triad)
    • Estimate likelihood
    • Calculate risk score
    • Map to MITRE ATT&CK and CWE where applicable
  4. Build attack trees for critical threats:

    • Create tree for threats with risk_score >= 12
    • Show attack paths as AND/OR trees
  5. Generate abuse cases (if --include-abuse):

    • Review sequence diagrams
    • Identify how legitimate flows could be misused
  6. Create risk register:

    • Prioritize by risk score
    • Group by category
    • Assign treatment strategy
  7. Write visual threat report (.threatmodel/reports/threat-report.md):

    # Threat Analysis Report
    
    **Generated**: [Date]
    **Framework**: STRIDE
    
    ## Summary
    
    

    THREAT ANALYSIS ═══════════════════════════════════════════════════════════

    Assets Analyzed: 14 Attack Surfaces Analyzed: 12

    THREATS BY SEVERITY ───────────────────────────────────────────────────────── CRITICAL │██████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 5 (11%) HIGH │████████████████████████░░░░░░░░░░░░░░░░│ 12 (26%) MEDIUM │████████████████████████████████████░░░░│ 18 (38%) LOW │████████████████████████░░░░░░░░░░░░░░░░│ 12 (26%)

    THREATS BY STRIDE CATEGORY ───────────────────────────────────────────────────────── Spoofing │████████████████░░░░░░░░░░░░░░░░│ 8 Tampering │████████████████████░░░░░░░░░░░░│ 10 Repudiation │████████░░░░░░░░░░░░░░░░░░░░░░░░│ 4 Information Disclosure│██████████████████░░░░░░░░░░░░░░│ 9 Denial of Service │██████████████░░░░░░░░░░░░░░░░░░│ 7 Elevation of Privilege│██████████████████░░░░░░░░░░░░░░│ 9

    
    ## Critical Threats
    
    ### THREAT-001: Credential Stuffing Attack
    
    

    ┌─────────────────────────────────────────────────────────┐ │ RISK SCORE: 8.5/10 (CRITICAL) │ ├─────────────────────────────────────────────────────────┤ │ Category: Spoofing │ │ Target: POST /api/auth/login │ │ │ │ ATTACK VECTOR: │ │ Automated login attempts with leaked credentials │ │ │ │ IMPACT: │ │ Confidentiality: HIGH │ │ Integrity: MEDIUM │ │ Availability: LOW │ │ │ │ MITRE ATT&CK: T1110.001 │ │ CWE: CWE-307 │ │ │ │ REQUIRED COUNTERMEASURES: │ │ • Rate limiting on auth endpoints │ │ • Account lockout after failed attempts │ │ • MFA enforcement │ └─────────────────────────────────────────────────────────┘

    
    [Additional threats...]
    
  8. Console summary (also display to user):

    Threat Analysis Complete
    ========================
    
    Framework: STRIDE
    Assets Analyzed: X
    Attack Surfaces Analyzed: Y
    
    Threats Identified:
      Critical: N
      High: N
      Medium: N
      Low: N
    
    Top Critical Threats:
      1. [THREAT-001] Title (Risk: 16)
      2. [THREAT-002] Title (Risk: 15)
    
    Attack Trees Generated: N
    Abuse Cases Documented: N
    
    Files Updated:
      .threatmodel/state/threats.json
      .threatmodel/state/attack-trees.json
      .threatmodel/state/risk-register.json
      .threatmodel/reports/threat-report.md
    
    Next Steps:
      Run /tm-verify to check control implementations
    

Reference Files

Control Verification

Purpose

Verify that security controls exist in your codebase by:

  • Searching for control implementations
  • Validating security configurations
  • Checking for security middleware/decorators
  • Identifying implementation gaps
  • Collecting evidence for each control

Usage

/tm-verify [--control <id>] [--category <name>] [--thorough] [--evidence]

Arguments:

  • --control: Verify specific control by ID
  • --category: Verify controls in category (auth, crypto, access-control, etc.)
  • --thorough: Deep code analysis
  • --evidence: Collect code evidence for documentation

Prerequisites

Requires threat analysis. Run /tm-threats first if threats.json doesn't exist.

Control Categories

Authentication Controls

Search patterns:
- passport, authenticate, login, signin
- bcrypt, argon2, scrypt, pbkdf2
- jwt, jsonwebtoken, jose
- session, cookie
- oauth, oidc, saml
- mfa, totp, 2fa, two-factor

Authorization Controls

Search patterns:
- authorize, isAuthorized, checkPermission
- hasRole, requireRole, role
- rbac, abac, acl
- permission, policy
- canAccess, isAllowed

Input Validation Controls

Search patterns:
- validate, validator, sanitize
- joi, yup, zod, ajv
- escape, encode
- xss, html-entities

Cryptography Controls

Search patterns:
- crypto, cipher, encrypt, decrypt
- hash, hmac, sign, verify
- tls, ssl, https
- certificate, key, secret

Rate Limiting Controls

Search patterns:
- rate-limit, rateLimit, throttle
- express-rate-limit
- slowDown
- quota, limit

Logging/Audit Controls

Search patterns:
- audit, log, logger
- winston, bunyan, pino
- monitor, track
- event, activity

Error Handling Controls

Search patterns:
- error, exception, catch
- errorHandler, onError
- try, catch, finally

Verification Process

For Each Required Control

  1. Search for implementation patterns

    • Use Grep with control-specific patterns
    • Search in configured code paths
    • Exclude test files and node_modules
  2. Analyze findings

    • Verify pattern matches are actual implementations
    • Check configuration completeness
    • Validate security of implementation
  3. Assess implementation status

    • implemented: Control fully present and configured
    • partial: Control exists but incomplete
    • planned: Control referenced but not implemented
    • missing: No evidence of control
  4. Collect evidence

    • File paths and line numbers
    • Configuration values
    • Related test files

Output Files

verification-report.md (Visual Report)

# Control Verification Report

**Generated**: [Date]
**Code Paths Analyzed**: [Paths]

## Summary

VERIFICATION RESULTS ═══════════════════════════════════════════════════════════

Controls Analyzed: 29

STATUS BREAKDOWN ───────────────────────────────────────────────────────── ✓ Implemented │████████████████████████████████████░░░░│ 18 (62%) ⚠ Partial │██████████████░░░░░░░░░░░░░░░░░░░░░░░░░░│ 7 (24%) ✗ Missing │████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 4 (14%)

GAPS BY SEVERITY ───────────────────────────────────────────────────────── CRITICAL │████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 2 HIGH │████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 4 MEDIUM │██████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 3 LOW │████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░│ 2


## Verified Controls

| Control | Status | Evidence |
|---------|--------|----------|
| Rate Limiting | ✓ Implemented | `src/middleware/rateLimiter.ts:15` |
| JWT Auth | ✓ Implemented | `src/middleware/auth.ts:23` |
| Input Validation | ⚠ Partial | `src/validators/` (missing on 3 routes) |
| MFA | ✗ Missing | No implementation found |

## Gap Details

### GAP-001: MFA Not Enforced (HIGH)

┌─────────────────────────────────────────────────────────┐ │ EXPECTED: MFA required for all admin accounts │ │ ACTUAL: MFA optional, no enforcement check found │ │ │ │ EVIDENCE: │ │ Searched: mfa, totp, 2fa, two-factor │ │ Found: No matches in auth middleware │ │ │ │ REMEDIATION: │ │ Add MFA verification in admin route middleware │ │ Effort: Medium | Priority: High │ └─────────────────────────────────────────────────────────┘


[Additional gaps...]

controls.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "controls": [
    {
      "id": "control-001",
      "name": "Rate Limiting on Auth Endpoints",
      "type": "preventive",
      "category": "authentication",
      "description": "Limit login attempts to prevent brute force",
      "threats_mitigated": ["threat-001", "threat-002"],
      "implementation": {
        "status": "implemented",
        "method": "express-rate-limit middleware",
        "configuration": {
          "windowMs": 60000,
          "max": 5
        }
      },
      "verification": {
        "status": "verified",
        "evidence": [
          {
            "type": "code",
            "location": "src/middleware/rateLimiter.ts:15-45",
            "verified_at": "2025-01-20T10:00:00Z"
          }
        ]
      },
      "effectiveness": 0.7
    }
  ]
}

gaps.json

{
  "version": "1.0",
  "generated": "ISO-8601",
  "gaps": [
    {
      "id": "gap-001",
      "control_id": "control-002",
      "title": "MFA Not Enforced for Admin Users",
      "description": "Multi-factor authentication available but not mandatory",
      "expected": "MFA required for all privileged accounts",
      "actual": "MFA optional, enforcement check missing",
      "severity": "high",
      "evidence": {
        "code_search": "No MFA enforcement in auth middleware",
        "config_check": "MFA_REQUIRED env var not set"
      },
      "remediation": {
        "recommendation": "Add MFA enforcement check in admin routes",
        "effort": "medium",
        "priority": "high"
      },
      "related_threats": ["threat-001", "threat-003"]
    }
  ]
}

Common Gap Patterns

Authentication Gaps

  • Password policy not enforced
  • Session timeout not configured
  • MFA not enforced
  • Account lockout missing

Authorization Gaps

  • Object-level authorization missing
  • Function-level access control gaps
  • IDOR vulnerabilities

Input Validation Gaps

  • Unvalidated user input
  • Missing output encoding
  • File upload without validation

Cryptography Gaps

  • Weak algorithms in use
  • Hardcoded secrets
  • Missing encryption at rest

Logging Gaps

  • Security events not logged
  • Sensitive data in logs
  • Missing log integrity

Instructions for Claude

When executing this skill:

  1. Load threat model state:

    • Read .threatmodel/state/threats.json
    • Read .threatmodel/config.yaml for code paths
  2. Determine required controls:

    • For each threat, identify needed countermeasures
    • Group by control category
  3. Search codebase for each control:

    • Use Grep with appropriate patterns
    • Search in configured code paths
    • Exclude test/vendor directories
  4. Analyze search results:

    • Verify matches are actual implementations
    • Check for proper configuration
    • Look for related tests
  5. Assess implementation status:

    • Mark as implemented, partial, or missing
    • Document evidence with file:line references
  6. Identify gaps:

    • For missing/partial controls
    • Document expected vs actual
    • Assess severity
    • Recommend remediation
  7. Write visual report file (.threatmodel/reports/verification-report.md):

    • Include ASCII progress bars for status breakdown
    • Include visual gap boxes with evidence
    • Use ✓, ⚠, ✗ symbols
    • This file should contain ALL the visual elements, not just JSON
  8. Console summary (also display to user):

    Control Verification Complete
    =============================
    
    Controls Analyzed: X
    
    Verification Results:
      ✓ Implemented: N
      ⚠ Partial: N
      ✗ Missing: N
    
    Gaps Identified:
      Critical: N
      High: N
      Medium: N
      Low: N
    
    Top Gaps:
      [GAP-001] HIGH: MFA not enforced
        Expected: Mandatory for admins
        Found: Optional in src/auth/mfa.ts
    
      [GAP-002] HIGH: SQL queries not parameterized
        Expected: Parameterized queries
        Found: Concatenation in src/legacy/reports.ts:120
    
    Files Updated:
      .threatmodel/state/controls.json
      .threatmodel/state/gaps.json
    
    Next Steps:
      Run /tm-compliance to map to frameworks
      Run /tm-report to generate risk report
    

Reference Files

Sponsors

Details

Marketplace
josemlopez/threat-modeling-toolkit
Author
Jose
Category
Community
License
MIT
Keywords
threat-modeling, security, stride, pasta, risk-analysis, compliance, owasp