0
0
Source

Python-based threat modeling using pytm library for programmatic STRIDE analysis, data flow diagram generation, and automated security threat identification. Use when: (1) Creating threat models programmatically using Python code, (2) Generating data flow diagrams (DFDs) with automatic STRIDE threat identification, (3) Integrating threat modeling into CI/CD pipelines and shift-left security practices, (4) Analyzing system architecture for security threats across trust boundaries, (5) Producing threat reports with STRIDE categories and mitigation recommendations, (6) Maintaining threat models as code for version control and automation.

Install

mkdir -p .claude/skills/pytm && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5141" && unzip -o skill.zip -d .claude/skills/pytm && rm skill.zip

Installs to .claude/skills/pytm

About this skill

Threat Modeling with pytm

Overview

pytm is a Python library for programmatic threat modeling based on the STRIDE methodology. It enables security engineers to define system architecture as code, automatically generate data flow diagrams (DFDs), identify security threats across trust boundaries, and produce comprehensive threat reports. This approach integrates threat modeling into CI/CD pipelines, enabling shift-left security and continuous threat analysis.

Quick Start

Create a basic threat model:

#!/usr/bin/env python3
from pytm import TM, Server, Dataflow, Boundary, Actor

# Initialize threat model
tm = TM("Web Application Threat Model")
tm.description = "E-commerce web application"

# Define trust boundaries
internet = Boundary("Internet")
dmz = Boundary("DMZ")
internal = Boundary("Internal Network")

# Define actors and components
user = Actor("Customer")
user.inBoundary = internet

web = Server("Web Server")
web.inBoundary = dmz

db = Server("Database")
db.inBoundary = internal

# Define data flows
user_to_web = Dataflow(user, web, "HTTPS Request")
user_to_web.protocol = "HTTPS"
user_to_web.data = "credentials, payment info"
user_to_web.isEncrypted = True

web_to_db = Dataflow(web, db, "Database Query")
web_to_db.protocol = "SQL/TLS"
web_to_db.data = "user data, transactions"

# Generate threat report and diagram
tm.process()

Install pytm:

pip install pytm
# Also requires graphviz for diagram generation
brew install graphviz  # macOS
# or: apt-get install graphviz  # Linux

Core Workflows

Workflow 1: Create New Threat Model

Progress: [ ] 1. Define system scope and trust boundaries [ ] 2. Identify all actors (users, administrators, external systems) [ ] 3. Map system components (servers, databases, APIs, services) [ ] 4. Define data flows between components with security attributes [ ] 5. Run tm.process() to generate threats and DFD [ ] 6. Review STRIDE threats and add mitigations [ ] 7. Generate threat report with scripts/generate_report.py

Work through each step systematically. Check off completed items.

Workflow 2: STRIDE Threat Analysis

pytm automatically identifies threats based on STRIDE categories:

  • Spoofing: Identity impersonation attacks
  • Tampering: Unauthorized modification of data
  • Repudiation: Denial of actions without traceability
  • Information Disclosure: Unauthorized access to sensitive data
  • Denial of Service: Availability attacks
  • Elevation of Privilege: Unauthorized access escalation

For each identified threat:

  1. Review threat description and affected component
  2. Assess likelihood and impact (use references/risk_matrix.md)
  3. Determine if existing controls mitigate the threat
  4. Add mitigation using threat.mitigation = "description"
  5. Document residual risk and acceptance criteria

Workflow 3: Architecture as Code

Define system architecture programmatically:

from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor, Lambda

tm = TM("Microservices Architecture")

# Cloud boundaries
internet = Boundary("Internet")
cloud_vpc = Boundary("Cloud VPC")

# API Gateway
api_gateway = Server("API Gateway")
api_gateway.inBoundary = cloud_vpc
api_gateway.implementsAuthentication = True
api_gateway.implementsAuthorization = True

# Microservices
auth_service = Lambda("Auth Service")
auth_service.inBoundary = cloud_vpc

order_service = Lambda("Order Service")
order_service.inBoundary = cloud_vpc

# Data stores
user_db = Datastore("User Database")
user_db.inBoundary = cloud_vpc
user_db.isEncryptedAtRest = True

# Data flows with security properties
client_to_api = Dataflow(Actor("Client"), api_gateway, "API Request")
client_to_api.protocol = "HTTPS"
client_to_api.isEncrypted = True
client_to_api.data = "user credentials, orders"

api_to_auth = Dataflow(api_gateway, auth_service, "Auth Check")
api_to_auth.protocol = "gRPC/TLS"

auth_to_db = Dataflow(auth_service, user_db, "User Lookup")
auth_to_db.protocol = "TLS"

tm.process()

Workflow 4: CI/CD Integration

Automate threat modeling in continuous integration:

# .github/workflows/threat-model.yml
name: Threat Model Analysis
on: [push, pull_request]

jobs:
  threat-model:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'

      - name: Install dependencies
        run: |
          pip install pytm
          sudo apt-get install -y graphviz

      - name: Generate threat model
        run: python threat_model.py

      - name: Upload DFD diagram
        uses: actions/upload-artifact@v3
        with:
          name: threat-model-dfd
          path: '*.png'

      - name: Check for unmitigated threats
        run: python scripts/check_mitigations.py threat_model.py

Workflow 5: Threat Report Generation

Generate comprehensive threat documentation:

# Run threat model with report generation
python threat_model.py

# Generate markdown report
./scripts/generate_report.py --model threat_model.py --output threat_report.md

# Generate JSON for tool integration
./scripts/generate_report.py --model threat_model.py --format json --output threats.json

Report includes:

  • System architecture overview
  • Trust boundary analysis
  • Complete STRIDE threat enumeration
  • Existing and recommended mitigations
  • Risk prioritization matrix

Security Considerations

Sensitive Data Handling

  • Threat models as code: Store in version control but review for sensitive architecture details
  • Credentials and secrets: Never hardcode in threat models - use placeholders
  • Data classification: Clearly label data flows with sensitivity levels (PII, PCI, PHI)
  • Report distribution: Control access to threat reports revealing security architecture

Access Control

  • Threat model repository: Restrict write access to security team and architects
  • CI/CD integration: Protect threat modeling pipeline from tampering
  • Diagram artifacts: Control distribution of DFDs showing system architecture
  • Mitigation tracking: Integrate with secure issue tracking systems

Audit Logging

Log the following for security governance:

  • Threat model creation and modification history
  • Identified threats and severity assessments
  • Mitigation implementation and validation
  • Risk acceptance decisions with approval
  • Threat model review and update cycles

Compliance Requirements

  • NIST 800-30: Risk assessment methodology alignment
  • ISO 27001: A.14.1.2 - Securing application services on public networks
  • OWASP SAMM: Threat Assessment practice maturity
  • PCI-DSS 6.3.1: Security threat identification in development
  • SOC2 CC9.1: Risk assessment process for system changes

Bundled Resources

Scripts (scripts/)

  • generate_report.py - Generate markdown/JSON threat reports with STRIDE categorization
  • check_mitigations.py - Validate all identified threats have documented mitigations
  • threat_classifier.py - Classify threats by severity using DREAD or custom risk matrix
  • template_generator.py - Generate threat model templates for common architectures

References (references/)

  • stride_methodology.md - Complete STRIDE methodology guide with threat examples
  • risk_matrix.md - Risk assessment framework with likelihood and impact scoring
  • component_library.md - Reusable pytm components for common patterns (APIs, databases, cloud services)
  • mitigation_strategies.md - Common mitigation patterns mapped to STRIDE categories and OWASP controls

Assets (assets/)

  • templates/web_application.py - Web application threat model template
  • templates/microservices.py - Microservices architecture template
  • templates/mobile_app.py - Mobile application threat model template
  • templates/iot_system.py - IoT system threat model template
  • dfd_styles.json - Custom graphviz styling for professional diagrams

Common Patterns

Pattern 1: Web Application Three-Tier Architecture

from pytm import TM, Server, Datastore, Dataflow, Boundary, Actor

tm = TM("Three-Tier Web Application")

# Boundaries
internet = Boundary("Internet")
dmz = Boundary("DMZ")
internal = Boundary("Internal Network")

# Components
user = Actor("End User")
user.inBoundary = internet

lb = Server("Load Balancer")
lb.inBoundary = dmz
lb.implementsNonce = True

web = Server("Web Server")
web.inBoundary = dmz
web.implementsAuthentication = True
web.implementsAuthenticationOut = False

app = Server("Application Server")
app.inBoundary = internal
app.implementsAuthorization = True

db = Datastore("Database")
db.inBoundary = internal
db.isSQL = True
db.isEncryptedAtRest = True

# Data flows
Dataflow(user, lb, "HTTPS").isEncrypted = True
Dataflow(lb, web, "HTTPS").isEncrypted = True
Dataflow(web, app, "HTTP").data = "session token, requests"
Dataflow(app, db, "SQL/TLS").data = "user data, transactions"

tm.process()

Pattern 2: Cloud Native Microservices

from pytm import TM, Lambda, Datastore, Dataflow, Boundary, Actor

tm = TM("Cloud Microservices")

cloud = Boundary("Cloud Provider VPC")
user = Actor("Mobile App")

# Serverless functions
api_gateway = Lambda("API Gateway")
api_gateway.inBoundary = cloud
api_gateway.implementsAPI = True

auth_fn = Lambda("Auth Function")
auth_fn.inBoundary = cloud

# Managed services
cache = Datastore("Redis Cache")
cache.inBoundary = cloud
cache.isEncrypted = True

db = Datastore("DynamoDB")
db.inBoundary = cloud
db.isEncryptedAtRest = True

# Data flows
Dataflow(user, api_gateway, "API Call").protocol = "HTTPS"
Dataflow(api_gateway, auth_fn, "Auth").protocol = "internal"
Dataflow(auth_fn, cache, "Session").isEncrypted = True
Dataflow(api_gateway, db, "Query").isEncrypted = True

tm.process()

Pattern 3: Adding Custom Threats

Define organization-specific threats:

from pytm import TM, Threat

---

*Content truncated.*

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

641968

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318395

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

450339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.