DEV Community

Cover image for From Manual to Automated: A Deep Dive into Threat Modeling as Code with Python
ellipse2v
ellipse2v

Posted on • Edited on

From Manual to Automated: A Deep Dive into Threat Modeling as Code with Python

How to transform security analysis from a one-time exercise into a continuous, collaborative process


In the world of modern software development, we live by the principles of automation, version control, and continuous integration. We have Infrastructure as Code (IaC), Policy as Code, and CI/CD pipelines that can test and deploy our applications in minutes.

So why does security analysis, specifically threat modeling, often feel like a step back in time?

The Problem: When Security Can't Keep Up

Picture this familiar scene: your team is developing a new critical feature. The code is tested, performance is optimized, deployment is automated. But when it comes time to analyze security risks... out come the whiteboard markers.

For many teams, threat modeling remains a manual, periodic exercise:

  • πŸ“‹ Brainstorming sessions with static diagrams
  • πŸ“š Documents stored in wikis, outdated the moment they're published
  • ⏰ Point-in-time analyses that can't keep up with agile pace

The result? A growing gap between technical reality and security analysis.

The Solution: Threat Modeling as Code (TMasC)

This is where a fundamental paradigm shift comes in: moving from periodic security reviews to Continuous Threat Modeling, enabled by Threat Modeling as Code.

What is TMasC?

TMasC treats your system's security design as a collection of code artifacts. You define your architecture, data flows, and trust boundaries in a simple, version-controlled text file.

This approach unlocks the same benefits that IaC brought to infrastructure:

Before (Manual) After (TMasC)
🐌 Periodic analyses ⚑ Continuous automation
πŸ“Έ Frozen snapshot πŸ”„ Evolution with code
🏝️ Siloed work 🀝 Cross-team collaboration
🎲 Variable results 🎯 Reproducible process

Practical Case: SecOpsTM in Action

To illustrate these concepts, let's explore SecOpsTM, an open-source Python framework designed specifically for TMasC.

1. A Developer-Friendly DSL

Instead of a complex GUI, SecOpsTM uses Markdown - a deliberate choice to stay within the developer's natural ecosystem:

# Threat Model: Advanced DMZ Architecture

## Boundaries
- **Internet**: color=lightcoral, is_trusted=False
- **DMZ**: color=khaki, is_trusted=False  
- **Intranet**: color=lightgreen, is_trusted=True

## Servers
- **External Firewall**: boundary=DMZ
- **Central Server**: boundary=Intranet

## Dataflows
- **Client to Firewall**: from="External Client", to="External Firewall", protocol="HTTPS"
Enter fullscreen mode Exit fullscreen mode

Why Markdown?

  • βœ… Human-readable
  • βœ… Git-friendly (diff, merge, history)
  • βœ… Expressive (components + metadata)

2. Rule-Based Threat Engine

The framework goes beyond a basic STRIDE analysis. It combines threat generation from PyTM with a customizable rule engine.

Example rule:
"If a dataflow uses the HTTP protocol AND crosses from an untrusted boundary to a trusted one, then generate a high-severity 'Information Disclosure' threat."

3. Contextual, Actionable Intelligence

Identifying a threat is only half the battle. SecOpsTM excels at enriching each finding:

πŸ” Threat detected: "SQL Injection possible on login endpoint"
    ↳ 🏷️ STRIDE Category: Tampering  
    ↳ 🎯 MITRE ATT&CK: T1190 (Exploit Public-Facing Application)
    ↳ πŸ”§ CAPEC: CAPEC-66 (SQL Injection)
    ↳ πŸ›‘οΈ D3FEND: Concrete defensive measures
Enter fullscreen mode Exit fullscreen mode

This context chain transforms a vague warning into a precise, actionable intelligence brief.

A Practical CI/CD Workflow

Let's visualize how TMasC integrates naturally into your pipeline:

Scenario: New Unencrypted API

  1. πŸ‘¨β€πŸ’» Commit & Push: Developer pushes code + updates threat_model.md

  2. πŸš€ CI Trigger: GitHub Actions automatically launches analysis

  3. πŸ” Execution:

    python -m threat_analysis --model-file threat_model.md
    
  4. βš–οΈ Evaluation: Pipeline parses JSON output. New HIGH/CRITICAL threats β†’ Build fails

  5. πŸ’¬ Instant Feedback: Developer gets feedback in PR before code even reaches production

Integration with Infrastructure as Code

Key point: SecOpsTM includes an Ansible plugin that automatically generates a threat model from your playbooks.

# In your Ansible playbook
vars:
  threat_model_metadata:
    boundaries:
      - name: "Production"
        trusted: true
    dataflows:
      - from: "User"
        to: "API Gateway"  
        protocol: "HTTPS"
Enter fullscreen mode Exit fullscreen mode

This integration creates a single source of truth, ensuring your threat model stays synchronized with your deployed reality.

Multiple Outputs for Different Audiences

The framework produces a suite of artifacts tailored to each audience:

  • πŸ“Š Detailed HTML Report: For development teams
  • πŸ—ΊοΈ Interactive Diagrams: Hierarchical navigation with breadcrumbs
  • πŸ”§ JSON Export: Integration with other tools
  • πŸ”— STIX 2.1 Format: Interoperability with threat intelligence platforms
  • 🎯 MITRE ATT&CK Navigator: Visual heatmap of relevant techniques

Experience and Challenges

βœ… What works well:

  • Quick adoption: Developers understand immediately
  • Early feedback: Risk detection before production
  • Traceability: Complete history of security evolution

⚠️ Points of attention:

  • Model quality: "Garbage in, garbage out" - accuracy depends on model completeness
  • Learning curve: Need training on threat modeling concepts
  • False positives: Need to fine-tune rules according to context

The Future: Automated and Collaborative

Threat Modeling as Code isn't just a new technique; it's a cultural shift. It integrates security into the very fabric of the development process, making it a shared responsibility.

Tools like SecOpsTM are the engines that drive this shift, transforming threat modeling from a static, feared event into a continuous, collaborative, and automated habit.

To get started now:

  1. πŸš€ Start small: Model a critical component of your architecture
  2. πŸ“š Train the team: Organize a STRIDE/DREAD workshop
  3. πŸ”„ Integrate progressively: Add analysis to a non-critical pipeline first
  4. πŸ“Š Measure impact: Track detection and resolution metrics

By embracing TMasC, you're not just building software faster; you're building it safer, from the very first line of code.


Examples in Action

Here’s a glimpse of what SecOpsTM can produce:

Interactive GUI for Real-time Editing

The web-based GUI provides a live-reloading editor next to a dynamic diagram, allowing you to see the impact of your changes instantly.

GUI Example

Hierarchical Project Reporting

For complex applications, the framework can process nested threat models and generate a unified, navigable HTML report with interactive diagrams.

Hierarchical navigator

MITRE ATT&CK Navigator Integration

Visualize your system's threat landscape directly in the MITRE ATT&CK Navigator by loading the generated JSON layer. This provides an immediate, industry-standard view of the adversary techniques relevant to your architecture.

Navigator Example

Threat Model Report

Mapping between the threat, capec, mitre att&ck technique, mitre att&ck mitigation, d3fend mitigation.

Threat Model Report


To start your own journey with Threat Modeling as Code, check out the project on GitHub.

πŸ’‘ What about you? Is your team already practicing continuous threat modeling? Share your experience in the comments!

Top comments (0)