threat-model-spec

module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 13, 2026 License: MIT

README

Threat Model Spec

Go CI Go Lint Go SAST Docs Visualization License

Threat Model Spec is an open-source library for creating security threat modeling diagrams as code. It provides a JSON-based intermediate representation (IR) that can be rendered to D2 diagrams and STIX 2.1 for threat intelligence sharing.

Architecture

                         ┌──────────────────────┐
                         │     ThreatModel      │
                         │  (Canonical Source)  │
                         └──────────┬───────────┘
                                    │
       ┌────────────────────────────┼───────────────────────────┐
       │              │             │             │             │
       ▼              ▼             ▼             ▼             ▼
  ┌─────────┐   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐
  │   DFD   │   │  Attack  │  │ Sequence │  │  Attack  │  │ Security │
  │ Diagram │   │  Chain   │  │ Diagram  │  │   Tree   │  │ Metadata │
  └────┬────┘   └─────┬────┘  └─────┬────┘  └─────┬────┘  └─────┬────┘
       │              │             │             │             │
       └──────────────┴─────────────┴─────────────┴─────────────┘
                                    │
                    ┌───────────────┼──────────────┐
                    │               │              │
                    ▼               ▼              ▼
               ┌──────────┐   ┌──────────┐   ┌──────────┐
               │    D2    │   │   STIX   │   │ Validate │
               │ Renderer │   │ Exporter │   │          │
               └────┬─────┘   └─────┬────┘   └─────┬────┘
                    │               │              │
                    ▼               ▼              ▼
               ┌──────────┐   ┌──────────┐   ┌──────────┐
               │   .d2    │   │  .json   │   │  pass/   │
               │  → .svg  │   │  STIX    │   │  fail    │
               └──────────┘   │  Bundle  │   └──────────┘
                              └──────────┘

Input: ThreatModel JSON with shared metadata, framework mappings, and multiple diagram views

Outputs:

  • D2 Diagrams → SVG/PNG via D2 CLI (one per diagram view)
  • STIX 2.1 Bundles → Threat intelligence sharing
  • Validation Results → Schema and reference checking

Features

Core Capabilities
  • Design-Time Threat Modeling — Proactive security analysis during SDLC with STRIDE/LINDDUN
  • Risk Assessment — Structured likelihood × impact scoring with categorical risk levels
  • Asset Inventory — Sensitivity classification and compliance mapping
  • Scenario Modeling — What-if attack scenarios with preconditions and attack paths
  • Diagrams-as-Code — Define threat models in JSON, render to D2/SVG
  • Multiple Diagram Types — DFD, Attack Chain, Sequence, Attack Tree diagrams
  • Framework Mappings — MITRE ATT&CK, MITRE ATLAS, OWASP Top 10 (API, LLM, Web, ASI/Agentic), STRIDE, LINDDUN, CWE, CVSS, CVE
  • Control Frameworks — NIST CSF, CIS Controls v8, ISO 27001 mappings
  • Compliance Frameworks — SOC 2, PCI-DSS, HIPAA, GDPR, FedRAMP, and more
  • Mitigations — Track countermeasures with status (implemented, planned, accepted)
  • Threat Actors — Document adversary profiles with sophistication and motivation
  • Network Topology — Map elements to hosts, ports, protocols, and cloud infrastructure
  • Detection & Response — Define detection capabilities and response actions
  • STIX 2.1 Export — Share threat intelligence in standard format
  • D2 Styles — Color-coded STRIDE/LINDDUN annotations, trust boundaries, attack flows
  • Validation — Type-specific field validation with strict mode
  • AI Agents — Claude Code plugin for AI-assisted diagram creation
Security Enhancement Features (v0.6.0+)
  • Role-Based Security Guidance

    • Red Team — Exploitation steps, offensive tools, payload patterns, difficulty ratings
    • Blue Team — Detection rules (Sigma, YARA, Splunk), IOCs, hunting queries, log sources
    • Remediation — Secure code patterns, review checklists, recommended libraries
    • Incident Playbooks — Structured response procedures with IR phases and contacts
  • Risk Quantification

    • FAIR Assessment — Factor Analysis of Information Risk with frequency/loss estimates
    • Business Impact — Revenue, customer, regulatory, reputation, operational impacts
    • EPSS Integration — Exploit Prediction Scoring System data for CVEs
    • KEV Catalog — CISA Known Exploited Vulnerabilities tracking
  • Purple Team

    • Atomic Red Team Mapping — Link attacks to atomic tests with validation status
    • Detection Coverage Matrix — Track technique coverage across detection capabilities
    • Security Metrics — MTTD, MTTR, MTTC, detection rates, false positive tracking
  • Threat Intelligence

    • Enhanced STIX 2.1 Export — IOCs to indicators, actors to threat-actors, detections to course-of-actions
    • OWASP ASI Support — Agentic Security Top 10 (2026) mappings for AI agent threats
  • Supply Chain Security

    • SBOM Integration — Link threat models to CycloneDX/SPDX software bills of materials
    • VEX Statements — Vulnerability Exploitability eXchange for vulnerability status tracking
    • Dependency Risk — Track vulnerable components with severity and remediation guidance
  • Vulnerability Management

    • SSVC Decision Trees — CISA's Stakeholder-Specific Vulnerability Categorization
    • Priority Decisions — Automated prioritization (Track, Track*, Attend, Act)
    • Exploitation Status — Track active exploitation, PoC availability, and automatable attacks
  • Attack Path Analysis

    • Attack Graphs — Graph-based representation of attack surfaces
    • Path Finding — Find all paths, shortest paths (Dijkstra), and critical paths
    • Risk Calculation — Path-based risk scoring and reachability analysis
    • Graph Construction — Build attack graphs from threat model diagrams
v0.7.0 Agentic AI & Evaluation Features
  • Agentic AI Threat Modeling

    • Agent Capabilities — Tool access, permissions, sandboxing, and approval controls
    • Execution Context — Runtime environment and privilege level
    • New Boundary Typescontainer, sandbox, agent, origin
  • Credential & WebSocket Security

    • Credential Flow Tracking — Model token exfiltration and replay attacks across lifecycle stages
    • WebSocket Security Configuration — Origin validation, CSRF protection, and known vulnerability types
    • Trust Modeling — Record implicit trust assumptions on boundaries and how they can be violated
    • New Flow Typescredential, websocket, cswsh, lateral
  • Attack Patterns

    • Reusable Templates — Prerequisites, attack chains, vulnerable/secure code, and detection patterns shared across models
  • LLM-as-Judge Evaluation

    • structured-evaluation Integration — Embedded rubrics for threat models, vulnerability articles, and diagrams
    • Report Conversion — Export evaluation results as structured-evaluation rubric and claims reports
v0.8.0 PDLC Lifecycle Analysis Features
  • PDLC-Aware Analysis

    • Six PDLC Stages — product-definition, builder-definition, implementation, deployment, builder-operations, product-operations
    • Lifecycle ObjectsArtifact, AnalysisRun, Evidence, Finding, SecurityRequirement, ArchitectureAssertion, Gate
    • ASPM Overlay — 10 Application Security Posture Management domains mapped onto the three builder-side stages
  • Stage Report Profiles and Grading

    • StageReportProfile — Normative per-stage contract: input mode, required output objects, coverage checks, rubric
    • ArtifactAvailabilityProfile — first-party/third-party/open-source profiles declaring which stages are credibly analyzable given what's actually available
    • Six Stage Rubrics — Calibrated grading criteria per stage with seeded-defect fixtures
    • Gate Evaluation — Deterministic coverage checks + rubric verdicts → GO/WARN/NO-GO per stage
  • tms analyze and Read Verbs

    • tms analyze — Two-phase plan/apply orchestration around an AI agent's reasoning step; atomic merge (an invalid apply writes nothing)
    • tms status / tms report / tms gate / tms profile — Read verbs with human and --json output modes and CI-meaningful exit codes
  • Computed Framework Reports

    • FrameworkReport — STRIDE/LINDDUN coverage, MITRE ATT&CK mapping-to-coverage join, OWASP coverage, attack-tree path analysis — all derived fresh from one canonical model
    • Staleness Detectiontms validate warns when a materialized report has drifted from a fresh computation
  • PDLC Stage-Analyst Agents

    • Six Agent Specs — One multi-agent-spec agent (+ slash command) per PDLC stage, generated into Claude/Kiro/Gemini plugins
v0.9.0 Agentic Collective & Incident Modeling Features
  • Agentic Collective Modeling

    • AgentCollective — populations of autonomous agents that coordinate (possibly emergently) toward shared objectives: members, coordination channel, emergent behaviors, population/scale
    • coordination flow type — an inter-agent coordination channel (covert/emergent), rendered as a distinct teal dashed channel alongside C2 flows
    • Reward-hacking constructsreward-hacking and emergent-agent-coordination AttackPattern templates
  • Incident Modeling

    • Vulnerability inventory — software CVEs and non-software weaknesses (config, credential-hygiene, design), cross-referenceable against the CISA KEV catalog
    • Timeline — chronological incident/attack-chain events with optional phase grouping
    • AlignmentFailureMode mappings — classify why models behaved as they did (reward hacking, goal drift, …), a layer beyond ATT&CK/ATLAS; plus per-section summaries
  • Finding Framework Categorization & Coverage

    • Finding framework fields — STRIDE/OWASP/MITRE categorization on Finding
    • ComputeCoverageChecks — deterministic coverage computation; stage gates computed and recorded in tms analyze --apply

Installation

Go Library
go get github.com/grokify/threat-model-spec
CLI Tool
go install github.com/grokify/threat-model-spec/cmd/tms@latest

Quick Start

Define a Threat Model (JSON)

A ThreatModel is the canonical format containing shared metadata and multiple diagram views:

{
  "id": "websocket-localhost-takeover",
  "title": "WebSocket Localhost Takeover",
  "description": "Attack exploiting missing origin validation",
  "mappings": {
    "mitreAttack": [
      {"tacticId": "TA0001", "techniqueId": "T1189", "techniqueName": "Drive-by Compromise"}
    ],
    "owasp": [
      {"category": "api", "id": "API2:2023", "name": "Broken Authentication"}
    ]
  },
  "diagrams": [
    {
      "type": "attack-chain",
      "title": "Attack Chain",
      "elements": [
        {"id": "attacker", "label": "Attacker", "type": "external-entity"},
        {"id": "victim", "label": "Victim", "type": "process"}
      ],
      "attacks": [
        {"step": 1, "from": "attacker", "to": "victim", "label": "WebSocket to localhost"}
      ]
    }
  ]
}

Single-diagram files (DiagramIR format) are also supported for simpler use cases.

Examples

The examples/ directory contains complete, validated threat models covering different parts of the format:

Example Demonstrates
openclaw-websocket-takeover.json A fully implemented vulnerability: DFD + attack-chain diagrams, framework mappings, red/blue team guidance, remediation, and v0.7.0 credential-flow/WebSocket-security fields
design-phase-payment-checkout.json Pre-implementation threat modeling: assumptions, prerequisites, and STRIDE threats derived from an architecture that doesn't exist yet
supply-chain-vulnerable-dependency.json Supply chain security: SBOM reference, VEX statements, and dependency risk tracking
threat-model-spec-self-assessment.json PDLC lifecycle analysis, first-party profile: a real three-stage tms analyze run against this project's own artifacts, graded with recorded Gates
lodash-template-open-source-assessment.json PDLC lifecycle analysis, open-source profile: a real external dependency (lodash, CVE-2021-23337) analyzed under a partial-artifact profile

Validate any example with the CLI:

tms validate examples/openclaw-websocket-takeover.json --strict
Generate Diagrams
# Generate D2 diagram from ThreatModel
tms generate threat-model.json -o diagram.d2

# Also render to SVG
tms generate threat-model.json -o diagram.d2 --svg

# Export to STIX 2.1
tms generate threat-model.json --stix -o threat-model.stix.json

# Validate only
tms validate threat-model.json
PDLC Stage Analysis
# Plan a stage analysis: resolve inputs, open an AnalysisRun
tms analyze threat-model.json --stage implementation --profile first-party \
  --producer implementation-analyst src/handler.go

# Apply an agent's results: validate + merge atomically, close the run
tms analyze threat-model.json --stage implementation --apply results.json --run <run-id>

# Read lifecycle state, gate results, and computed framework reports
tms status threat-model.json
tms gate threat-model.json --stage implementation --ci
tms report threat-model.json --framework stride --format markdown
tms profile open-source

Diagram Types

Type Description Key Fields
dfd Data Flow Diagram elements, boundaries, flows
attack-chain Attack sequence elements, attacks, targets
sequence Time-ordered messages actors, messages, phases
attack-tree Hierarchical attack decomposition attackTree (nodes with AND/OR logic)

Framework Mappings

Threat Frameworks
Framework Field Example
MITRE ATT&CK mitreAttack {"tacticId": "TA0001", "techniqueId": "T1189"}
MITRE ATLAS mitreAtlas {"id": "AML.T0024", "name": "Prompt Injection"}
Alignment Failure Modes alignmentFailureModes {"id": "reward-hacking", "name": "Reward Hacking", "primary": true}
OWASP owasp {"category": "api", "id": "API2:2023"}
STRIDE stride {"category": "S", "name": "Spoofing"}
LINDDUN linddun {"category": "I", "name": "Identifiability"}
CWE cwe {"id": "CWE-346", "name": "Origin Validation Error"}
CVE cve {"id": "CVE-2024-12345"}
CVSS cvss {"version": "3.1", "vector": "CVSS:3.1/..."}
OWASP Top 10 Categories
Category Value List Year
API Security api API Security Top 10 2023
LLM Applications llm LLM Application Top 10 2025
Web Applications web Web Application Top 10 2021
Agentic Applications agentic Agentic Top 10 (ASI) 2026

Attack steps can include asiIds for OWASP Agentic Security mappings:

{
  "step": 6,
  "from": "gateway",
  "to": "agent",
  "label": "Access agent",
  "asiIds": ["ASI02:2026", "ASI03:2026"],
  "owaspIds": ["API8:2023"]
}
Control Frameworks
Framework Field Example
NIST CSF controls.nistCsf {"function": "Protect", "category": "PR.AC"}
CIS Controls controls.cis {"controlId": "16", "safeguardId": "16.4"}
ISO 27001 controls.iso27001 {"controlId": "A.9.2.3"}
Compliance Frameworks
Framework Value Description
SOC 2 soc2 AICPA Service Organization Controls
PCI-DSS pci-dss Payment Card Industry Data Security
HIPAA hipaa Health Insurance Portability
GDPR gdpr General Data Protection Regulation
FedRAMP fedramp Federal Risk Authorization
NIST SP 800-53 nist-sp-800-53 Security Controls Catalog

D2 Style Reference

STRIDE Threat Annotations
Category Color Description
S - Spoofing Red Identity spoofing
T - Tampering Yellow Data tampering
R - Repudiation Purple Non-repudiation failures
I - Information Disclosure Blue Information leakage
D - Denial of Service Orange Availability attacks
E - Elevation of Privilege Green Privilege escalation
LINDDUN Privacy Threats
Category Color Description
L - Linkability Indigo Linking items of interest
I - Identifiability Blue Identifying data subjects
N - Non-repudiation Orange Unable to deny actions
D - Detectability Pink Detecting item existence
Di - Disclosure Red Information disclosure
U - Unawareness Purple Lack of awareness
Nc - Non-compliance Brown Regulatory non-compliance
Trust Boundaries
Type Color Use For
browser Blue Browser sandbox
localhost Purple Localhost implicit trust
network Green Network zones
breached Dark red Compromised boundaries
Mitigation Status
Status Color Description
implemented Green Fully implemented
partial Orange Partially implemented
planned Blue Planned for future
accepted Gray Risk accepted
transferred Light blue Risk transferred

Security Lifecycle

Mitigations

Track countermeasures for identified threats:

{
  "mitigations": [
    {
      "id": "mit-1",
      "title": "Implement Origin Validation",
      "status": "implemented",
      "threatIds": ["threat-1"],
      "owner": "security-team"
    }
  ]
}
Threat Actors

Document adversary profiles:

{
  "threatActors": [
    {
      "id": "actor-1",
      "name": "External Attacker",
      "type": "criminal",
      "sophistication": "medium",
      "motivations": ["financial"]
    }
  ]
}
Detection & Response

Define detection capabilities:

{
  "detections": [
    {
      "id": "det-1",
      "title": "WebSocket Origin Anomaly",
      "coverage": "full",
      "dataSources": ["logs", "waf"]
    }
  ]
}

AI Agents

The agents/ directory contains specifications for AI-assisted threat model diagram creation:

Agent Description
dfd-creator Creates Data Flow Diagrams with numbered flows and trust boundaries
attack-flow-visualizer Creates attack chain diagrams with MITRE ATT&CK annotations
diagram-quality-reviewer Reviews diagrams for layout quality and legend clarity
Claude Code Plugin

Install the Claude Code plugin for AI-assisted diagram creation:

claude plugins add ./agents/plugins/claude

Use the /create-dfd command to generate diagrams interactively.

Specification

The Threat Model Specification follows a versioned schema approach similar to OpenAPI.

Version Schema Specification
v0.9.0 threat-model.schema.json specification.md
v0.8.0 threat-model.schema.json specification.md
v0.7.0 threat-model.schema.json specification.md
v0.6.0 threat-model.schema.json specification.md
v0.5.0 threat-model.schema.json specification.md
v0.4.0 threat-model.schema.json specification.md
Schema URLs

The links above resolve on GitHub for browsing. For $schema references that require raw JSON (validators, editors), use the published documentation site instead — GitHub's web UI serves an HTML wrapper, not raw JSON:

https://grokify.github.io/threat-model-spec/versions/v0.9.0/threat-model.schema.json
https://grokify.github.io/threat-model-spec/versions/v0.9.0/diagram.schema.json
Using the Schema

Reference the schema in your threat model JSON:

{
  "$schema": "https://grokify.github.io/threat-model-spec/versions/v0.8.0/threat-model.schema.json",
  "id": "my-threat-model",
  "title": "My Application Threat Model",
  "diagrams": [...]
}

Requirements

  • Go 1.25+
  • D2 v0.6+ for SVG rendering

License

MIT License - see LICENSE

References

Directories

Path Synopsis
cmd
genschema command
Command genschema generates JSON Schema files from Go types.
Command genschema generates JSON Schema files from Go types.
tms command
tms (Threat Model Spec) is a CLI for creating security threat modeling diagrams.
tms (Threat Model Spec) is a CLI for creating security threat modeling diagrams.
demo
attacker command
Automated Attack Demo with Video Capture
Automated Attack Demo with Video Capture
vulnerable-server command
Vulnerable WebSocket Server - Educational Demo
Vulnerable WebSocket Server - Educational Demo
Package diagram provides types for building threat model diagrams that can be rendered to D2 format.
Package diagram provides types for building threat model diagrams that can be rendered to D2 format.
Package evaluation: PDLC/structured-evaluation integration conventions.
Package evaluation: PDLC/structured-evaluation integration conventions.
Package ir provides the intermediate representation for threat models.
Package ir provides the intermediate representation for threat models.
Package killchain provides types for attack chain frameworks including MITRE ATT&CK and Lockheed Martin Cyber Kill Chain.
Package killchain provides types for attack chain frameworks including MITRE ATT&CK and Lockheed Martin Cyber Kill Chain.
Package schema provides embedded JSON Schema files for threat model validation.
Package schema provides embedded JSON Schema files for threat model validation.
Package stix provides STIX 2.1 export capabilities for threat models.
Package stix provides STIX 2.1 export capabilities for threat models.
Package stride provides types for STRIDE threat modeling.
Package stride provides types for STRIDE threat modeling.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL