Skip to content
SecureKhan
Go back

Threat Modeling for Security Engineers

Threat Modeling for Security Engineers

Find vulnerabilities before writing code. Threat modeling is the most cost-effective security activity, yet it’s often skipped. This guide makes you proficient at structured threat analysis.

Quick Reference

FrameworkBest ForComplexity
STRIDEApplication featuresMedium
PASTABusiness-focused analysisHigh
Attack TreesSpecific attack scenariosMedium
DREADRisk prioritizationLow
LINDDUNPrivacy-focusedMedium

Why Threat Model?

Cost of Finding Vulnerabilities

Cost Multiplier by Phase:
┌─────────────────────────────────────────────────────┐
│ Design     │ █           │ 1x                       │
│ Development│ ████        │ 6x                       │
│ Testing    │ ███████     │ 15x                      │
│ Production │ ████████████│ 30x                      │
│ Post-Breach│ ███████████████████████│ 100x+        │
└─────────────────────────────────────────────────────┘

Threat modeling happens at design (1x cost)

When to Threat Model

TriggerAction
New feature/productFull threat model
Architecture changeUpdate existing model
New integrationFocused threat model
Incident occurredReview and update model
Periodic reviewAnnual refresh

The Four Questions Framework

Every threat model answers these questions:

1. What are we building?
   → Architecture diagrams, data flows

2. What can go wrong?
   → Threats, attack scenarios

3. What are we doing about it?
   → Mitigations, controls

4. Did we do a good job?
   → Review, validation

Creating Data Flow Diagrams

DFD Elements

┌─────────────────────────────────────────────────────────────┐
│                    DFD Symbol Reference                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────┐    External Entity (user, external system)     │
│  │ Entity  │    Outside your control/trust boundary         │
│  └─────────┘                                                │
│                                                             │
│  ( Process )    Process/Service                             │
│                 Transforms or processes data                 │
│                                                             │
│  ═══════════    Data Store                                  │
│  ║ DB/File ║    Persistent storage                          │
│  ═══════════                                                │
│                                                             │
│  ─────────→     Data Flow                                   │
│                 Movement of data                            │
│                                                             │
│  - - - - - -    Trust Boundary                              │
│                 Security context change                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Example: E-Commerce Application DFD

                           TRUST BOUNDARY: Internet
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

┌──────────┐      HTTPS            │
│ Customer │──────────────────────>│
└──────────┘                       │

- - - - - - - - - - - - - - - - - -│- - - - - - - - - - - - - -
                           TRUST BOUNDARY: DMZ


                            ( Web Server )

                                   │ Internal API

- - - - - - - - - - - - - - - - - -│- - - - - - - - - - - - - -
                           TRUST BOUNDARY: Internal Network


                            ( App Server )
                              /         \
                             /           \
                            ▼             ▼
                    ═══════════     ═══════════
                    ║  Users  ║     ║  Orders ║
                    ║   DB    ║     ║   DB    ║
                    ═══════════     ═══════════


- - - - - - - - - - - - - - - - - - - - - │ - - - - - - - - - -
                           TRUST BOUNDARY: Payment Network


                                   ┌────────────┐
                                   │  Payment   │
                                   │  Gateway   │
                                   └────────────┘

Identifying Trust Boundaries

BoundaryDescriptionSecurity Concern
Internet → DMZUntrusted usersAuthentication, input validation
DMZ → InternalPublic to privateAuthorization, network segmentation
Internal → DBApp to dataSQL injection, access control
Internal → ExternalYour system to partnerData integrity, confidentiality

STRIDE Methodology

STRIDE Categories

ThreatProperty ViolatedExample
SpoofingAuthenticationStolen credentials, session hijacking
TamperingIntegrityModified data, SQL injection
RepudiationNon-repudiationDeleted audit logs, false claims
Information DisclosureConfidentialityData breach, verbose errors
Denial of ServiceAvailabilityDDoS, resource exhaustion
Elevation of PrivilegeAuthorizationAdmin access, privilege escalation

STRIDE-per-Element

Apply STRIDE based on DFD element type:

ElementSTRIDE
External Entity
Process
Data Store
Data Flow

Example: Applying STRIDE

Component: User Authentication Process

┌──────────┐     credentials      ( Auth     )    ═══════════
│   User   │─────────────────────>│ Service  │───>║ User DB ║
└──────────┘                      (          )    ═══════════
ThreatAnalysisMitigation
SpoofingAttacker impersonates userMFA, strong password policy
TamperingModify auth request in transitHTTPS, request signing
RepudiationUser denies loginAudit logging with timestamps
Info DisclosureEnumerate valid usernamesGeneric error messages
DoSAccount lockout abuseCAPTCHA, rate limiting
ElevationBypass auth, gain adminRBAC, principle of least privilege

Attack Trees

Building Attack Trees

Goal: Steal Customer Credit Card Data
├── 1. Compromise Database
│   ├── 1.1 SQL Injection
│   │   ├── 1.1.1 Find injectable parameter
│   │   └── 1.1.2 Extract data via UNION
│   ├── 1.2 Stolen DB Credentials
│   │   ├── 1.2.1 Phish DBA
│   │   └── 1.2.2 Find creds in code/config
│   └── 1.3 Exploit DB vulnerability
│       └── 1.3.1 Unpatched CVE

├── 2. Intercept in Transit
│   ├── 2.1 Man-in-the-Middle
│   │   ├── 2.1.1 SSL stripping
│   │   └── 2.1.2 Rogue certificate
│   └── 2.2 Compromise endpoint
│       └── 2.2.1 Malware on client

└── 3. Access via Application
    ├── 3.1 IDOR to other users' data
    ├── 3.2 Compromise admin account
    │   ├── 3.2.1 Credential stuffing
    │   └── 3.2.2 Password spray
    └── 3.3 Export functionality abuse

Annotating Attack Trees

Add metrics to prioritize:

Goal: Steal Customer Credit Card Data [Impact: Critical]
├── 1. SQL Injection [Likelihood: Medium, Effort: Low]
│   → Mitigation: Parameterized queries, WAF
│   → Status: Mitigated

├── 2. Stolen DB Credentials [Likelihood: Low, Effort: Medium]
│   → Mitigation: Secrets management, rotation
│   → Status: Partially mitigated

└── 3. IDOR [Likelihood: High, Effort: Low]
    → Mitigation: Authorization checks, UUID
    → Status: NEEDS ATTENTION ⚠️

PASTA Methodology

Seven Stages of PASTA

Stage 1: Define Objectives
├── Business objectives
├── Security requirements
└── Compliance needs

Stage 2: Define Technical Scope
├── Architecture diagrams
├── Technologies used
└── Data flows

Stage 3: Application Decomposition
├── Identify components
├── Trust boundaries
└── Entry points

Stage 4: Threat Analysis
├── Threat intelligence
├── Historical incidents
└── Industry threats

Stage 5: Vulnerability Analysis
├── Known vulnerabilities
├── Design weaknesses
└── Configuration issues

Stage 6: Attack Modeling
├── Attack trees
├── Attack scenarios
└── Exploit likelihood

Stage 7: Risk Analysis
├── Business impact
├── Prioritization
└── Mitigation strategies

PASTA Example: Banking App

Stage 1: Objectives

Stage 4: Threat Analysis

Threat ActorMotivationCapabilityRelevance
CybercriminalsFinancial gainHighCritical
Nation-stateEspionageVery HighMedium
InsiderFraud, revengeMediumHigh
HacktivistsReputation damageMediumLow

Stage 6: Attack Scenarios

  1. Credential stuffing → Account takeover → Fraudulent transfers
  2. XSS injection → Session hijacking → Unauthorized access
  3. Insider → Direct DB access → Data exfiltration

Risk Prioritization

DREAD Scoring

FactorDescriptionScore
DamageHow bad is the impact?1-10
ReproducibilityHow easy to reproduce?1-10
ExploitabilityHow easy to exploit?1-10
Affected UsersHow many impacted?1-10
DiscoverabilityHow easy to find?1-10

Risk = (D + R + E + A + D) / 5

Example DREAD Analysis

Threat: SQL Injection in Search Function

FactorScoreRationale
Damage9Full database compromise
Reproducibility8Consistent exploitation
Exploitability7sqlmap automates it
Affected Users10All customers
Discoverability6Requires testing

Risk Score: (9+8+7+10+6)/5 = 8.0 (Critical)

Risk Matrix

              │ Low Impact │ Medium Impact │ High Impact │
──────────────┼────────────┼───────────────┼─────────────┤
High          │   Medium   │     High      │  Critical   │
Likelihood    │            │               │             │
──────────────┼────────────┼───────────────┼─────────────┤
Medium        │    Low     │    Medium     │    High     │
Likelihood    │            │               │             │
──────────────┼────────────┼───────────────┼─────────────┤
Low           │    Info    │     Low       │   Medium    │
Likelihood    │            │               │             │

Threat Modeling in Practice

Facilitating a Threat Model Session

Preparation (30 min before):

1. Gather architecture diagrams
2. Identify key stakeholders
3. Prepare DFD templates
4. Review previous threat models
5. Research relevant threat intelligence

Session Agenda (2 hours):

0:00 - Introduction, scope definition (15 min)
0:15 - Architecture walkthrough (20 min)
0:35 - Create/update DFD (25 min)
1:00 - Break (10 min)
1:10 - STRIDE analysis (30 min)
1:40 - Prioritization (15 min)
1:55 - Next steps, action items (5 min)

Post-Session:

1. Document findings in standard format
2. Create tickets for mitigations
3. Schedule follow-up review
4. Update threat model repository

Threat Model Document Template

# Threat Model: [Feature/System Name]

## Metadata
- Version: 1.0
- Date: 2024-01-15
- Author: Security Team
- Reviewers: [Names]
- Status: Draft/Review/Approved

## 1. Overview
Brief description of the system/feature being modeled.

## 2. Architecture
### 2.1 System Context
[High-level diagram]

### 2.2 Data Flow Diagram
[Detailed DFD with trust boundaries]

### 2.3 Technologies
| Component | Technology | Version |
|-----------|------------|---------|
| Web Server | nginx | 1.24 |
| Application | Node.js | 20.x |
| Database | PostgreSQL | 15 |

## 3. Assets
| Asset | Sensitivity | Owner |
|-------|-------------|-------|
| User credentials | Critical | IAM Team |
| Payment data | Critical | Finance |
| Session tokens | High | App Team |

## 4. Threat Analysis
### 4.1 STRIDE Analysis
[Table of threats per component]

### 4.2 Attack Trees
[Relevant attack trees]

## 5. Mitigations
| Threat | Mitigation | Status | Owner |
|--------|------------|--------|-------|
| SQLi | Parameterized queries | Implemented | Dev |
| XSS | CSP headers | In Progress | DevOps |

## 6. Risks
| Risk | Likelihood | Impact | Score | Accept/Mitigate |
|------|------------|--------|-------|-----------------|
| Data breach via SQLi | Low | Critical | 6.5 | Mitigate |

## 7. Action Items
- [ ] Implement CSP headers (DevOps, 2024-02-01)
- [ ] Add rate limiting (Backend, 2024-02-15)

## 8. Appendix
- Previous threat model versions
- Related security documentation

Interview Deep Dive

Q: Walk me through how you’d threat model a new user authentication feature.

A: I’d follow a structured approach:

1. Scope Definition:

2. Create DFD:

┌──────┐    creds     ( Auth    )    ═══════════
│ User │────────────>│ Service │───>║ User DB ║
└──────┘             (         )    ═══════════
    │                     │
    │                     ▼
    │              ( Session    )
    │              │ Manager    │
    │              (            )
    │                     │
    └──────session───────<┘

3. STRIDE Analysis:

ThreatSpecific RiskMitigation
SpoofingCredential theftMFA, password policy
TamperingSession token modificationSigned JWTs, integrity checks
RepudiationDeny login actionsComprehensive audit logs
Info DisclosureUsername enumerationGeneric error messages
DoSAccount lockout abuseCAPTCHA, progressive delays
ElevationAuth bypass → adminStrict RBAC, claims validation

4. Prioritize and Assign:

Q: How do you handle threat modeling for a microservices architecture?

A: Microservices add complexity but follow similar principles:

1. Layer the Analysis:

2. Focus on Trust Boundaries:

Every service-to-service call crosses a trust boundary
- Service A → Service B: Is B validating A's identity?
- API Gateway → Services: Is the gateway a single point of failure?
- External → Internal: Where's the security perimeter?

3. Key Threat Areas:

AreaThreatsControls
Service meshSpoofing between servicesmTLS, service identity
API GatewayBypass, misconfigurationAuth at gateway AND service
SecretsCredential sprawlCentralized secrets management
ObservabilityLog injection, data leakSanitized logging, access controls

4. Practical Approach:

Q: What’s the difference between STRIDE and PASTA? When would you use each?

A: Key differences:

AspectSTRIDEPASTA
FocusTechnical threatsBusiness-aligned risks
ApproachPer-element analysisFull lifecycle methodology
ComplexityMediumHigh
OutputThreat listRisk-prioritized attack scenarios
Best forFeature-level analysisSystem-level, compliance

When to use STRIDE:

When to use PASTA:

In practice, I often combine them: STRIDE for technical enumeration, PASTA’s business context for prioritization.


Hands-on Lab Scenarios

Lab 1: Basic Threat Model

Scenario: Model a password reset feature.

Components:

Exercise:

  1. Draw the DFD
  2. Identify trust boundaries
  3. Apply STRIDE to each element
  4. List top 5 threats with mitigations

Expected Output:

DFD:
┌──────┐  email    ( Reset   )  token  ═══════════
│ User │─────────>│ Service │────────>║ Token DB║
└──────┘          (         )         ═══════════
    │                  │
    │                  ▼ email
    │             [Email Service]
    │                  │
    │<────reset link───┘

    │  new password
    └────────────────>( Reset )───>═══════════
                      │ Service│    ║ User DB ║
                      (        )    ═══════════

Top Threats:
1. Token prediction (S) → Use cryptographic randomness
2. Token reuse (T) → One-time use, expiration
3. Email interception (I) → HTTPS links, short expiry
4. Brute force token (S) → Rate limiting, long tokens
5. Account enumeration (I) → Generic messages

Lab 2: Attack Tree Exercise

Scenario: Build an attack tree for “Compromise Admin Account.”

Goal: Compromise Admin Account
├── 1. Credential Attacks
│   ├── 1.1 Brute force
│   │   ├── 1.1.1 Dictionary attack
│   │   └── 1.1.2 Credential stuffing
│   ├── 1.2 Phishing
│   │   ├── 1.2.1 Spear phishing email
│   │   └── 1.2.2 Fake login page
│   └── 1.3 Credential theft
│       ├── 1.3.1 Keylogger
│       └── 1.3.2 Memory scraping

├── 2. Session Attacks
│   ├── 2.1 Session hijacking
│   │   ├── 2.1.1 XSS to steal token
│   │   └── 2.1.2 Network sniffing
│   └── 2.2 Session fixation

├── 3. Privilege Escalation
│   ├── 3.1 IDOR to admin functions
│   ├── 3.2 Role parameter tampering
│   └── 3.3 JWT claim manipulation

└── 4. Social Engineering
    ├── 4.1 Impersonate IT support
    └── 4.2 Physical access

Annotate with:
- Likelihood (H/M/L)
- Effort (H/M/L)
- Current mitigations
- Gaps

Lab 3: Microservices Threat Model

Scenario: Model a checkout flow with 3 services.

Services:
- Cart Service (manages shopping cart)
- Payment Service (processes payments)
- Order Service (creates orders)

Flow:
User → Cart → Payment → Order → User

Questions to answer:
1. What happens if Payment Service is compromised?
2. How do services authenticate to each other?
3. Where is PCI data flowing?
4. What's the blast radius of each service?

Tools and Resources

ToolPurposeLink
Microsoft Threat Modeling ToolDFD creation, STRIDEmicrosoft.com
OWASP Threat DragonOpen-source threat modelingthreatdragon.org
IriusRiskAutomated threat modelingiriusrisk.com
draw.ioDiagram creationdraw.io
MITRE ATT&CKThreat intelligenceattack.mitre.org

Threat Libraries

ResourceDescription
OWASP Top 10Web application threats
OWASP API Top 10API-specific threats
CWECommon weaknesses
CAPECAttack patterns
ATT&CKAdversary techniques

Common Mistakes

MistakeProblemFix
No trust boundariesMiss key threatsIdentify every context switch
Too high-levelThreats too genericDecompose to components
No prioritizationAnalysis paralysisUse DREAD or risk matrix
One-time exerciseOutdated modelIntegrate into SDLC
Security team onlyMissing contextInclude developers, architects

What’s Next?


Key Takeaways

  1. Start with data flows - You can’t protect what you don’t understand
  2. Trust boundaries matter most - Focus analysis where trust changes
  3. STRIDE is your friend - Systematic approach beats ad-hoc brainstorming
  4. Prioritize ruthlessly - Not all threats are equal
  5. Iterate continuously - Threat models are living documents
  6. Include developers - They know the system best

Share this post on:

Previous Post
Incident Response Playbooks for Security Engineers
Next Post
Securing CI/CD Pipelines: A Security Engineer's Guide