Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:38:26 +08:00
commit 41d9f6b189
304 changed files with 98322 additions and 0 deletions

View File

@@ -0,0 +1,216 @@
---
name: security-threat-model
description: Use when designing or reviewing systems handling sensitive data (PII, PHI, financial, auth credentials), building features with security implications (auth, payments, file uploads, APIs), preparing for security audits or compliance (PCI, HIPAA, SOC 2), investigating security incidents, integrating third-party services, or when user mentions "threat model", "security architecture", "STRIDE", "trust boundaries", "attack surface", or "security review".
---
# Security Threat Model
## Table of Contents
1. [Purpose](#purpose)
2. [When to Use](#when-to-use)
3. [What Is It](#what-is-it)
4. [Workflow](#workflow)
5. [STRIDE Framework](#stride-framework)
6. [Trust Boundary Mapping](#trust-boundary-mapping)
7. [Common Patterns](#common-patterns)
8. [Guardrails](#guardrails)
9. [Quick Reference](#quick-reference)
## Purpose
Security Threat Modeling systematically identifies vulnerabilities, threats, and mitigations for systems handling sensitive data. It transforms ad-hoc security thinking into structured analysis using STRIDE methodology, trust boundary mapping, and defense-in-depth principles.
## When to Use
**Invoke this skill when you need to:**
- Design secure architecture for systems handling sensitive data (PII, PHI, payment data, credentials)
- Review existing systems for security vulnerabilities before launch or audit
- Evaluate security implications of new features (auth, file uploads, APIs, integrations)
- Prepare for compliance requirements (PCI DSS, HIPAA, SOC 2, GDPR, FedRAMP)
- Investigate security incidents to identify root causes and prevent recurrence
- Assess third-party integration risks (OAuth, webhooks, data sharing)
- Document security posture for stakeholders, auditors, or customers
- Prioritize security improvements with limited resources
**User phrases that trigger this skill:**
- "Is this secure?"
- "What are the security risks?"
- "Threat model for [system]"
- "STRIDE analysis"
- "Trust boundaries"
- "Security review before launch"
- "Compliance requirements"
## What Is It
A structured security analysis that:
1. **Maps system architecture** (components, data flows, trust boundaries)
2. **Classifies data** (sensitivity levels, compliance requirements, lifecycle)
3. **Identifies threats** using STRIDE (Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege)
4. **Defines mitigations** (preventive controls, detective controls, corrective controls)
5. **Establishes monitoring** (alerts, audit logs, incident response)
6. **Prioritizes risks** (likelihood × impact, exploitability, compliance)
**Quick example (Password Reset Flow):**
- **Trust Boundaries**: User → Web Server → Email Service → Database
- **Data**: Email address (PII), reset token (credential), user ID
- **Threats**:
- **Spoofing**: Attacker requests reset for victim's email
- **Tampering**: Token modified in email link
- **Information Disclosure**: Token visible in logs/analytics
- **Denial of Service**: Mass reset requests exhaust email quota
- **Elevation of Privilege**: Reset token doesn't expire, reusable across sessions
- **Mitigations**: Rate limiting (5/hour), short-lived tokens (15 min), HTTPS only, email confirmation, account lockout after failed attempts, cryptographic token signing
## Workflow
Copy this checklist and track your progress:
```
Security Threat Model Progress:
- [ ] Step 1: Map system architecture and data flows
- [ ] Step 2: Identify trust boundaries
- [ ] Step 3: Classify data and compliance requirements
- [ ] Step 4: Apply STRIDE to identify threats
- [ ] Step 5: Define mitigations, monitoring, and prioritize risks
```
**Step 1: Map system architecture and data flows**
Document components, external services, users, data stores, and communication paths. See [Common Patterns](#common-patterns) for architecture examples. For straightforward systems → Use [resources/template.md](resources/template.md).
**Step 2: Identify trust boundaries**
Mark where data crosses security domains (user → server, server → database, internal → third-party). See [Trust Boundary Mapping](#trust-boundary-mapping) for boundary types.
**Step 3: Classify data and compliance requirements**
Rate data sensitivity (public, internal, confidential, restricted), identify PII/PHI/PCI, document compliance obligations (GDPR, HIPAA, PCI DSS). See [resources/template.md](resources/template.md) for classification tables.
**Step 4: Apply STRIDE to identify threats**
For each trust boundary and data flow, systematically check all six STRIDE threat categories. See [STRIDE Framework](#stride-framework) for threat identification. For complex systems with multiple attack surfaces → Study [resources/methodology.md](resources/methodology.md) for advanced attack tree analysis and DREAD scoring.
**Step 5: Define mitigations, monitoring, and prioritize risks**
Propose preventive/detective/corrective controls, establish monitoring and alerting, prioritize by risk score (likelihood × impact). Self-check using [resources/evaluators/rubric_security_threat_model.json](resources/evaluators/rubric_security_threat_model.json). Minimum standard: Average score ≥ 3.5.
## STRIDE Framework
**S - Spoofing Identity**
- **Threat**: Attacker impersonates legitimate user or system
- **Examples**: Stolen credentials, session hijacking, caller ID spoofing, email spoofing
- **Mitigations**: Multi-factor authentication, certificate validation, cryptographic signatures, mutual TLS
**T - Tampering with Data**
- **Threat**: Unauthorized modification of data in transit or at rest
- **Examples**: Man-in-the-middle attacks, SQL injection, file modification, message replay
- **Mitigations**: HTTPS/TLS, input validation, parameterized queries, digital signatures, checksums, immutable storage
**R - Repudiation**
- **Threat**: User denies performing action, no proof of activity
- **Examples**: Deleted logs, unsigned transactions, missing audit trails
- **Mitigations**: Comprehensive audit logging, digital signatures on transactions, tamper-proof logs, third-party timestamping
**I - Information Disclosure**
- **Threat**: Exposure of sensitive information to unauthorized parties
- **Examples**: Database dumps, verbose error messages, unencrypted backups, API over-fetching
- **Mitigations**: Encryption at rest/in transit, access control, data minimization, secure deletion, redaction in logs
**D - Denial of Service**
- **Threat**: System becomes unavailable or degraded
- **Examples**: Resource exhaustion, distributed attacks, algorithmic complexity exploits, storage filling
- **Mitigations**: Rate limiting, auto-scaling, circuit breakers, input size limits, CDN/DDoS protection
**E - Elevation of Privilege**
- **Threat**: Attacker gains unauthorized access or permissions
- **Examples**: SQL injection to admin, IDOR to other user data, path traversal, privilege escalation bugs
- **Mitigations**: Principle of least privilege, input validation, authorization checks on every request, role-based access control
## Trust Boundary Mapping
**Trust boundary**: Where data crosses security domains with different trust levels.
**Common boundaries:**
- **User → Application**: Untrusted input enters system (validate, sanitize, rate limit)
- **Application → Database**: Application credentials vs. user permissions (parameterized queries, connection pooling)
- **Internal → External Service**: Data leaves your control (encryption, audit logging, contract terms)
- **Public → Private Network**: Internet to internal systems (firewall, VPN, API gateway)
- **Client-side → Server-side**: JavaScript to backend (never trust client, re-validate server-side)
- **Privileged → Unprivileged Code**: Admin functions vs. user code (isolation, separate processes, security boundaries)
**Boundary analysis questions:**
- What data crosses this boundary? (classify sensitivity)
- Who/what is on each side? (authentication, authorization)
- What could go wrong at this crossing? (apply STRIDE)
- What controls protect this boundary? (authentication, encryption, validation, rate limiting)
## Common Patterns
**Pattern 1: Web Application with Database**
- **Boundaries**: User ↔ Web Server ↔ Database
- **Critical threats**: SQLi (Tampering), XSS (Spoofing), CSRF (Spoofing), session hijacking (Spoofing), IDOR (Elevation of Privilege)
- **Key mitigations**: Parameterized queries, CSP headers, CSRF tokens, HttpOnly/Secure cookies, authorization checks
**Pattern 2: API with Third-Party OAuth**
- **Boundaries**: User ↔ Frontend ↔ API Server ↔ OAuth Provider ↔ Third-Party API
- **Critical threats**: Token theft (Spoofing), scope creep (Elevation of Privilege), authorization code interception, redirect URI manipulation
- **Key mitigations**: PKCE for public clients, state parameter validation, token rotation, minimal scopes, HTTPS only
**Pattern 3: Microservices Architecture**
- **Boundaries**: API Gateway ↔ Service A ↔ Service B ↔ Message Queue ↔ Database
- **Critical threats**: Service impersonation (Spoofing), lateral movement (Elevation of Privilege), message tampering (Tampering), service enumeration (Information Disclosure)
- **Key mitigations**: mTLS between services, service mesh, API authentication per service, network policies, least privilege IAM
**Pattern 4: File Upload Service**
- **Boundaries**: User ↔ Upload Handler ↔ Virus Scanner ↔ Object Storage
- **Critical threats**: Malware upload (Tampering), path traversal (Information Disclosure), file overwrite (Tampering), storage exhaustion (DoS)
- **Key mitigations**: File type validation (magic bytes not extension), size limits, virus scanning, unique file naming, separate storage domain
**Pattern 5: Mobile App with Backend API**
- **Boundaries**: Mobile App ↔ API Gateway ↔ Backend Services
- **Critical threats**: API key extraction (Information Disclosure), certificate pinning bypass (Tampering), local data theft (Information Disclosure), reverse engineering
- **Key mitigations**: Certificate pinning, ProGuard/R8 obfuscation, biometric auth, local encryption (Keychain/Keystore), root/jailbreak detection
## Guardrails
**Assume breach mindset:**
- Don't ask "can attacker get in?" but "when attacker gets in, what damage can they do?"
- Defense in depth: Multiple overlapping controls, no single point of failure
- Least privilege: Minimal permissions by default, explicit grants only
**Prioritize realistically:**
- Focus on high-value assets (customer data, credentials, financial data) first
- Address compliance-critical threats (PCI, HIPAA) before nice-to-haves
- Balance security cost vs. risk (don't over-engineer low-risk systems)
**Avoid security theater:**
- **Security theater**: Controls that feel secure but don't meaningfully reduce risk (e.g., password complexity without rate limiting = still vulnerable to credential stuffing)
- **Effective security**: Address actual threat vectors with measurable risk reduction
**Document assumptions:**
- "Assumes database is not publicly accessible" (validate with network config)
- "Assumes TLS 1.2+ enforced" (verify in load balancer settings)
- "Assumes environment variables protected" (confirm secrets management)
**Update threat model:**
- Threat models decay (new features, new attack techniques, infrastructure changes)
- Review quarterly or when architecture changes significantly
- Incorporate lessons from incidents and security research
## Quick Reference
**Resources:**
- **Quick threat model**: [resources/template.md](resources/template.md)
- **Advanced techniques**: [resources/methodology.md](resources/methodology.md) (attack trees, DREAD scoring, abuse cases)
- **Quality rubric**: [resources/evaluators/rubric_security_threat_model.json](resources/evaluators/rubric_security_threat_model.json)
**5-Step Process**: Map Architecture → Identify Boundaries → Classify Data → Apply STRIDE → Mitigate & Monitor
**STRIDE**: Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, Elevation of Privilege
**Trust Boundaries**: User→App, App→DB, Internal→External, Public→Private, Client→Server, Privileged→Unprivileged
**Mitigation Types**: Preventive (block attacks), Detective (identify attacks), Corrective (respond to attacks)
**Prioritization**: High-value assets first, compliance-critical threats, realistic risk vs. cost balance

View File

@@ -0,0 +1,172 @@
{
"name": "Security Threat Model Evaluator",
"description": "Evaluates security threat models for architecture clarity, STRIDE coverage, mitigation completeness, risk prioritization, and actionability",
"criteria": [
{
"name": "Architecture & Boundary Mapping",
"weight": 1.4,
"scale": {
"1": "No architecture diagram, components vague ('the server', 'database'), trust boundaries not identified",
"2": "Basic diagram but missing external dependencies (third-party services, cloud providers), boundaries mentioned but not analyzed",
"3": "Architecture documented with main components, some boundaries identified (user→server, server→DB) but network zones unclear",
"4": "Clear architecture diagram, all components with tech stack, trust boundaries marked, network zones (DMZ/VPC/Internet) specified",
"5": "Exemplary: Comprehensive architecture (component diagram with ASCII art or visual), all components with specific versions (PostgreSQL 13, Node 16), data flows documented (numbered DF1, DF2...), all trust boundaries explicitly marked and analyzed, network zones clear (public/DMZ/private), external dependencies fully documented (SaaS, APIs, auth providers), authentication methods specified per boundary"
}
},
{
"name": "Data Classification Completeness",
"weight": 1.3,
"scale": {
"1": "No data classification, no mention of PII/PHI/PCI, compliance requirements unknown",
"2": "Some data elements listed but not classified (sensitive vs public), compliance mentioned vaguely ('we need to be compliant')",
"3": "Data classified (internal/confidential) but PII/PHI/PCI not specifically identified, retention/encryption not documented",
"4": "All data elements classified (public/internal/confidential/restricted), PII/PHI/PCI identified, compliance requirements stated (GDPR, HIPAA, PCI DSS)",
"5": "Exemplary: Comprehensive data inventory with sensitivity classification (4 levels: public/internal/confidential/restricted), specific compliance mapped to data (GDPR for PII, HIPAA for PHI, PCI DSS for payment data), retention policies documented (7 years, until deletion, 90 days), encryption requirements (at rest/in transit/both), data lifecycle (creation, storage, transmission, deletion), data in logs/analytics/backups not forgotten"
}
},
{
"name": "STRIDE Coverage & Rigor",
"weight": 1.5,
"scale": {
"1": "STRIDE not applied, or only 1-2 categories checked (e.g., only Spoofing and Tampering), no systematic analysis",
"2": "STRIDE mentioned but incomplete (3-4 categories), not applied to all trust boundaries, threats vague ('attacker could break in')",
"3": "STRIDE applied to most boundaries with 5-6 categories, some threats identified but likelihood/impact not scored",
"4": "STRIDE systematically applied to all trust boundaries (all 6 categories), threats specific (not vague), likelihood and impact scored",
"5": "Exemplary: STRIDE comprehensively applied to every trust boundary crossing and critical component (all 6 categories: Spoofing, Tampering, Repudiation, Information Disclosure, DoS, Elevation of Privilege), threats specific with attack scenarios (not 'could be compromised' but 'SQL injection via login form allows data exfiltration'), likelihood scored (1-5 with justification), impact scored (1-5 with business consequence), risk score calculated (likelihood × impact), no categories skipped (addressed Repudiation with audit logging, etc.)"
}
},
{
"name": "Mitigation Depth & Defense in Depth",
"weight": 1.5,
"scale": {
"1": "No mitigations proposed, or generic ('use encryption', 'add security'), no distinction between preventive/detective/corrective",
"2": "Some mitigations listed but vague ('better validation', 'secure the API'), no implementation details, no monitoring",
"3": "Mitigations proposed with some specifics (parameterized queries, HTTPS) but only preventive controls, detective/corrective missing",
"4": "Specific mitigations for major threats (preventive controls with implementation), detective controls (monitoring, alerts) included",
"5": "Exemplary: Comprehensive defense-in-depth strategy with preventive (TLS 1.2+, parameterized queries, input validation with specific libraries/methods), detective (CloudWatch alarms on failed auth >5/5min, SQL injection attempt logging, geo-impossible travel detection), and corrective controls (incident response plan with RTO/RPO, backup restoration procedures, credential rotation runbooks), mitigations mapped to specific STRIDE threats, implementation details (not 'use MFA' but 'AWS IAM MFA with TOTP, enforced via policy'), monitoring thresholds quantified"
}
},
{
"name": "Risk Prioritization & Scoring",
"weight": 1.4,
"scale": {
"1": "No risk prioritization, all threats treated equally, no scoring (likelihood/impact)",
"2": "Some threats called 'high priority' but no quantitative scoring, prioritization seems arbitrary",
"3": "Basic risk scoring (Low/Med/High) but no multiplication (likelihood × impact), unclear how priorities set",
"4": "Risk scores calculated (likelihood × impact = 1-25), threats prioritized by score, top 3-5 risks identified",
"5": "Exemplary: Quantitative risk scoring (likelihood 1-5 × impact 1-5 = risk score 1-25), clear thresholds (P0: ≥20, P1: 12-19, P2: 6-11, P3: 1-5), all threats scored and prioritized, top 3-5 critical risks highlighted with action items, residual risk assessed post-mitigation (Medium→Low after controls), accepted risks explicitly documented with rationale (e.g., 'CSRF on read-only GET endpoints accepted, low impact, cost of tokens outweighs risk')"
}
},
{
"name": "Actionability & Ownership",
"weight": 1.3,
"scale": {
"1": "No action items, threat model is analysis only with no next steps, no owners assigned",
"2": "Vague recommendations ('improve security', 'add monitoring') but no concrete actions, no owners or deadlines",
"3": "Some action items with owners but no deadlines, or deadlines without prioritization",
"4": "Clear action items with owners and deadlines, prioritized by risk (P0/P1/P2), status tracked (Done/In Progress/TODO)",
"5": "Exemplary: Concrete action items (not 'fix SQLi' but 'Manual code review of all SQL queries for parameterized query usage, add automated SQLMap scan to CI/CD'), named owners (Engineering, DevOps, Security with specific people if known), deadlines (2 weeks, 1 month, immediate), prioritized (P0/P1/P2 mapped to risk scores), status indicators (✓ Done, ⚠ Partial, 🔴 TODO, 🟡 In Progress), mitigation status per threat documented, review date set (quarterly or after architecture changes)"
}
},
{
"name": "Compliance Alignment",
"weight": 1.2,
"scale": {
"1": "No mention of compliance requirements (GDPR, HIPAA, PCI, SOC 2), unclear if system handles regulated data",
"2": "Compliance mentioned but not mapped to threats or mitigations (e.g., 'we're PCI compliant' but no PCI-specific controls documented)",
"3": "Compliance requirements identified (GDPR for PII, PCI for payment data) but controls not fully mapped (missing audit logging, encryption gaps)",
"4": "Compliance requirements documented, key controls mapped (PCI: no CVV storage, encryption, quarterly scans), audit trail addressed",
"5": "Exemplary: All compliance requirements identified and mapped to data/systems (GDPR: consent management, right to deletion, breach notification <72hr; PCI DSS: tokenization, no CVV storage, quarterly ASV scans, annual audit; HIPAA: PHI encryption, access controls, audit logs; SOC 2: change management, access reviews), controls explicitly aligned with compliance frameworks (e.g., 'Encryption at rest (AES-256) satisfies GDPR Article 32, HIPAA 164.312(a)(2)(iv), PCI DSS 3.4'), gaps identified ('need to implement GDPR right-to-delete API')"
}
},
{
"name": "Monitoring & Incident Response",
"weight": 1.2,
"scale": {
"1": "No monitoring or alerting defined, no incident response plan, unclear how attacks would be detected",
"2": "Generic monitoring mentioned ('we have logs') but no specific alerts, no incident response procedures",
"3": "Some monitoring defined (CloudWatch, Datadog) with basic alerts (CPU >80%) but no security-specific alerts (failed auth, SQLi attempts), no IR plan",
"4": "Security monitoring with specific alerts (failed login >5/5min, SQLi pattern detected, geo-impossible travel), incident response runbook exists",
"5": "Exemplary: Comprehensive detective controls (failed auth monitoring with threshold >5/5min→auto-block IP, SQLi attempt logging→security review, unusual data access→throttle user, privilege escalation→block+review, DDoS detection→Shield activation, backup integrity checks→page on-call), alert thresholds quantified, incident response plans (Database compromise: restore from backup <4hr RTO, rotate creds; DDoS: Shield Advanced + WAF tuning <15min; Credential leak: rotate secrets <1hr, force password resets; Data breach: IR plan + legal notification <72hr GDPR), runbooks tested (quarterly DDoS drill, tabletop data breach exercise), audit log retention (1 year SOC 2), immutable logs (S3 object lock)"
}
}
],
"guidance": {
"by_system_type": {
"web_application": {
"critical_threats": "SQLi (Tampering), XSS (Spoofing), CSRF (Spoofing), session hijacking (Spoofing), IDOR (Elevation of Privilege), information disclosure via errors",
"key_boundaries": "User→Web Server (untrusted input), Web Server→Database (SQLi risk), Client→Server (XSS/CSRF), Internal→External APIs (data exfiltration)",
"essential_mitigations": "Parameterized queries, CSP headers, CSRF tokens, HttpOnly/Secure cookies, input validation, authorization checks, TLS 1.2+",
"compliance_focus": "GDPR (if EU users), PCI DSS (if payment data), SOC 2 (B2B SaaS)"
},
"mobile_app": {
"critical_threats": "Certificate pinning bypass (Tampering), local data theft (Information Disclosure), API key extraction (Information Disclosure), reverse engineering, jailbreak detection bypass",
"key_boundaries": "Mobile App→API (certificate pinning), App→Local Storage (encryption), User→App (biometric auth)",
"essential_mitigations": "Certificate pinning, ProGuard/R8 obfuscation, Keychain/Keystore, biometric auth, no secrets in code, root/jailbreak detection",
"compliance_focus": "GDPR (PII in app), COPPA (if children's app), HIPAA (if health data)"
},
"cloud_infrastructure": {
"critical_threats": "IAM misconfiguration (Elevation of Privilege), public S3 bucket (Information Disclosure), credential theft from metadata (Spoofing), security group override (Tampering), cost attack (DoS)",
"key_boundaries": "Internet→API Gateway (DDoS), Service→Service (lateral movement), Service→S3/DB (data access), IAM roles (privilege boundaries)",
"essential_mitigations": "Least privilege IAM, IMDSv2, S3 bucket policies (private), security groups, CloudTrail, Config rules, encryption at rest, VPC endpoints",
"compliance_focus": "SOC 2 (cloud controls), FedRAMP (government), ISO 27001 (international)"
},
"api_service": {
"critical_threats": "BOLA/IDOR (Elevation of Privilege), API key theft (Spoofing), rate limit bypass (DoS), over-fetching (Information Disclosure), mass assignment (Tampering), OAuth scope creep",
"key_boundaries": "Client→API (authentication), API→Database (authorization), API→Third-Party (OAuth)",
"essential_mitigations": "API authentication (key/OAuth), authorization per endpoint, rate limiting, field-level permissions (GraphQL), CORS, input validation, audit logging",
"compliance_focus": "GDPR (data minimization), HIPAA (if PHI in API), PCI DSS (if payment data)"
}
}
},
"common_failure_modes": {
"incomplete_stride": {
"symptom": "Only 2-3 STRIDE categories applied (usually Spoofing, Tampering, DoS), Repudiation and Information Disclosure skipped",
"root_cause": "Not systematically checking all 6 categories for each boundary, assuming 'we don't have repudiation issues' without thinking through audit requirements",
"fix": "Create checklist: For each trust boundary, explicitly ask all 6 STRIDE questions. Repudiation → audit logging. Information Disclosure → check logs/errors/backups for PII."
},
"missing_trust_boundaries": {
"symptom": "Only obvious boundary (user→server) analyzed, internal boundaries (server→DB, service→service) missed",
"root_cause": "Thinking threats only come from external attackers, not considering lateral movement or insider threats",
"fix": "Map all data flows, mark every point where data crosses security domains (authentication change, encryption boundary, network zone, privilege level)"
},
"vague_mitigations": {
"symptom": "Mitigations like 'use encryption', 'add security', 'validate input' without specifics",
"root_cause": "Not thinking through implementation details, treating threat model as high-level only",
"fix": "Specify: 'TLS 1.2+ enforced via ALB listener policy', 'Joi schema validation on all POST/PUT endpoints', 'AES-256 encryption at rest via RDS setting'"
},
"no_monitoring": {
"symptom": "Only preventive controls (firewalls, encryption), no detective controls (alerts, logging), no incident response",
"root_cause": "Assume breach mindset not applied, thinking 'if we prevent, we don't need to detect'",
"fix": "For each high-risk threat, define: How would we detect this? What alert fires? Who responds? What's the runbook?"
},
"compliance_afterthought": {
"symptom": "Compliance mentioned but not integrated (e.g., 'we're HIPAA compliant' but no PHI encryption documented, no audit logs)",
"root_cause": "Treating compliance as checkbox, not understanding specific technical requirements",
"fix": "Map compliance framework to controls: GDPR→consent+deletion+breach notification, PCI→tokenization+encryption+no CVV, HIPAA→PHI encryption+access logs+BAA"
},
"static_threat_model": {
"symptom": "Threat model created once, never updated, doesn't reflect current architecture",
"root_cause": "Treating threat model as one-time deliverable, not living document",
"fix": "Set review cadence (quarterly or when architecture changes), track threat model version, integrate into change management (new feature = update threat model)"
}
},
"excellence_indicators": [
"Architecture diagram clear with all components, data flows numbered, trust boundaries marked",
"All data elements classified (sensitivity + compliance), retention and encryption documented",
"STRIDE systematically applied to every trust boundary (all 6 categories)",
"Threats specific with attack scenarios, not vague ('SQL injection via login form user_id parameter')",
"Likelihood and impact scored (1-5), risk score calculated (L×I)",
"Mitigations defense-in-depth: preventive + detective + corrective controls",
"Mitigations specific with implementation ('Parameterized queries via Sequelize ORM, no raw SQL')",
"Monitoring defined with quantified thresholds (>5 failed logins/5min→auto-block IP)",
"Incident response plans with RTO/RPO (Database restore <4hr RTO, <24hr RPO)",
"Risk prioritization (P0/P1/P2) with top 3-5 critical risks highlighted",
"Action items concrete, named owners, deadlines, priority, status tracked",
"Compliance requirements mapped to controls (GDPR Article 32→encryption at rest)",
"Accepted risks explicitly documented with rationale",
"Review date set (quarterly or after major architecture changes)",
"Assumptions documented ('Assumes TLS 1.2+ enforced—verify in ALB config')",
"Threat model would survive security audit (specific, comprehensive, actionable)"
]
}

View File

@@ -0,0 +1,447 @@
# Security Threat Model: Advanced Methodologies
## Table of Contents
1. [Attack Trees & Attack Graphs](#1-attack-trees--attack-graphs)
2. [DREAD Risk Scoring](#2-dread-risk-scoring)
3. [Abuse Cases & Misuse Stories](#3-abuse-cases--misuse-stories)
4. [Data Flow Diagrams (DFD) for Threat Modeling](#4-data-flow-diagrams-dfd-for-threat-modeling)
5. [Threat Intelligence Integration](#5-threat-intelligence-integration)
6. [Advanced STRIDE Patterns](#6-advanced-stride-patterns)
## 1. Attack Trees & Attack Graphs
### Attack Tree Construction
**Attack tree**: Hierarchical diagram showing how security goals can be defeated through combinations of attacks.
**Structure**:
- **Root** (top): Attacker's goal (e.g., "Steal customer credit card data")
- **Nodes**: Sub-goals or attack steps
- **Leaves** (bottom): Atomic attacks (individual exploits)
- **AND nodes**: All child attacks must succeed (serial gates)
- **OR nodes**: Any child attack succeeds (parallel gates)
**Example (Steal Credit Card Data)**:
```
[Steal CC Data] (ROOT - OR)
├── [Compromise Database] (AND)
│ ├── [Gain network access] (OR)
│ │ ├── Phish employee for VPN creds
│ │ └── Exploit public-facing vulnerability
│ └── [Escalate privileges to DBA] (OR)
│ ├── SQL injection → shell → lateral movement
│ └── Steal DB credentials from secrets file
├── [Intercept in Transit] (AND)
│ ├── [MITM between user and server] (OR)
│ │ ├── Compromise WiFi router
│ │ └── BGP hijacking (sophisticated)
│ └── [Decrypt TLS] (OR)
│ ├── Steal server private key
│ └── Downgrade to weak cipher (if supported)
└── [Social Engineering] (OR)
├── Phish customer directly for CC
└── Compromise customer support → access CC vault
```
**Leaf Attack Attributes**:
- **Difficulty**: Low (script kiddie), Medium (skilled attacker), High (APT)
- **Cost**: $0-100, $100-10K, $10K+ (attacker resources)
- **Detection Likelihood**: Low (0-30%), Medium (30-70%), High (70-100%)
- **Impact**: If this leaf succeeds, what's compromised?
**Analysis**:
- **Most likely path**: Lowest combined difficulty + cost
- **Stealthiest path**: Lowest combined detection likelihood
- **Critical leaves**: Appear in multiple paths (defend these first)
**Mitigation Strategy**:
- **Prune OR nodes**: Block at least one child (breaks that path)
- **Strengthen AND nodes**: Make any one child infeasible (breaks entire branch)
- **Monitor leaves**: Add detection at leaf level (early warning)
### Attack Graph Analysis
**Attack graph**: Network-level visualization showing how attacker moves laterally.
**Components**:
- **Nodes**: Network hosts (web server, DB, workstation)
- **Edges**: Exploits that allow movement between nodes
- **Entry points**: Internet-facing hosts (start nodes)
- **Crown jewels**: High-value targets (end nodes)
**Example**:
```
[Internet] → [Web Server] (SQLi) → [App Server] (lateral via shared subnet)
[Database] (DB creds in config file)
```
**Path Analysis**:
- **Shortest path**: Fewest hops to crown jewels
- **Easiest path**: Lowest aggregate difficulty
- **Most likely path**: Attacker's expected route (probability-weighted)
**Mitigations**:
- **Network segmentation**: Break edges (VLANs, security groups, air gaps)
- **Least privilege**: Reduce accessible edges from each node
- **Defense in depth**: Require multiple successful exploits per path
## 2. DREAD Risk Scoring
**DREAD**: Microsoft's risk scoring model for prioritizing threats.
### Scoring Criteria (1-10 scale)
**D - Damage Potential**
- 1-3: Minor impact (single user affected, limited data)
- 4-7: Significant impact (many users, sensitive data)
- 8-10: Catastrophic (all users, regulated data breach, life-safety)
**R - Reproducibility**
- 1-3: Hard to reproduce (race condition, specific timing)
- 4-7: Moderate (requires specific configuration, some skill)
- 8-10: Trivial (works every time, no special conditions)
**E - Exploitability**
- 1-3: Very difficult (requires custom exploit, deep expertise)
- 4-7: Moderate (exploit code available, requires adaptation)
- 8-10: Trivial (point-and-click tool, no skill needed)
**A - Affected Users**
- 1-3: Minimal (single user, admin only, specific config)
- 4-7: Moderate (some users, default install, optional feature)
- 8-10: All users (default config, core functionality)
**D - Discoverability**
- 1-3: Obscure (requires source code audit, specific knowledge)
- 4-7: Moderate (found through scanning, disclosed vulnerability)
- 8-10: Obvious (visible in UI, publicly documented, automated scanners find it)
### Calculating DREAD Score
**Formula**: (Damage + Reproducibility + Exploitability + Affected Users + Discoverability) / 5
**Example (SQL Injection in Login Form)**:
- **Damage**: 10 (full database access, PII breach)
- **Reproducibility**: 10 (always works with same payload)
- **Exploitability**: 8 (SQLMap automates it, some skill needed)
- **Affected Users**: 10 (all users, login is core functionality)
- **Discoverability**: 9 (login forms are obvious attack surface, scanners find it)
- **DREAD Score**: (10+10+8+10+9)/5 = **9.4** (Critical)
**Example (Admin API without rate limiting)**:
- **Damage**: 7 (can enumerate accounts, some PII)
- **Reproducibility**: 10 (always works)
- **Exploitability**: 10 (trivial, just send requests)
- **Affected Users**: 6 (admin API, limited exposure)
- **Discoverability**: 5 (requires knowledge of API endpoint, not in public docs)
- **DREAD Score**: (7+10+10+6+5)/5 = **7.6** (High)
### Using DREAD for Prioritization
**Thresholds**:
- **9.0-10.0**: Critical (P0, fix immediately)
- **7.0-8.9**: High (P1, fix this sprint)
- **5.0-6.9**: Medium (P2, backlog priority)
- **3.0-4.9**: Low (P3, monitor, accept risk)
- **1.0-2.9**: Minimal (P4, informational)
**Advantages**:
- Quantitative scoring aids prioritization
- Granular (1-10 scale) vs. coarse (Low/Med/High)
- Factors in exploitability and discoverability (not just impact)
**Limitations**:
- Subjective (scorers may disagree)
- Doesn't account for existing mitigations (score pre-mitigation threat)
- "Discoverability" less relevant in post-disclosure world (assume all vulns are known)
## 3. Abuse Cases & Misuse Stories
### Abuse Cases
**Abuse case**: Scenario where functionality is misused for malicious purposes (not a bug, feature used as weapon).
**Structure**:
- **Actor**: Who abuses (insider, competitor, attacker)
- **Goal**: What they want (exfiltrate data, disrupt service, frame someone)
- **Preconditions**: What they need (account, network access, knowledge)
- **Steps**: How they abuse the feature
- **Result**: What damage occurs
- **Mitigation**: How to detect or prevent
**Example (Bulk Data Export Feature)**:
**Abuse Case**: Insider data exfiltration
- **Actor**: Disgruntled employee with valid credentials
- **Goal**: Steal entire customer database before leaving company
- **Preconditions**: Login access, export feature available to all users
- **Steps**:
1. Log in with legitimate credentials
2. Navigate to export page
3. Select "All customers" (no pagination limit)
4. Click "Export to CSV"
5. Download 10M customer records
6. Upload to competitor or dark web
- **Result**: Massive data breach, GDPR violation, competitive damage
- **Mitigation**:
- **Detective**: Audit log for large exports, alert on exports >1000 records
- **Preventive**: Require manager approval for exports >100 records
- **Corrective**: Watermark exports with user ID (attribution), DLP to prevent upload
### Misuse Stories (Agile Format)
**Misuse story**: Agile user story from attacker's perspective.
**Format**: "As a [attacker type], I want to [malicious action], so that I can [attacker goal]"
**Example**:
- "As a **script kiddie**, I want to **enumerate valid usernames through password reset**, so that I can **target credential stuffing attacks**"
- **Mitigation**: Generic error messages ("If that email exists, we sent a reset link"), rate limiting
- "As a **competitor**, I want to **scrape all product prices and descriptions**, so that I can **undercut pricing**"
- **Mitigation**: Rate limiting, CAPTCHA, robots.txt, legal terms of service, API authentication
- "As a **disgruntled ex-employee**, I want to **use my old credentials that weren't revoked**, so that I can **delete critical data for revenge**"
- **Mitigation**: Offboarding checklist (revoke all access day 1), audit logs, backups, immutable delete (soft delete with retention)
### Misuse Case Matrix
| Feature | Legitimate Use | Misuse | Mitigation |
|---------|----------------|--------|-----------|
| Search | Find products | Enumerate database, injection testing | Rate limiting, parameterized queries, no PII in results |
| File upload | Share documents | Malware upload, path traversal, storage DoS | File type validation (magic bytes), size limits, virus scan, separate domain |
| Admin panel | Manage system | Privilege escalation, mass data modification | Strong auth (MFA), audit logs, confirmation dialogs, IP whitelisting |
| API | Integrate systems | Credential theft, rate limit bypass, cost attacks | API key rotation, quota limits, cost caps, monitoring |
| Commenting | User feedback | Spam, XSS, phishing links, hate speech | Content filtering, CAPTCHA, XSS prevention (CSP), moderation queue |
## 4. Data Flow Diagrams (DFD) for Threat Modeling
### DFD Levels
**Level 0 (Context Diagram)**:
- High-level: System as single process, external entities only
- Use for: Executive overview, scope definition
**Level 1 (Major Components)**:
- Shows: Main processes, data stores, external entities, trust boundaries
- Use for: STRIDE analysis at component level
**Level 2+ (Detailed)**:
- Decomposes: Level 1 processes into sub-processes
- Use for: Deep dive on critical components (auth, payment, data handling)
### DFD Elements
**Symbols**:
- **External Entity** (rectangle): User, third-party service, external system
- **Process** (circle): Component that transforms data (web server, API, background job)
- **Data Store** (parallel lines): Database, file system, cache, queue
- **Data Flow** (arrow): Data moving between elements (HTTP request, DB query, file read)
- **Trust Boundary** (dotted line box): Security domain boundary
**Example (Login Flow - Level 1)**:
```
[User] ---(email, password)---> [Web Server] ---(credentials)---> [Database]
| |
|<--(user record, hashed pw)---|
|
|---(session token)---> [Redis Cache]
```
**Trust boundaries**:
- User ↔ Web Server (untrusted → trusted, validate all input)
- Web Server ↔ Database (application → data layer, parameterized queries)
### Applying STRIDE to DFD
**For each element type, ask specific STRIDE questions**:
**External Entity**:
- **Spoofing**: Can attacker impersonate this entity? (auth required?)
- **Repudiation**: Can entity deny actions? (audit logging?)
**Process**:
- **Tampering**: Can attacker modify process logic? (code signing, integrity checks?)
- **Information Disclosure**: Does process leak sensitive data in logs/errors?
- **Denial of Service**: Can attacker crash/exhaust this process?
- **Elevation of Privilege**: Can attacker gain higher permissions through this process?
**Data Store**:
- **Tampering**: Can attacker modify stored data? (access control, integrity checks?)
- **Information Disclosure**: Can attacker read sensitive data? (encryption at rest, access control?)
- **Denial of Service**: Can attacker fill/corrupt data store?
**Data Flow**:
- **Tampering**: Can attacker modify data in transit? (TLS, message signing?)
- **Information Disclosure**: Can attacker eavesdrop? (encryption in transit?)
- **Denial of Service**: Can attacker block/flood this flow?
### DFD-Based Threat Enumeration
**Systematic approach**:
1. Draw DFD with trust boundaries
2. Number each data flow (DF1, DF2, ...)
3. For each flow crossing trust boundary, apply STRIDE
4. For each process, apply STRIDE
5. For each data store with sensitive data, apply Tampering + Information Disclosure
6. Document threats in spreadsheet (DFD element, STRIDE category, threat description, mitigation)
**Example**:
| DFD Element | Trust Boundary | STRIDE | Threat | Likelihood | Impact | Mitigation |
|-------------|----------------|--------|--------|------------|--------|-----------|
| DF1: User → Web Server | Yes (external → internal) | Spoofing | CSRF attack using stolen session cookie | Medium | High | CSRF tokens, SameSite cookies |
| DF1: User → Web Server | Yes | Tampering | MITM modifies login request | Low | High | HTTPS, HSTS |
| P1: Web Server | No | Elevation of Privilege | SQLi escalates to admin via DB access | Medium | Critical | Parameterized queries, least privilege DB user |
| DS1: Database | No | Information Disclosure | Backup left public on S3 | Low | Critical | S3 bucket policy (private), encryption |
## 5. Threat Intelligence Integration
### MITRE ATT&CK Mapping
**MITRE ATT&CK**: Knowledge base of adversary tactics and techniques observed in real-world attacks.
**Tactics** (why): Initial Access, Execution, Persistence, Privilege Escalation, Defense Evasion, Credential Access, Discovery, Lateral Movement, Collection, Exfiltration, Impact
**Example Mapping**:
| System Feature | ATT&CK Technique | Mitigation |
|----------------|------------------|-----------|
| Web application login | T1078 (Valid Accounts) | MFA, account lockout, monitoring |
| API with OAuth | T1550 (Use Alternate Authentication Material - token theft) | Short-lived tokens, token rotation, secure storage |
| File upload | T1105 (Ingress Tool Transfer - upload malware) | File type validation, virus scanning |
| Admin panel | T1078.003 (Valid Accounts: Local Accounts) | Principle of least privilege, MFA, audit logs |
| Database backups | T1530 (Data from Cloud Storage Object) | Encryption, private buckets, access logging |
**Using ATT&CK**:
- **Threat modeling input**: Browse ATT&CK for tactics relevant to your system (e.g., "Initial Access" for Internet-facing apps)
- **Red teaming**: Use ATT&CK techniques to simulate attacks during testing
- **Detection engineering**: Map ATT&CK techniques to monitoring rules (e.g., T1078 → alert on failed login spike)
### CVE/CWE Mapping
**CWE (Common Weakness Enumeration)**: Catalog of software weaknesses.
**Top CWEs** (CWE Top 25):
- CWE-79: Cross-Site Scripting (XSS)
- CWE-89: SQL Injection
- CWE-20: Improper Input Validation
- CWE-78: OS Command Injection
- CWE-190: Integer Overflow
- CWE-352: CSRF
- CWE-22: Path Traversal
- CWE-798: Hard-coded Credentials
**CVE (Common Vulnerabilities and Exposures)**: Specific vulnerabilities in specific products.
**Integration**:
- **Dependency scanning**: Identify CVEs in third-party libraries (npm audit, Snyk, Dependabot)
- **Patch management**: Prioritize CVEs with public exploits (CVSS ≥7.0, exploited in wild)
- **Threat model coverage**: Ensure threat model addresses CWE Top 25 for your language/framework
## 6. Advanced STRIDE Patterns
### STRIDE for Cloud Infrastructure
**Cloud-specific threats**:
**Spoofing**:
- **IAM role assumption**: Attacker assumes role with excessive permissions
- **Instance metadata service (IMDS)**: Attacker fetches IAM credentials from EC2 metadata
- **Mitigation**: Least privilege IAM, IMDSv2 (session-based), instance profile credential rotation
**Tampering**:
- **S3 bucket policy override**: Attacker modifies bucket to public
- **Security group modification**: Attacker opens firewall rules
- **Mitigation**: AWS Config rules (detect policy changes), SCPs (deny public access), CloudTrail alerts
**Information Disclosure**:
- **Public snapshot**: EBS/RDS snapshot left world-readable
- **CloudWatch Logs exposure**: Logs contain secrets, accessible to over-permissioned roles
- **Mitigation**: Automated snapshot encryption, secrets redaction in logs, least privilege CloudWatch access
**Denial of Service**:
- **Cost attack**: Attacker triggers expensive operations (Lambda invocations, data transfer)
- **Resource exhaustion**: Attacker fills S3 bucket, exhausts RDS connections
- **Mitigation**: Cost alarms, resource quotas, rate limiting
**Elevation of Privilege**:
- **Privilege escalation via misconfigured IAM**: Attacker modifies own permissions
- **Container escape**: Attacker breaks out of container to host
- **Mitigation**: IAM permission boundaries, pod security policies, AppArmor/SELinux
### STRIDE for APIs
**API-specific threats**:
**Spoofing**:
- **API key theft**: Hardcoded in client, extracted from mobile app
- **JWT forgery**: Weak secret, algorithm confusion (RS256 → HS256)
- **Mitigation**: API key rotation, secure storage (Keychain), strong JWT secrets (256-bit), algorithm whitelisting
**Tampering**:
- **Parameter tampering**: Modify user_id in request to access other user's data (IDOR)
- **Mass assignment**: Send unexpected fields to create admin users
- **Mitigation**: Authorization checks (verify user_id matches authenticated user), allowlist input fields
**Repudiation**:
- **No audit trail**: API calls not logged, can't prove who did what
- **Mitigation**: Comprehensive API logging (request ID, user ID, timestamp, endpoint, status)
**Information Disclosure**:
- **Over-fetching**: GraphQL query returns entire user object including PII
- **Verbose errors**: Stack traces reveal internal structure
- **Mitigation**: Field-level authorization (GraphQL), generic error messages to client
**Denial of Service**:
- **Query depth attack**: GraphQL query with 50 nested levels exhausts CPU
- **Rate limit bypass**: Distributed requests from many IPs
- **Mitigation**: Query depth limiting, query cost analysis, distributed rate limiting (Redis), CAPTCHA
**Elevation of Privilege**:
- **OAuth scope creep**: App requests excessive scopes, user approves without reading
- **Broken Object Level Authorization (BOLA)**: API doesn't check if user can access resource
- **Mitigation**: Minimal scopes (principle of least privilege), authorization middleware on every endpoint
### STRIDE for Mobile Apps
**Mobile-specific threats**:
**Spoofing**:
- **Jailbreak/root detection bypass**: Attacker modifies app to skip security checks
- **Certificate pinning bypass**: Attacker uses Frida to disable pinning, installs proxy cert
- **Mitigation**: Multiple anti-tamper checks, runtime integrity verification, server-side device attestation
**Tampering**:
- **Reverse engineering**: Attacker decompiles APK/IPA, finds hardcoded secrets
- **Mitigation**: ProGuard/R8 obfuscation (Android), app encryption (iOS), no secrets in client code (fetch from server)
**Information Disclosure**:
- **Insecure local storage**: SQLite DB unencrypted, accessible via device backup
- **Logging sensitive data**: Passwords/tokens in Logcat (Android) or Console (iOS)
- **Mitigation**: Keychain (iOS) / Keystore (Android), encrypted databases (SQLCipher), disable logging in production
**Denial of Service**:
- **Battery drain attack**: Malicious app or ad SDK consumes CPU/network
- **Mitigation**: Background task limits, network efficiency monitoring
**Elevation of Privilege**:
- **Permission escalation**: App tricks user into granting dangerous permissions
- **Mitigation**: Request permissions at time of use (just-in-time), explain why needed
---
## When to Use Advanced Methodologies
**Attack Trees**: Complex systems with many attack paths, need to prioritize defenses, red team planning
**DREAD Scoring**: Quantitative risk prioritization, limited security budget, need to justify spending to leadership
**Abuse Cases**: Feature-rich applications, insider threat modeling, compliance requirements (SOX, HIPAA audit trails)
**DFD-based STRIDE**: New system design (pre-implementation), comprehensive threat coverage, training junior security engineers
**Threat Intelligence (ATT&CK/CVE)**: Mature security programs, red team exercises, detection engineering, patch prioritization
**Cloud/API/Mobile STRIDE**: Specialized systems requiring domain-specific threat patterns
**Start simple** (basic STRIDE on trust boundaries), **add complexity as needed** (attack trees for critical paths, DREAD for prioritization).

View File

@@ -0,0 +1,391 @@
# Security Threat Model Template
## Workflow
Copy this checklist and track your progress:
```
Security Threat Model Progress:
- [ ] Step 1: Map system architecture and data flows
- [ ] Step 2: Identify trust boundaries
- [ ] Step 3: Classify data and compliance
- [ ] Step 4: Apply STRIDE to each boundary
- [ ] Step 5: Define mitigations and monitoring
```
**Step 1: Map system architecture**
Complete the [System Architecture](#system-architecture) section. Document all components and data flows.
**Step 2: Identify trust boundaries**
Mark boundaries in the [Trust Boundaries](#trust-boundaries) section. Identify where data crosses security domains.
**Step 3: Classify data**
Complete [Data Classification](#data-classification). Rate sensitivity and identify compliance requirements.
**Step 4: Apply STRIDE**
For each boundary, complete [STRIDE Analysis](#stride-analysis). Systematically check all six threat categories.
**Step 5: Define mitigations**
Document controls in [Mitigations & Monitoring](#mitigations--monitoring). Prioritize by risk score.
---
## Security Threat Model
### System Overview
**System Name**: [Name of system being threat modeled]
**Purpose**: [What this system does, business value, users served]
**Scope**: [What's included in this threat model, what's out of scope]
**Date**: [Date of analysis]
**Analyst(s)**: [Who conducted this threat model]
**Review Date**: [When this should be reviewed next, e.g., quarterly, after major changes]
---
### System Architecture
**Component Diagram**:
```
[User/Browser] ─── HTTPS ───> [Load Balancer] ─── HTTP ───> [Web Server]
│ JDBC
[Database]
[Backup Storage]
```
**Components**:
| Component | Technology | Purpose | Network Zone | Authentication Method |
|-----------|------------|---------|--------------|---------------------|
| [User/Browser] | Chrome/Safari/Firefox | End user interface | Public Internet | Session cookie |
| [Load Balancer] | AWS ALB | Traffic distribution, TLS termination | DMZ | N/A (no auth) |
| [Web Server] | Node.js/Express | Business logic, API endpoints | Private VPC | API key from LB |
| [Database] | PostgreSQL RDS | Persistent storage | Private subnet | DB credentials |
| [Backup Storage] | S3 bucket | Encrypted backups | AWS Region | IAM role |
| [Third-party service] | Stripe API | Payment processing | External | API secret key |
**Data Flows**:
1. **User Login**: User → LB → Web Server → Database (credentials check) → Web Server → User (session token)
2. **Data Retrieval**: User → LB → Web Server → Database (query) → Web Server → User (JSON response)
3. **Payment**: User → LB → Web Server → Stripe API (payment token) → Webhook → Web Server → Database (order confirmation)
4. **Backup**: Database → S3 (nightly encrypted snapshot)
**External Dependencies**:
| Service | Purpose | Data Shared | Authentication | SLA/Criticality |
|---------|---------|-------------|----------------|-----------------|
| [Stripe] | Payment processing | Card tokens, customer IDs | API secret key | Critical (payment failures = revenue loss) |
| [SendGrid] | Email delivery | Email addresses, message content | API key | High (notifications) |
| [Datadog] | Monitoring/logging | Logs, metrics (may contain PII) | API key | Medium (observability) |
---
### Trust Boundaries
**Boundary 1: Public Internet → Load Balancer**
- **Data crossing**: HTTP requests (headers, body, query params)
- **Trust change**: Untrusted (anyone on Internet) → Trusted infrastructure
- **Controls**: TLS 1.2+, DDoS protection, rate limiting, Web Application Firewall (WAF)
- **Risk**: High (direct exposure to attackers)
**Boundary 2: Load Balancer → Web Server**
- **Data crossing**: HTTP requests (forwarded), source IP, X-Forwarded-For headers
- **Trust change**: DMZ → Private VPC
- **Controls**: Security groups (whitelist LB IPs), API key validation, input validation
- **Risk**: Medium (internal but accepts untrusted input)
**Boundary 3: Web Server → Database**
- **Data crossing**: SQL queries, query parameters
- **Trust change**: Application layer → Data layer
- **Controls**: Parameterized queries, connection pooling, DB credentials in secrets manager, least privilege grants
- **Risk**: High (SQL injection = full data compromise)
**Boundary 4: Web Server → Third-Party API (Stripe)**
- **Data crossing**: Payment tokens, customer data, order details
- **Trust change**: Internal → External (Stripe's control)
- **Controls**: HTTPS, API key rotation, minimal data sharing, audit logging of requests
- **Risk**: Medium (data leaves our control, reputational risk)
**Boundary 5: Database → Backup Storage (S3)**
- **Data crossing**: Encrypted database snapshots
- **Trust change**: Live database → Long-term storage
- **Controls**: AES-256 encryption at rest, bucket policies (private), versioning, lifecycle policies, cross-region replication
- **Risk**: Medium (exposure if misconfigured, compliance requirement)
**Boundary 6: Client-side (JavaScript) → Server-side (API)**
- **Data crossing**: User inputs, client-side state
- **Trust change**: User-controlled code → Server validation
- **Controls**: Server-side validation (never trust client), CSRF tokens, CSP headers, HttpOnly cookies
- **Risk**: High (client fully controlled by attacker)
---
### Data Classification
**Data Inventory**:
| Data Element | Classification | Compliance | Storage Location | Encryption | Retention |
|--------------|---------------|------------|------------------|------------|-----------|
| User passwords | Restricted | GDPR | Database | bcrypt hash (cost 12) | Until account deletion |
| Credit card numbers | Restricted (PCI) | PCI DSS Level 1 | Stripe (tokenized) | Stripe manages | Stripe retention policy |
| Email addresses | Confidential (PII) | GDPR, CAN-SPAM | Database, SendGrid | At rest: AES-256 | 7 years post-deletion |
| Order history | Confidential | GDPR | Database | At rest: AES-256 | 7 years (tax law) |
| Session tokens | Confidential | - | Redis, cookies | In transit: TLS | 24 hours |
| Audit logs | Internal | SOC 2 | Datadog, S3 | At rest: AES-256 | 1 year |
| API keys (3rd party) | Restricted | - | AWS Secrets Manager | Encrypted by SM | Rotated quarterly |
| User IP addresses | Internal (PII) | GDPR | Logs, analytics | At rest: AES-256 | 90 days |
**Classification Levels**:
- **Public**: Can be freely shared (marketing content, public documentation)
- **Internal**: For internal use, no external sharing (business metrics, roadmaps)
- **Confidential**: Sensitive, access controlled (PII, customer data)
- **Restricted**: Highly sensitive, strict access (credentials, PCI data, PHI)
**Compliance Requirements**:
- **GDPR**: Data minimization, consent management, right to deletion, breach notification (72 hours)
- **PCI DSS Level 1**: No storage of CVV, tokenization, quarterly ASV scans, annual audit
- **SOC 2 Type II**: Access controls, audit logging, change management, annual audit
---
### STRIDE Analysis
For each trust boundary, systematically apply all six STRIDE threat categories:
#### Boundary: Public Internet → Load Balancer
**S - Spoofing**
- **Threat**: Attacker spoofs user identity using stolen session cookies
- **Likelihood**: Medium (session cookies in browser storage vulnerable to XSS)
- **Impact**: High (full account access)
- **Mitigation**: HttpOnly + Secure + SameSite=Strict cookies, short session timeout (1 hour), IP binding, device fingerprinting
- **Status**: ✓ Implemented
- **Monitoring**: Alert on geo-impossible travel (login from US then China in 1 hour)
**T - Tampering**
- **Threat**: Man-in-the-middle attack modifies requests/responses
- **Likelihood**: Low (TLS widely enforced)
- **Impact**: High (data corruption, command injection)
- **Mitigation**: TLS 1.2+ enforced, HSTS header, certificate pinning (mobile), integrity checks on critical operations
- **Status**: ✓ Implemented
- **Monitoring**: Monitor TLS version usage, alert on downgrade attempts
**R - Repudiation**
- **Threat**: User denies making purchase, no audit trail
- **Likelihood**: Low (audit logging in place)
- **Impact**: Medium (dispute resolution, fraud)
- **Mitigation**: Comprehensive audit logging (user ID, timestamp, action, IP, user agent), immutable logs (S3 with object lock), digital signatures on transactions
- **Status**: ✓ Implemented
- **Monitoring**: Alert on log tampering, regular log integrity checks
**I - Information Disclosure**
- **Threat**: Verbose error messages reveal stack traces, database schema
- **Likelihood**: Medium (development errors in production)
- **Impact**: Medium (aids attacker reconnaissance)
- **Mitigation**: Generic error messages to users, detailed errors logged server-side only, security headers (X-Content-Type-Options, X-Frame-Options), no PII in URLs/logs
- **Status**: ⚠ Partial (need to audit error messages)
- **Monitoring**: Log analysis for stack traces in responses, alert on 500 errors
**D - Denial of Service**
- **Threat**: DDoS attack exhausts resources, site becomes unavailable
- **Likelihood**: Medium (e-commerce sites are targets)
- **Impact**: High (revenue loss, reputation)
- **Mitigation**: CloudFront CDN, AWS Shield Standard, WAF rate limiting (100 req/min per IP), auto-scaling, circuit breakers, resource quotas
- **Status**: ✓ Implemented
- **Monitoring**: Alert on traffic spikes (>10x baseline), track error rates, auto-scaling metrics
**E - Elevation of Privilege**
- **Threat**: Regular user gains admin access via authorization bypass
- **Likelihood**: Low (authorization checks in place)
- **Impact**: High (full system compromise)
- **Mitigation**: Role-based access control (RBAC), authorization check on every request, principle of least privilege, admin actions require re-authentication
- **Status**: ✓ Implemented
- **Monitoring**: Alert on privilege escalation attempts, admin action audit log
**Risk Score** (Likelihood × Impact):
- Spoofing: 2 × 3 = 6 (Medium)
- Tampering: 1 × 3 = 3 (Low)
- Repudiation: 1 × 2 = 2 (Low)
- Information Disclosure: 2 × 2 = 4 (Medium)
- Denial of Service: 2 × 3 = 6 (Medium)
- Elevation of Privilege: 1 × 3 = 3 (Low)
**Top Risks for This Boundary**: Session hijacking (Spoofing), DDoS (DoS), Information disclosure via errors
---
#### Boundary: Web Server → Database
**S - Spoofing**
- **Threat**: Attacker connects to database impersonating web server
- **Likelihood**: Very Low (internal network, firewall rules)
- **Impact**: High (full data access)
- **Mitigation**: Database credentials in AWS Secrets Manager (rotated), security groups (whitelist web server IPs only), IAM database authentication
- **Status**: ✓ Implemented
- **Monitoring**: Alert on new database connections from unexpected IPs, failed auth attempts
**T - Tampering**
- **Threat**: SQL injection modifies data, drops tables
- **Likelihood**: Medium (common vulnerability)
- **Impact**: Critical (data loss, corruption, exfiltration)
- **Mitigation**: Parameterized queries (ORM), input validation, least privilege DB user (no DROP/ALTER), read-only replicas for reporting, database backups
- **Status**: ⚠ Partial (manual code review needed for all SQL)
- **Monitoring**: Database audit log for DDL statements, unexpected UPDATE/DELETE volumes
**R - Repudiation**
- **Threat**: Database changes cannot be attributed to specific user
- **Likelihood**: Low (application logging in place)
- **Impact**: Low (audit, compliance)
- **Mitigation**: Application-level audit logging (user ID + action + timestamp), database query log (CloudWatch), immutable logs
- **Status**: ✓ Implemented
- **Monitoring**: Daily audit log integrity check
**I - Information Disclosure**
- **Threat**: Database dump exposed through misconfiguration, backup left public
- **Likelihood**: Medium (S3 misconfigurations common)
- **Impact**: Critical (full data breach)
- **Mitigation**: Encryption at rest (AES-256), encrypted backups, S3 bucket policies (private), no public snapshots, VPC endpoint for S3, data masking in non-prod
- **Status**: ✓ Implemented
- **Monitoring**: AWS Config rules for public S3 buckets, daily snapshot encryption check
**D - Denial of Service**
- **Threat**: Expensive queries exhaust database CPU/memory
- **Likelihood**: Medium (missing query optimization)
- **Impact**: High (site unavailable)
- **Mitigation**: Query timeouts (5s), connection pooling, read replicas, CloudWatch alarms on CPU (>80%), slow query log, query plan analysis
- **Status**: ✓ Implemented
- **Monitoring**: Alert on database CPU/memory, slow query log review weekly
**E - Elevation of Privilege**
- **Threat**: Web server DB user escalates to DBA privileges
- **Likelihood**: Very Low (IAM policies enforced)
- **Impact**: High (full database control)
- **Mitigation**: Least privilege DB grants (SELECT/INSERT/UPDATE only, no ALTER/DROP/GRANT), separate admin credentials, MFA for DB admin access
- **Status**: ✓ Implemented
- **Monitoring**: Alert on privilege grant operations, regular IAM policy audit
**Risk Score**:
- Tampering (SQL injection): 2 × 4 = 8 (High - Priority 1)
- Information Disclosure (backup exposure): 2 × 4 = 8 (High - Priority 1)
- Denial of Service (query exhaustion): 2 × 3 = 6 (Medium)
- Spoofing: 1 × 3 = 3 (Low)
- Repudiation: 1 × 1 = 1 (Low)
- Elevation of Privilege: 1 × 3 = 3 (Low)
**Top Risks for This Boundary**: SQL injection (Tampering), Backup exposure (Information Disclosure)
---
[Repeat STRIDE analysis for each trust boundary identified above]
---
### Mitigations & Monitoring
**Preventive Controls** (block attacks before they succeed):
| Control | Threats Mitigated | Implementation | Owner | Status |
|---------|-------------------|----------------|-------|--------|
| TLS 1.2+ enforcement | Tampering (MITM) | ALB listener policy | DevOps | ✓ Done |
| Parameterized queries | Tampering (SQLi) | ORM (Sequelize) | Engineering | ⚠ Partial |
| Input validation | Tampering, Injection | Joi schema validation | Engineering | ✓ Done |
| Rate limiting | DoS | WAF rules (100 req/min/IP) | DevOps | ✓ Done |
| CSRF tokens | Spoofing (CSRF) | csurf middleware | Engineering | ✓ Done |
| HttpOnly cookies | Spoofing (XSS → session theft) | Express cookie settings | Engineering | ✓ Done |
| Least privilege IAM | Elevation of Privilege | IAM policies | DevOps | ✓ Done |
| MFA for admin | Spoofing (credential theft) | AWS IAM MFA | DevOps | ✓ Done |
| Encryption at rest | Information Disclosure | RDS encryption, S3 default encryption | DevOps | ✓ Done |
| WAF (OWASP Top 10) | Multiple (SQLi, XSS, etc.) | AWS WAF managed rules | DevOps | ✓ Done |
**Detective Controls** (identify attacks in progress or after):
| Control | Detection Method | Alert Threshold | Incident Response | Owner | Status |
|---------|-----------------|----------------|-------------------|-------|--------|
| Failed login monitoring | CloudWatch Logs Insights | >5 failures in 5 min from same IP | Auto-block IP (24h), notify security team | DevOps | ✓ Done |
| SQL injection attempts | WAF logs + application logs | Any blocked SQLi pattern | Security review of attempted payload | Security | ✓ Done |
| Unusual data access | Database audit log | User accessing >1000 records in 1 min | Throttle user, security review | Engineering | ⚠ Partial |
| Privilege escalation attempts | Application audit log | Non-admin accessing admin endpoints | Block user, security review | Engineering | ✓ Done |
| Geo-impossible travel | Session activity log | Login from US then Asia <2 hours | Force re-auth, notify user | Engineering | ⚠ TODO |
| DDoS detection | CloudWatch metrics | Traffic >10x baseline | Engage AWS Shield Response Team | DevOps | ✓ Done |
| Backup integrity | S3 lifecycle checks | Missing daily backup | Page on-call, investigate | DevOps | ✓ Done |
| Secret rotation overdue | Secrets Manager | >90 days since rotation | Automated rotation, alert if fails | DevOps | ✓ Done |
**Corrective Controls** (respond to and recover from attacks):
| Scenario | Response Plan | Recovery Time Objective (RTO) | Recovery Point Objective (RPO) | Owner | Tested? |
|----------|--------------|-------------------------------|-------------------------------|-------|---------|
| Database compromise | Restore from backup, rotate credentials, forensic analysis | <4 hours | <24 hours (daily backups) | DevOps | ⚠ Last tested 6 months ago |
| DDoS attack | Enable AWS Shield Advanced, adjust WAF rules, failover to static site | <15 minutes | N/A | DevOps | ✓ Tested quarterly |
| Credential leak | Rotate all secrets, force password resets, revoke sessions, notify users | <1 hour | N/A | Security | ⚠ Runbook exists, not tested |
| Data breach | Incident response plan, legal notification, forensic preservation, public disclosure | <72 hours (GDPR) | N/A | Legal + Security | ⚠ Tabletop exercise needed |
---
### Risk Prioritization
**Risk Matrix** (Likelihood × Impact):
| Threat | Likelihood (1-5) | Impact (1-5) | Risk Score | Priority | Mitigation Status | Residual Risk |
|--------|------------------|--------------|------------|----------|-------------------|---------------|
| SQL injection | 3 (Medium) | 5 (Critical) | 15 | P0 (Critical) | Partial (manual review needed) | Medium |
| Backup exposure | 2 (Low) | 5 (Critical) | 10 | P1 (High) | Implemented | Low |
| Session hijacking | 3 (Medium) | 4 (High) | 12 | P1 (High) | Implemented | Medium |
| DDoS | 3 (Medium) | 4 (High) | 12 | P1 (High) | Implemented | Low |
| Info disclosure (errors) | 3 (Medium) | 2 (Medium) | 6 | P2 (Medium) | Partial | Medium |
| Credential stuffing | 2 (Low) | 4 (High) | 8 | P2 (Medium) | Implemented (rate limiting) | Low |
| CSRF | 2 (Low) | 3 (Medium) | 6 | P2 (Medium) | Implemented | Low |
| Query DoS | 2 (Low) | 3 (Medium) | 6 | P2 (Medium) | Implemented | Low |
**Top 3 Priorities**:
1. **SQL Injection (P0)**: Complete manual code review of all SQL queries, add automated SQLi detection in CI/CD
2. **Session Hijacking (P1)**: Implement geo-impossible travel detection, add device fingerprinting
3. **DDoS Protection (P1)**: Test Shield Advanced failover, document runbook
**Accepted Risks**:
- **CSRF on read-only endpoints**: Low impact (no state change), cost of tokens on every GET outweighs risk
- **Verbose logging in development**: Acceptable in dev/staging (not in production), aids debugging
---
### Action Items
| Action | Owner | Deadline | Priority | Status |
|--------|-------|----------|----------|--------|
| [Manual SQL code review for parameterized queries] | Engineering | 2 weeks | P0 | 🔴 Not Started |
| [Implement geo-impossible travel detection] | Engineering | 1 month | P1 | 🔴 Not Started |
| [Audit all error messages for information disclosure] | Engineering | 2 weeks | P2 | 🔴 Not Started |
| [Test database restore procedure] | DevOps | 1 week | P1 | 🟡 In Progress |
| [Tabletop exercise for data breach response] | Security + Legal | 1 month | P1 | 🔴 Not Started |
| [Document DDoS runbook and test] | DevOps | 2 weeks | P1 | 🟡 In Progress |
| [Rotate all API keys] | DevOps | Immediately | P0 | ✅ Done |
---
## Guidance for Each Section
**System Architecture**: Include visual diagram, technology stack (specific versions), network zones (DMZ/VPC/Internet), external dependencies (SaaS, APIs). Avoid vague descriptions.
**Data Classification**: Classify every element (public/internal/confidential/restricted), consult legal/compliance for PII/PHI/PCI, document retention and encryption. Don't forget data in logs/analytics/backups.
**STRIDE Application**: Apply all 6 categories to each boundary. Start with high-risk boundaries (user input, external integrations). Likelihood: 1=sophisticated attacker, 3=script kiddie, 5=trivial. Impact: 1=nuisance, 3=significant exposure, 5=complete compromise.
**Mitigation Status**: ✓ Implemented, ⚠ Partial, 🔴 TODO, ✅ Done
**Quality Checklist**: All components diagrammed | All boundaries analyzed | STRIDE on each boundary | All data classified | Mitigations mapped | Monitoring defined | Risks prioritized | Action items assigned | Assumptions documented | Review date set