
Threat Modeling Techniques
- 2 installs
- 28 repo stars
- Updated June 29, 2026
- nickcrew/claude-cortex
Applies STRIDE, attack trees, and risk assessment to identify attack vectors when designing secure systems or reviewing security.
About
Provides threat modeling methodologies using STRIDE, attack trees, and risk assessment for proactive security analysis. A developer uses it when designing secure systems or identifying potential attack vectors.
- Uses STRIDE, attack trees, and risk assessment for proactive analysis
- Identifies attack vectors during system design and security reviews
Threat Modeling Techniques by the numbers
- 2 all-time installs (skills.sh)
- Ranked #1,785 of 2,202 Security skills by installs in the Skillselion catalog
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/nickcrew/claude-cortex --skill threat-modeling-techniquesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 28 |
| Last updated | June 29, 2026 |
| Repository | nickcrew/claude-cortex ↗ |
What it does
Applies STRIDE, attack trees, and risk assessment to identify attack vectors when designing secure systems or reviewing security.
Files
Threat Modeling Techniques
Systematic framework for identifying, analyzing, and mitigating security threats during system design and architecture phases using proven methodologies like STRIDE, attack trees, and risk assessment frameworks.
When to Use This Skill
- Designing new systems or features with security requirements
- Conducting security architecture reviews
- Identifying attack vectors and threat scenarios
- Assessing security risks before implementation
- Creating security requirements and controls
- Evaluating third-party integrations for security impact
- Planning security testing strategies
- Documenting security design decisions
- Training teams on proactive security thinking
- Supporting security compliance initiatives (SOC 2, ISO 27001)
Core Process
Five-Stage Threat Modeling Process:
1. Define - Understand the system and create architecture diagrams 2. Identify - Enumerate threats using structured methodologies (STRIDE, attack trees) 3. Assess - Evaluate risk severity and likelihood (DREAD scoring) 4. Mitigate - Design controls and countermeasures 5. Validate - Review and test security controls
Quick Reference
| Task | Load reference |
|---|---|
| STRIDE: Spoofing Identity | skills/threat-modeling-techniques/references/stride-spoofing.md |
| STRIDE: Tampering with Data | skills/threat-modeling-techniques/references/stride-tampering.md |
| STRIDE: Repudiation | skills/threat-modeling-techniques/references/stride-repudiation.md |
| STRIDE: Information Disclosure | skills/threat-modeling-techniques/references/stride-disclosure.md |
| STRIDE: Denial of Service | skills/threat-modeling-techniques/references/stride-dos.md |
| STRIDE: Elevation of Privilege | skills/threat-modeling-techniques/references/stride-elevation.md |
| Attack Trees | skills/threat-modeling-techniques/references/attack-trees.md |
| Data Flow Diagrams (DFD) | skills/threat-modeling-techniques/references/data-flow-diagrams.md |
| DREAD Risk Scoring | skills/threat-modeling-techniques/references/dread-scoring.md |
| Mitigation Strategies | skills/threat-modeling-techniques/references/mitigation-strategies.md |
| Tools & Process | skills/threat-modeling-techniques/references/tools-and-process.md |
Core Concepts
STRIDE Methodology
STRIDE categorizes threats into six types:
- Spoofing: Pretending to be someone/something else (authentication bypass, credential theft)
- Tampering: Malicious modification of data (MITM attacks, data corruption)
- Repudiation: Denying actions without proof (lack of audit trails)
- Information Disclosure: Exposing sensitive data (data leaks, verbose errors)
- Denial of Service: Making systems unavailable (resource exhaustion, DDoS)
- Elevation of Privilege: Gaining unauthorized capabilities (privilege escalation, IDOR)
Apply STRIDE to:
- Each component in data flow diagrams
- Every trust boundary crossing
- All data stores and processes
- External integrations and APIs
Attack Trees
Hierarchical diagrams showing attack paths from goals to methods:
[Root: Attack Goal]
|
+-- [OR] Method 1 (alternative paths)
| |
| +-- [AND] Required Step 1.1
| +-- [AND] Required Step 1.2
|
+-- [OR] Method 2 (alternative paths)Use attack trees to:
- Visualize attack scenarios
- Identify easiest attack paths
- Assign attributes (cost, skill, detection likelihood)
- Prioritize mitigations for high-risk paths
DREAD Risk Scoring
DREAD quantifies threat severity (each criterion scored 0-10, average = risk score):
- Damage Potential: How much damage if exploited?
- Reproducibility: How easy to reproduce?
- Exploitability: How easy to exploit?
- Affected Users: How many users affected?
- Discoverability: How easy to discover?
Risk Levels:
- 7.1-10.0: Critical (immediate action)
- 5.1-7.0: High (next sprint)
- 3.1-5.0: Medium (upcoming releases)
- 0.0-3.0: Low (backlog)
Trust Boundaries
Lines separating different trust levels:
- Network: Internet → DMZ → Internal
- Process: User Mode → Kernel, Container → Host
- User: Anonymous → Authenticated → Admin
At each boundary, verify:
- Authentication required?
- Authorization checks enforced?
- Data encrypted?
- Inputs validated?
- Actions logged?
Practical Workflow
1. Scope Definition (30 min)
- Identify system components in scope
- Define trust boundaries
- List assets requiring protection
- Identify compliance requirements
2. Architecture Decomposition (1 hour)
- Create data flow diagrams (DFDs)
- Document external dependencies
- Identify authentication/authorization points
- Map data storage locations
3. Threat Identification (1-2 hours)
- Apply STRIDE to each DFD element
- Create attack trees for high-value assets
- Brainstorm threat scenarios with team
- Use threat modeling tools for suggestions
4. Risk Assessment (1 hour)
- Apply DREAD scoring to each threat
- Prioritize threats by risk score
- Consider business context and compliance
- Identify quick wins vs. long-term efforts
5. Mitigation Planning (1 hour)
- Design security controls (eliminate, reduce, transfer, accept)
- Document mitigation strategies
- Create security requirements (SEC-### format)
- Assign ownership for implementation
6. Documentation (30 min)
- Export threat model diagrams
- Create security requirements document
- Document risk acceptance decisions
- Share with stakeholders
Common Mistakes
Avoid:
- Threat modeling too late (after implementation complete)
- Focusing only on external threats (ignore insider threats)
- Creating static threat models (never updating them)
- Over-complicating diagrams (too much detail)
- Ignoring low-likelihood, high-impact threats
- Failing to document assumptions and decisions
- Not following through on mitigations
Best Practices
Team Involvement:
- Developers: Implementation details, code-level threats
- Architects: System design, integration points
- Security Team: Threat expertise, attack scenarios
- Operations: Deployment, monitoring, incident response
- Product Owners: Business impact, risk acceptance decisions
Process Integration:
- Design phase: Threat model before implementation
- Development: Implement controls, create security tests
- Deployment: Verify controls, enable monitoring
- Maintenance: Update model when features change
Tools
Microsoft Threat Modeling Tool: Visual DFD editor, automated STRIDE threat generation OWASP Threat Dragon: Open source, cross-platform, web and desktop versions IriusRisk: Commercial platform, DevSecOps integration, compliance mapping ThreatModeler: Collaborative, cloud architecture support
Resources
- Microsoft Threat Modeling Tool: https://aka.ms/threatmodelingtool
- OWASP Threat Dragon: https://owasp.org/www-project-threat-dragon/
- STRIDE Documentation: https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool-threats
- Threat Modeling Manifesto: https://www.threatmodelingmanifesto.org/
- NIST Threat Modeling: https://csrc.nist.gov/projects/threat-modeling
Attack Trees
Definition: Hierarchical diagrams showing attack paths from goals to methods.
Structure
[Root: Attack Goal]
|
+-- [OR] Method 1
| |
| +-- [AND] Step 1.1
| +-- [AND] Step 1.2
|
+-- [OR] Method 2
|
+-- [AND] Step 2.1Key Concepts:
- OR nodes: Alternative attack methods (any one succeeds)
- AND nodes: Required steps (all must succeed)
- Leaf nodes: Atomic attack actions
- Root node: Attacker's ultimate goal
Example: Unauthorized Data Access
[Goal: Access Customer Database]
|
+-- [OR] Exploit SQL Injection
| |
| +-- [AND] Find vulnerable input field
| +-- [AND] Craft malicious SQL payload
| +-- [AND] Extract data from database
|
+-- [OR] Steal Admin Credentials
| |
| +-- [AND] Phishing attack on admin
| +-- [AND] Bypass 2FA (if enabled)
| +-- [AND] Login with stolen credentials
|
+-- [OR] Exploit Misconfigured Access Controls
|
+-- [AND] Enumerate API endpoints
+-- [AND] Find unprotected endpoint
+-- [AND] Access data without authenticationCreating Attack Trees
Process
1. Define the attacker's goal (root node)
- Example: "Steal credit card data", "Disrupt service"
2. Identify alternative attack methods (OR nodes)
- Different ways to achieve the goal
- Each method is independent
3. Break down each method into required steps (AND nodes)
- Sequential or parallel steps
- All steps must succeed for method to work
4. Assign attributes to each node
- Cost, skill level, detection likelihood, impact
5. Analyze most likely attack paths
- Calculate aggregate attributes for paths
- Identify easiest/cheapest/stealthiest paths
6. Prioritize mitigations for high-risk paths
- Focus on high-probability, high-impact paths
- Consider cost-effectiveness of mitigations
Attributes to Track
Cost
Resources required by attacker
- Low: Free tools, minimal time
- Medium: Commercial tools, days of effort
- High: Custom development, weeks of effort
Skill Level
Technical expertise needed
- Novice: Script kiddie, pre-built tools
- Intermediate: Developer, moderate security knowledge
- Expert: Security professional, custom exploit development
Detection Likelihood
Probability of being caught
- Low: Stealthy, hard to detect
- Medium: Detectable with monitoring
- High: Obvious, triggers immediate alerts
Impact
Damage if successful
- Low: Minor inconvenience
- Medium: Data exposure, service degradation
- High: Major breach, complete compromise
- Critical: Catastrophic damage, regulatory violations
Attack Tree Analysis
Feasibility Scoring
For each attack path, calculate:
Path Feasibility = (1 / Cost) × (1 / Skill) × (1 / Detection)Higher score = More likely attack vector
Prioritization
Focus mitigations on paths with:
- High feasibility: Easy to execute
- High impact: Severe consequences
- Low cost to mitigate: Quick wins
Example with Attributes
[Goal: Access Customer Database]
|
+-- [OR] SQL Injection
| Cost: Low | Skill: Intermediate | Detection: Medium | Impact: Critical
| |
| +-- [AND] Find vulnerable field (Cost: Low, Skill: Novice)
| +-- [AND] Craft payload (Cost: Low, Skill: Intermediate)
| +-- [AND] Extract data (Cost: Low, Skill: Intermediate)
|
+-- [OR] Steal Admin Credentials
| Cost: Medium | Skill: Intermediate | Detection: High | Impact: Critical
| |
| +-- [AND] Phishing (Cost: Low, Skill: Novice)
| +-- [AND] Bypass 2FA (Cost: High, Skill: Expert)
| +-- [AND] Login (Cost: Low, Skill: Novice)
|
+-- [OR] Misconfigured Access
Cost: Low | Skill: Novice | Detection: Low | Impact: Critical
|
+-- [AND] Enumerate endpoints (Cost: Low, Skill: Novice)
+-- [AND] Find unprotected endpoint (Cost: Low, Skill: Novice)
+-- [AND] Access data (Cost: Low, Skill: Novice)Analysis:
- Highest Risk: Misconfigured access (low cost, low skill, low detection)
- Priority Mitigation: Fix access controls, implement authentication
- Secondary Risk: SQL injection (common, well-known attack)
- Lower Priority: Credential theft (2FA makes it harder)
Best Practices
- Start broad, refine iteratively: Begin with high-level goals, add detail
- Include stakeholders: Developers, security team, operations
- Update regularly: As system evolves, threats change
- Document assumptions: What security controls are assumed to exist?
- Consider attacker profiles: Nation-state vs. script kiddie vs. insider
- Validate with penetration testing: Do theoretical attacks work in practice?
Data Flow Diagrams (DFD)
Purpose: Visualize how data moves through the system to identify threat points.
DFD Elements
Key Components
External Entity (rectangle)
- Users, external systems, third-party services
- Outside the system boundary
- Sources or destinations of data
Process (circle)
- Application components, services, functions
- Transform or process data
- Trust boundaries often cross between processes
Data Store (parallel lines)
- Databases, file systems, caches, message queues
- Persistent or temporary storage
- Potential targets for information disclosure
Data Flow (arrow)
- Data movement between elements
- Can cross trust boundaries
- Each flow is a potential attack vector
Trust Boundary (dashed line)
- Security context changes
- Authentication/authorization required
- Critical points for STRIDE analysis
Example DFD
[User Browser] ---(1) HTTPS Request---> [Web Server]
|
(2) Query
|
v
[Application Server]
|
(3) SQL
|
v
[Database]
|
(4) Logs
|
v
[Audit Log Store]
Trust Boundaries:
- Between User Browser and Web Server (Internet)
- Between Web Server and Application Server (DMZ)
- Between Application Server and Database (Internal Network)Threat Analysis per DFD Element
For Each Data Flow, Consider STRIDE
Flow 1: User → Web Server (HTTPS)
Spoofing
- Stolen credentials, session hijacking
- Mitigation: Strong authentication, MFA, session expiration
Tampering
- Man-in-the-middle if HTTPS not enforced
- Mitigation: Force HTTPS, HSTS header, certificate pinning
Repudiation
- User denies sending request
- Mitigation: Audit logging with request signatures
Information Disclosure
- Sniffing credentials over network
- Mitigation: TLS 1.3, encrypted connections
Denial of Service
- DDoS attack on web server
- Mitigation: Rate limiting, WAF, DDoS protection
Elevation of Privilege
- Session hijacking, cookie theft
- Mitigation: HttpOnly/Secure cookies, CSRF tokens
Flow 2: Application → Database (SQL)
Spoofing
- Spoofing database credentials
- Mitigation: Connection pooling, credential rotation, least privilege
Tampering
- SQL injection modifying queries
- Mitigation: Parameterized queries, ORM, input validation
Repudiation
- No audit of database changes
- Mitigation: Database audit logs, transaction logging
Information Disclosure
- Unauthorized data access, SQL injection
- Mitigation: Access controls, encryption at rest, query filtering
Denial of Service
- Resource exhaustion, slow queries
- Mitigation: Query timeouts, connection limits, query optimization
Elevation of Privilege
- Privilege escalation via SQL injection
- Mitigation: Least privilege DB accounts, parameterized queries
Trust Boundaries
Definition
Lines separating different trust levels in a system.
Common Trust Boundaries
1. Network Boundaries
- Internet → DMZ: Public to semi-public
- DMZ → Internal Network: Semi-public to private
- Internal → Secure Enclave: Private to highly restricted
Security Controls:
- Firewalls, network segmentation
- IDS/IPS systems
- VPN/private connections
2. Process Boundaries
- User Mode → Kernel Mode: Application to OS
- Guest VM → Host System: Virtual to physical
- Container → Host: Isolated to privileged
Security Controls:
- OS-level permissions
- Sandboxing, containerization
- Hypervisor isolation
3. User Boundaries
- Anonymous → Authenticated: Unknown to verified
- User → Administrator: Standard to privileged
- Internal → External Users: Trusted to untrusted
Security Controls:
- Authentication mechanisms
- Role-based access control
- Multi-factor authentication
Analyzing Trust Boundaries
Questions to Ask:
1. Authentication
- What authentication is required to cross the boundary?
- Is it strong enough for the trust level change?
2. Authorization
- What authorization checks are performed?
- Are permissions verified at every boundary?
3. Encryption
- Is data encrypted when crossing the boundary?
- What encryption strength is used?
4. Validation
- Are all inputs validated when crossing the boundary?
- Is validation comprehensive (type, format, range)?
5. Logging
- Is boundary crossing logged and monitored?
- Can anomalies be detected?
DFD Best Practices
Creating Effective DFDs
1. Start with context diagram: High-level system overview 2. Decompose into levels: Level 0 → Level 1 → Level 2 3. Focus on data flow: Not control flow or implementation 4. Mark trust boundaries explicitly: Use dashed lines 5. Label data flows: Describe what data is moving 6. Include all external entities: Don't forget third-party services 7. Show all data stores: Databases, caches, files, queues
Common Mistakes to Avoid
- Too much detail: Keep focused on security-relevant flows
- Missing trust boundaries: Every boundary is a potential threat point
- Ignoring indirect flows: Data flows through logs, caches, etc.
- Forgetting external dependencies: Third-party APIs, CDNs, etc.
- Not updating diagrams: DFDs must evolve with the system
Applying STRIDE to DFD
Systematic Process
For each element in the DFD:
1. External Entity: Focus on Spoofing, Repudiation 2. Process: All STRIDE threats apply 3. Data Store: Focus on Tampering, Information Disclosure, Denial of Service 4. Data Flow: All STRIDE threats apply 5. Trust Boundary: Critical for all STRIDE threats
Threat Checklist Template
## [Data Flow Name]
**Spoofing**: Can the sender be impersonated?
**Tampering**: Can the data be modified in transit?
**Repudiation**: Can the sender deny the action?
**Information Disclosure**: Can the data be intercepted?
**Denial of Service**: Can the flow be disrupted?
**Elevation of Privilege**: Can the flow grant unauthorized access?
**Risk Score**: [Low/Medium/High/Critical]
**Mitigations**: [List of controls]DREAD Risk Assessment
DREAD is a risk assessment framework for quantifying threat severity.
DREAD Criteria
Each criterion scored 0-10, average = risk score
D - Damage Potential
Question: How much damage if exploited?
Scoring:
- 0-2: Minimal impact, cosmetic issues
- 3-4: Limited data exposure, temporary service degradation
- 5-6: Significant data exposure, extended downtime
- 7-8: Major breach, customer data compromised
- 9-10: Complete system compromise, catastrophic damage
Examples:
- 2: Display bug in UI
- 5: Exposure of non-sensitive user data
- 9: Full database compromise with PII/financial data
R - Reproducibility
Question: How easy to reproduce the attack?
Scoring:
- 0-2: Very difficult, requires specific conditions
- 3-4: Difficult, requires timing or race conditions
- 5-6: Moderate, requires authenticated access
- 7-8: Easy, any authenticated user can reproduce
- 9-10: Trivial, anyone can reproduce easily
Examples:
- 2: Requires specific hardware and network conditions
- 5: Requires valid user account and specific request timing
- 10: Works every time with simple HTTP request
E - Exploitability
Question: How easy to exploit?
Scoring:
- 0-2: Requires expert skills and custom tools
- 3-4: Requires advanced knowledge and tool modification
- 5-6: Requires moderate skill and available tools
- 7-8: Requires basic scripting knowledge
- 9-10: Web browser or curl command only
Examples:
- 2: Requires reverse engineering and custom exploit development
- 5: Use Burp Suite with some configuration
- 10: Copy-paste command from blog post
A - Affected Users
Question: How many users affected?
Scoring:
- 0-2: Single user or small subset
- 3-4: Specific user group or feature subset
- 5-6: Significant portion of users
- 7-8: Majority of users or critical subset
- 9-10: All users, entire system, or critical data
Examples:
- 2: Single admin account
- 5: All users of premium feature (20% of user base)
- 10: Entire customer database exposed
D - Discoverability
Question: How easy to discover the vulnerability?
Scoring:
- 0-2: Very hard to find, requires source code access
- 3-4: Requires detailed analysis and fuzzing
- 5-6: Found with moderate effort and scanning
- 7-8: Found with automated scanners
- 9-10: Obvious, visible in URL or public documentation
Examples:
- 2: Logic flaw requiring deep code analysis
- 5: Found by targeted security testing
- 10: SQL injection in URL parameter, found by SQLMap
DREAD Scoring Examples
Example 1: SQL Injection in Login Form
Threat: SQL Injection in publicly accessible login endpoint
Scoring:
- Damage: 9 (Full database compromise, data theft)
- Reproducibility: 10 (Easy to reproduce every time)
- Exploitability: 7 (Moderate skill, tools available like SQLMap)
- Affected Users: 10 (All users, entire database at risk)
- Discoverability: 8 (Common vulnerability, automated scanners find it)
Risk Score: (9 + 10 + 7 + 10 + 8) / 5 = 8.8 (CRITICAL)
Priority: Immediate fix required
Example 2: Missing Rate Limiting on API
Threat: No rate limiting on password reset endpoint
Scoring:
- Damage: 6 (Account takeover possible via brute force)
- Reproducibility: 10 (Easy to reproduce)
- Exploitability: 8 (Simple scripting required)
- Affected Users: 7 (All users vulnerable, but requires targeting)
- Discoverability: 6 (Found with moderate testing)
Risk Score: (6 + 10 + 8 + 7 + 6) / 5 = 7.4 (HIGH)
Priority: Fix in next sprint
Example 3: Information Disclosure in Comments
Threat: HTML comments contain internal IP addresses
Scoring:
- Damage: 3 (Minor information disclosure, aids reconnaissance)
- Reproducibility: 10 (Always present in source)
- Exploitability: 10 (View source in any browser)
- Affected Users: 2 (Information disclosure, not direct user impact)
- Discoverability: 10 (Obvious in HTML source)
Risk Score: (3 + 10 + 10 + 2 + 10) / 5 = 7.0 (MEDIUM-HIGH)
Priority: Fix soon, but not critical
Example 4: XSS in Admin-Only Field
Threat: Stored XSS in admin panel description field
Scoring:
- Damage: 7 (Admin session hijacking, high privileges)
- Reproducibility: 10 (Easy to reproduce)
- Exploitability: 8 (Simple XSS payload)
- Affected Users: 2 (Only affects admins who view the field)
- Discoverability: 4 (Requires admin access to discover)
Risk Score: (7 + 10 + 8 + 2 + 4) / 5 = 6.2 (MEDIUM)
Priority: Fix in backlog, but monitor for abuse
Risk Level Interpretation
Risk Score Ranges:
- 0.0 - 3.0: Low - Monitor, fix when convenient
- 3.1 - 5.0: Medium - Fix in upcoming releases
- 5.1 - 7.0: High - Prioritize for next sprint
- 7.1 - 10.0: Critical - Immediate action required
DREAD Worksheet Template
## Threat: [Threat Name]
### DREAD Scoring
**D - Damage Potential**: [0-10]
- Justification: [Explain the potential damage]
**R - Reproducibility**: [0-10]
- Justification: [Explain how easily it can be reproduced]
**E - Exploitability**: [0-10]
- Justification: [Explain the required skill and tools]
**A - Affected Users**: [0-10]
- Justification: [Explain the scope of impact]
**D - Discoverability**: [0-10]
- Justification: [Explain how easily it can be found]
### Risk Calculation
**Risk Score**: ([D] + [R] + [E] + [A] + [D]) / 5 = **[Score]**
**Risk Level**: [Low/Medium/High/Critical]
**Priority**: [When to fix]
### Recommended Actions
- [List mitigations]Limitations of DREAD
Known Issues
- Subjectivity: Scores can vary between assessors
- Binary thinking: Doesn't capture nuanced risks well
- Evolving threats: Scores may change as exploits become easier
- Context dependency: Same vulnerability, different risk in different systems
Improvements
- Calibration sessions: Team agreement on scoring examples
- Regular updates: Re-assess as threat landscape changes
- Combine with other methods: Use with STRIDE, attack trees
- Document assumptions: Why you scored each criterion
Mitigation Strategies
Risk Prioritization Matrix
Risk Level = Likelihood × Impact
| Impact → | Low (1) | Medium (2) | High (3) | Critical (4) |
|---|---|---|---|---|
| High (3) | Medium | High | Critical | Critical |
| Med (2) | Low | Medium | High | Critical |
| Low (1) | Low | Low | Medium | High |
Priority Actions:
- Critical: Immediate action, stop release if necessary
- High: Fix before next release
- Medium: Schedule in upcoming sprint
- Low: Backlog, fix when convenient
Four Mitigation Approaches
1. Eliminate
Strategy: Remove the threat entirely by eliminating the vulnerable feature or attack surface.
When to Use:
- Feature is not critical to functionality
- Risk significantly outweighs benefit
- Simpler alternatives exist
Examples:
- Disable unused administrative endpoints
- Remove unnecessary file upload functionality
- Eliminate deprecated authentication methods
- Shut down unused network services
- Remove debug endpoints in production
Pros:
- Most effective mitigation (threat gone)
- No ongoing maintenance cost
- No performance impact
Cons:
- May reduce functionality
- May require architecture changes
2. Reduce
Strategy: Implement security controls to reduce the likelihood or impact of the threat.
When to Use:
- Feature is necessary
- Risk can be managed to acceptable level
- Controls are cost-effective
Examples:
- Add authentication/authorization to exposed endpoints
- Implement input validation and sanitization
- Apply principle of least privilege
- Add rate limiting and throttling
- Encrypt sensitive data
- Add logging and monitoring
Pros:
- Maintains functionality
- Can reduce risk significantly
- Industry-standard approach
Cons:
- Requires implementation effort
- Ongoing maintenance needed
- May impact performance
3. Transfer
Strategy: Shift the risk to a third party or external service.
When to Use:
- Third party has better security expertise
- Risk is too high to manage internally
- Compliance requires specialized controls
Examples:
- Use Auth0/Okta instead of custom authentication
- Use cloud provider's encryption (KMS, AWS Secrets Manager)
- Purchase cyber insurance
- Use payment processor for credit card handling (PCI compliance)
- Leverage CDN for DDoS protection (Cloudflare, Akamai)
Pros:
- Reduced internal complexity
- Expert-managed security
- Insurance coverage for incidents
Cons:
- Ongoing costs
- Vendor dependency
- May not eliminate risk entirely
4. Accept
Strategy: Acknowledge the risk and accept the potential consequences.
When to Use:
- Mitigation cost exceeds potential damage
- Risk level is very low
- Legal/compliance obligations met
Examples:
- Known UI bug with minimal impact
- Theoretical attack requiring nation-state resources
- Low-value internal tool with limited exposure
Requirements:
- Document risk acceptance: Written record with justification
- Get approval: Management sign-off on acceptance
- Implement monitoring: Detect if risk materializes
- Plan incident response: Know what to do if exploited
- Review periodically: Risk may increase over time
Pros:
- No implementation cost
- Focus resources on higher risks
Cons:
- Risk remains present
- May materialize despite low likelihood
- Potential liability if exploited
Control Types
Preventive Controls
Purpose: Stop threats before they occur
Examples:
- Input validation: Block malicious inputs at entry
- Access controls: RBAC, ABAC, least privilege
- Encryption: Protect data at rest and in transit
- Authentication: MFA, certificate-based auth
- Secure coding: Parameterized queries, output encoding
- Network segmentation: Firewalls, VLANs, DMZ
- Secure configuration: Disable defaults, harden systems
Characteristics:
- First line of defense
- Most cost-effective (prevent > detect > respond)
- Requires design-time implementation
Detective Controls
Purpose: Identify threats in progress or after occurrence
Examples:
- Logging and monitoring: Centralized log aggregation
- Intrusion detection systems (IDS): Network and host-based
- SIEM: Security information and event management
- File integrity monitoring (FIM): Detect unauthorized changes
- Anomaly detection: ML-based behavior analysis
- Audit trails: Comprehensive activity logging
- Vulnerability scanning: Regular automated scans
Characteristics:
- Second line of defense
- Enables quick response
- Requires ongoing monitoring
Corrective Controls
Purpose: Respond to detected threats and restore normal operations
Examples:
- Incident response procedures: Documented playbooks
- Backup and recovery: Regular backups, tested restores
- Patching and updates: Automated patch management
- Account lockout: Automatic response to brute force
- Failover systems: Redundant infrastructure
- Rollback mechanisms: Version control, database snapshots
Characteristics:
- Third line of defense
- Minimizes damage and downtime
- Requires preparation and testing
Defense in Depth
Principle: Layer multiple controls so failure of one doesn't compromise security.
Example Layered Defense
Threat: SQL Injection
Layer 1 - Preventive:
- Use parameterized queries (ORM, prepared statements)
- Input validation with allow-lists
- Least privilege database accounts
Layer 2 - Detective:
- Database activity monitoring
- SIEM alerts on suspicious queries
- Anomaly detection for data access patterns
Layer 3 - Corrective:
- Automated query blocking on detection
- Database connection kill switches
- Backup and recovery procedures
Result: Even if one layer fails, others provide protection
Mitigation Effectiveness
Measuring Control Effectiveness
Metrics:
- Risk Reduction: DREAD score before and after mitigation
- Coverage: Percentage of attack paths blocked
- Detection Rate: True positives vs. false positives
- Response Time: Time to detect and respond
- Cost: Implementation and ongoing maintenance
Example Effectiveness Analysis
Threat: Credential Stuffing Attack
Mitigation Options:
| Control | Risk Reduction | Coverage | Implementation Cost | Ongoing Cost | Effectiveness Score |
|---|---|---|---|---|---|
| Rate Limiting | Medium (30%) | 60% | Low | Low | Good |
| CAPTCHA | High (60%) | 80% | Low | Medium | Excellent |
| MFA | Very High (90%) | 95% | Medium | Low | Outstanding |
| Passwordless Auth | Complete (100%) | 100% | High | Medium | Best |
Recommendation: Implement MFA as immediate mitigation, plan migration to passwordless authentication for long-term solution.
Security Requirements Template
From threat model to actionable requirements:
## Security Requirement: [ID]
### Threat Context
- **Threat**: [Brief description]
- **STRIDE Category**: [S/T/R/I/D/E]
- **Risk Score (DREAD)**: [Score] ([Low/Medium/High/Critical])
- **Attack Vector**: [How the attack works]
### Requirement
[Specific, testable security control to implement]
### Acceptance Criteria
- [ ] [Criterion 1 - must be testable]
- [ ] [Criterion 2 - must be testable]
- [ ] [Criterion 3 - must be testable]
### Implementation Notes
[Technical guidance, patterns, libraries to use]
### Verification Method
- **Code Review**: [What to look for]
- **Testing**: [How to test]
- **Tools**: [SAST, DAST, manual testing]
### Owner
- **Team**: [Responsible team]
- **Due Date**: [Sprint/release]
### Dependencies
- [Required changes, infrastructure, etc.]Example Security Requirement
## Security Requirement: SEC-001
### Threat Context
- **Threat**: SQL Injection in product search endpoint
- **STRIDE Category**: Tampering, Information Disclosure, Elevation of Privilege
- **Risk Score (DREAD)**: 8.8 (Critical)
- **Attack Vector**: Malicious SQL in search parameter
### Requirement
All database queries MUST use parameterized statements or ORM methods. String concatenation for SQL queries is prohibited.
### Acceptance Criteria
- [ ] No string concatenation in any SQL query
- [ ] ORM (Sequelize) used for all database operations
- [ ] Input validation with allow-list for search terms
- [ ] SQL injection testing included in automated test suite
- [ ] SAST tool configured to detect SQL concatenation
### Implementation Notes
- Use Sequelize ORM for all queries
- For complex queries requiring raw SQL, use `sequelize.query()` with bound parameters
- Validate input: alphanumeric characters only, max 100 chars
- Library: `validator.js` for input sanitization
### Verification Method
- **Code Review**: Check for raw SQL, string interpolation
- **Testing**: Automated SQLMap scan, manual injection attempts
- **Tools**: SonarQube (SAST), OWASP ZAP (DAST)
### Owner
- **Team**: Backend Team
- **Due Date**: Sprint 23 (before release)
### Dependencies
- Sequelize ORM already in use
- Update test suite with security test casesSTRIDE: Information Disclosure
Definition: Exposing information to unauthorized individuals.
Threat Examples
Verbose Error Messages
// THREAT: Exposing sensitive data through verbose error messages
// VULNERABLE: Stack traces exposed to users
app.use((err, req, res, next) => {
res.status(500).json({
error: err.message,
stack: err.stack,
sql: err.sql // Exposes database structure
});
});
// MITIGATION: Generic errors, detailed internal logs
app.use((err, req, res, next) => {
// Log internally with full details
logger.error('Request error', {
error: err.message,
stack: err.stack,
sql: err.sql,
requestId: req.id,
userId: req.user?.id
});
// Return generic error to client
res.status(500).json({
error: 'Internal server error',
requestId: req.id
});
});Common Disclosure Vectors
- Error messages: Stack traces, database errors, file paths
- Debug information: Environment variables, configuration details
- Source code comments: Credentials, API keys, internal URLs
- Directory listings: Exposed file structure
- Metadata: EXIF data, document properties
- API responses: Excessive data, internal IDs
- Network traffic: Unencrypted communications
Mitigations
- Encryption at rest: AES-256, disk encryption
- Encryption in transit: TLS 1.3, certificate pinning
- Access control enforcement: RBAC, ABAC, least privilege
- Data classification: Mark and handle sensitive data appropriately
- Secure key management: KMS, HSM, key rotation
- Data masking & tokenization: Protect sensitive fields
- Generic error messages: Don't leak internal details to users
- Security headers: Prevent MIME sniffing, clickjacking, XSS
- API response filtering: Only return necessary fields
- Secrets scanning: Detect credentials in code/logs
STRIDE: Denial of Service
Definition: Making systems unavailable to legitimate users.
Threat Examples
Resource Exhaustion
// THREAT: Resource exhaustion through unbounded operations
// VULNERABLE: No rate limiting or resource constraints
app.post('/api/search', async (req, res) => {
const results = await db.query(`SELECT * FROM products WHERE name LIKE '%${req.body.query}%'`);
res.json(results); // Returns unlimited rows
});
// MITIGATION: Rate limiting + pagination + timeouts
const rateLimit = require('express-rate-limit');
const searchLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 20 // 20 requests per minute
});
app.post('/api/search', searchLimiter, async (req, res) => {
const query = req.body.query;
const page = parseInt(req.body.page) || 1;
const limit = Math.min(parseInt(req.body.limit) || 10, 100); // Max 100 items
const offset = (page - 1) * limit;
// Use parameterized query with LIMIT
const results = await db.query(
'SELECT * FROM products WHERE name LIKE ? LIMIT ? OFFSET ?',
[`%${query}%`, limit, offset],
{ timeout: 5000 } // 5 second query timeout
);
res.json({
results,
page,
limit,
hasMore: results.length === limit
});
});DoS Attack Vectors
- Application layer: Expensive operations, algorithmic complexity
- Network layer: SYN floods, UDP floods, amplification attacks
- Resource exhaustion: Memory leaks, CPU spinning, disk filling
- Logic bombs: Triggering expensive operations repeatedly
- Distributed attacks (DDoS): Coordinated botnet attacks
Mitigations
- Rate limiting & throttling: Per-user, per-IP, per-endpoint limits
- Resource quotas: Memory limits, CPU time, disk space
- Timeouts: Request timeouts, query timeouts, connection timeouts
- Input validation: Size limits, complexity limits, format validation
- Load balancing: Distribute traffic across multiple servers
- Auto-scaling: Horizontal scaling based on load
- CDN & caching: Reduce load on origin servers
- Anti-automation: CAPTCHA, proof-of-work challenges
- DDoS protection: Cloudflare, AWS Shield, Akamai
- Circuit breakers: Fail fast when dependencies are down
- Backpressure: Push back on clients when overwhelmed
STRIDE: Elevation of Privilege
Definition: Gaining capabilities without proper authorization.
Threat Examples
Parameter Manipulation
// THREAT: Privilege escalation through parameter manipulation
// VULNERABLE: Client-controlled role assignment
app.post('/api/users', authenticate, async (req, res) => {
const user = await db.createUser({
username: req.body.username,
password: req.body.password,
role: req.body.role // Attacker sets role: 'admin'
});
res.json(user);
});
// MITIGATION: Server-side role enforcement
app.post('/api/users', authenticate, requireRole('admin'), async (req, res) => {
// Only admins can create users
// Default role assigned by system, not client
const user = await db.createUser({
username: req.body.username,
password: req.body.password,
role: 'user', // Always default to least privilege
createdBy: req.user.id
});
logger.info('User created', {
newUserId: user.id,
createdBy: req.user.id,
timestamp: new Date()
});
res.json(user);
});
// Separate endpoint for role changes with strict controls
app.patch('/api/users/:id/role', authenticate, requireRole('admin'), async (req, res) => {
const targetUser = await db.getUser(req.params.id);
// Prevent self-elevation
if (targetUser.id === req.user.id) {
return res.status(403).json({ error: 'Cannot modify own role' });
}
// Validate role value
const validRoles = ['user', 'moderator', 'admin'];
if (!validRoles.includes(req.body.role)) {
return res.status(400).json({ error: 'Invalid role' });
}
await db.updateUser(req.params.id, { role: req.body.role });
logger.warn('Role changed', {
targetUserId: targetUser.id,
oldRole: targetUser.role,
newRole: req.body.role,
changedBy: req.user.id,
timestamp: new Date()
});
res.json({ success: true });
});Privilege Escalation Vectors
- Horizontal escalation: Access another user's resources
- Vertical escalation: Gain higher privileges (user → admin)
- Parameter manipulation: Modify request parameters (user ID, role)
- Path traversal: Access restricted directories/files
- SQL injection: Bypass authorization checks
- Insecure direct object references (IDOR): Access objects without authorization
Mitigations
- Principle of least privilege: Grant minimum required permissions
- Role-based access control (RBAC): Define and enforce roles
- Input validation: Validate all privilege-related parameters
- Separation of duties: Require multiple approvals for sensitive actions
- Privilege use logging: Audit all privilege changes and usage
- Secure defaults: Deny by default, explicit allow
- Regular privilege audits: Review and revoke unused permissions
- Attribute-based access control (ABAC): Fine-grained access control
- Just-in-time (JIT) access: Temporary elevated privileges
STRIDE: Repudiation
Definition: Denying actions or transactions without proof otherwise.
Threat Examples
Missing Audit Trail
// THREAT: User denies performing sensitive action without audit trail
// VULNERABLE: No audit logging
app.post('/api/transfer', authenticate, async (req, res) => {
await transferFunds(req.user.id, req.body.to, req.body.amount);
res.json({ success: true });
});
// MITIGATION: Comprehensive audit logging
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'audit.log' })
]
});
app.post('/api/transfer', authenticate, async (req, res) => {
const auditEvent = {
action: 'FUND_TRANSFER',
userId: req.user.id,
from: req.user.accountId,
to: req.body.to,
amount: req.body.amount,
ip: req.ip,
userAgent: req.get('user-agent'),
timestamp: new Date().toISOString(),
sessionId: req.session.id
};
logger.info('Fund transfer initiated', auditEvent);
try {
const result = await transferFunds(req.user.id, req.body.to, req.body.amount);
logger.info('Fund transfer completed', { ...auditEvent, transactionId: result.id });
res.json({ success: true, transactionId: result.id });
} catch (err) {
logger.error('Fund transfer failed', { ...auditEvent, error: err.message });
res.status(500).json({ error: 'Transfer failed' });
}
});Mitigations
- Comprehensive audit logging: Who, what, when, where, why
- Digital signatures: Cryptographic non-repudiation
- Tamper-proof log storage: Append-only, immutable logs
- Secure time-stamping: Trusted time sources
- Multi-party approval: Require multiple signatures for critical actions
- Legal agreements: Terms of service, audit clauses
- Blockchain/distributed ledger: Immutable transaction records
STRIDE: Spoofing Identity
Definition: Pretending to be someone or something else to gain unauthorized access.
Threat Examples
JWT Manipulation Without Verification
// THREAT: Spoofing user identity via JWT manipulation
// Attacker modifies JWT payload without signature verification
// VULNERABLE: No signature verification
app.get('/api/profile', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const decoded = JSON.parse(Buffer.from(token.split('.')[1], 'base64'));
// Using decoded.userId without verification
const user = db.getUser(decoded.userId);
res.json(user);
});
// MITIGATION: Proper JWT verification
const jwt = require('jsonwebtoken');
app.get('/api/profile', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = db.getUser(decoded.userId);
res.json(user);
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
});Mitigations
- Strong authentication mechanisms: MFA, certificate-based auth
- Digital signatures: Cryptographic verification of identity claims
- Secure credential storage: Hashed passwords, encrypted keys
- Session management: Secure tokens with expiration and rotation
- Mutual TLS: For service-to-service communication
- Anti-spoofing headers: SPF, DKIM, DMARC for email systems
STRIDE: Tampering with Data
Definition: Malicious modification of data in transit or at rest.
Threat Examples
Man-in-the-Middle Attack
// THREAT: Man-in-the-middle attack modifying API requests
// VULNERABLE: Unencrypted data transmission
fetch('http://api.example.com/transfer', {
method: 'POST',
body: JSON.stringify({ amount: 100, to: 'account123' })
});
// MITIGATION: HTTPS + request signing
const crypto = require('crypto');
function signRequest(data, secret) {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(JSON.stringify(data));
return hmac.digest('hex');
}
const data = { amount: 100, to: 'account123', timestamp: Date.now() };
const signature = signRequest(data, process.env.API_SECRET);
fetch('https://api.example.com/transfer', {
method: 'POST',
headers: {
'X-Signature': signature,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});Mitigations
- TLS/HTTPS: Encrypt data in transit
- Digital signatures & HMAC: Verify data integrity
- Input validation: Sanitize and validate all inputs
- Immutable audit logs: Tamper-proof logging
- Database transaction controls: ACID properties, checksums
- File integrity monitoring (FIM): Detect unauthorized changes
- Content Security Policy (CSP): Prevent XSS tampering
Threat Modeling Tools & Process
Threat Modeling Tools
Microsoft Threat Modeling Tool
Overview:
- Free Windows desktop application
- Developed by Microsoft Security team
- Integrated STRIDE methodology
- Template-based threat generation
Features:
- Visual DFD editor with drag-and-drop
- Automated STRIDE threat generation per element
- Built-in threat knowledge base
- Mitigation recommendations
- Report generation (HTML, PDF)
- Import/export capabilities
Best Practices:
1. Start with high-level architecture diagram
2. Break down into detailed DFDs (Level 0 → Level 1 → Level 2)
3. Define trust boundaries explicitly (Internet, DMZ, Internal)
4. Let tool generate STRIDE threats automatically
5. Review and customize threats for your context
6. Document mitigations for each threat
7. Export report for security requirements
8. Update model as system evolvesDownload: https://aka.ms/threatmodelingtool
OWASP Threat Dragon
Overview:
- Cross-platform, open source
- Web-based and desktop versions
- Community-driven threat library
- GitHub integration
Features:
- DFD modeling with STRIDE analysis
- No vendor lock-in, fully open source
- Web version runs in browser
- Desktop version (Windows, macOS, Linux)
- GitHub repository integration
- Extensible threat templates
- Export to JSON, PDF
Advantages:
- Free for all use cases
- Community contributions
- No platform dependencies (web version)
- Privacy-focused (local storage option)
- Active development
Best For:
- Open source projects
- Cross-platform teams
- Cloud-native development
- Teams wanting customization
Website: https://owasp.org/www-project-threat-dragon/
IriusRisk
Overview:
- Commercial threat modeling platform
- Automated threat library
- DevSecOps integration
- Compliance mapping
Features:
- Questionnaire-driven threat modeling
- Automated threat and control suggestions
- SDLC tool integrations (Jira, GitHub, etc.)
- Compliance frameworks (PCI-DSS, ISO 27001, GDPR)
- Risk scoring and prioritization
- Team collaboration features
Best For:
- Enterprise environments
- Compliance-heavy industries
- DevSecOps workflows
- Large development teams
ThreatModeler
Overview:
- Collaborative threat modeling platform
- Cloud architecture support
- Real-time collaboration
Features:
- Visual threat modeling for cloud (AWS, Azure, GCP)
- Automated threat identification
- Integration with CI/CD pipelines
- Real-time team collaboration
- Compliance reporting
- API for automation
Best For:
- Cloud-native applications
- Distributed teams
- Continuous threat modeling
CAIRIS
Overview:
- Requirements and risk management platform
- Persona-based threat modeling
- Open source, research-focused
Features:
- Persona and scenario-based modeling
- Requirements traceability
- Risk and vulnerability management
- Security requirements generation
- Attack tree generation
- Export to various formats
Best For:
- User-centered security design
- Academic and research projects
- Requirements engineering teams
Practical Threat Modeling Workflow
Step-by-Step Process
1. Scope Definition (30 min)
Objectives:
- Define what's in scope for threat modeling
- Identify boundaries and assumptions
- List critical assets
Activities:
- Identify system components in scope
- Frontend, backend, databases, APIs, third-party services
- Define trust boundaries
- Internet/DMZ, DMZ/Internal, User/Admin
- List assets requiring protection
- User data, financial info, intellectual property, credentials
- Identify compliance requirements
- PCI-DSS, GDPR, HIPAA, SOC 2, ISO 27001
Deliverables:
- Scope document listing components, boundaries, assets
- List of out-of-scope items
- Compliance requirements checklist
2. Architecture Decomposition (1 hour)
Objectives:
- Understand how the system works
- Create visual representation
- Document data flows
Activities:
- Create data flow diagrams (DFDs)
- Level 0: Context diagram (high-level)
- Level 1: Major components and flows
- Level 2: Detailed subsystem views
- Document external dependencies
- Third-party APIs, cloud services, CDN
- Identify authentication/authorization points
- Login, API auth, service-to-service auth
- Map data storage locations
- Databases, caches, file systems, logs
Deliverables:
- Multi-level DFD diagrams
- External dependency list
- Trust boundary map
- Data storage inventory
3. Threat Identification (1-2 hours)
Objectives:
- Enumerate potential threats
- Use structured methodologies
- Capture team knowledge
Activities:
- Apply STRIDE to each DFD element
- For each process, data flow, data store
- Document all applicable STRIDE categories
- Create attack trees for high-value assets
- Customer data, payment processing, admin access
- Brainstorm threat scenarios with team
- Include developers, security, operations
- Consider insider threats, supply chain risks
- Use threat modeling tool for suggestions
- Leverage built-in threat libraries
- Customize for your context
Deliverables:
- Comprehensive threat list
- Attack tree diagrams
- Threat brainstorming notes
- Tool-generated threat report
4. Risk Assessment (1 hour)
Objectives:
- Prioritize threats by risk
- Consider business impact
- Identify quick wins
Activities:
- Apply DREAD scoring to each threat
- Damage, Reproducibility, Exploitability, Affected Users, Discoverability
- Prioritize threats by risk score
- Critical (7.1-10.0), High (5.1-7.0), Medium (3.1-5.0), Low (0.0-3.0)
- Consider business context and compliance
- Regulatory requirements, business impact, reputation
- Identify quick wins vs. long-term efforts
- High impact, low effort = quick wins
- High impact, high effort = strategic initiatives
Deliverables:
- Risk-scored threat list
- Prioritized threat backlog
- Quick win opportunities
- Risk acceptance decisions (if any)
5. Mitigation Planning (1 hour)
Objectives:
- Design security controls
- Create actionable requirements
- Assign ownership
Activities:
- Design security controls for high-risk threats
- Preventive, detective, corrective controls
- Defense in depth approach
- Document mitigation strategies
- Eliminate, reduce, transfer, accept
- Create security requirements
- Specific, testable, actionable
- Assign ownership for implementation
- Development teams, infrastructure, security
Deliverables:
- Mitigation strategy document
- Security requirements list (with IDs)
- Ownership assignments
- Implementation timeline
6. Documentation (30 min)
Objectives:
- Capture all work
- Enable future updates
- Share with stakeholders
Activities:
- Export threat model diagrams
- DFDs, attack trees, architecture diagrams
- Create security requirements document
- SEC-### format with acceptance criteria
- Document risk acceptance decisions
- What risks were accepted and why
- Share with stakeholders
- Development, security, management, compliance
Deliverables:
- Threat model report (PDF/HTML)
- Security requirements document
- Risk acceptance register
- Stakeholder presentation
Example Security Requirement
From Threat Model to Actionable Requirement:
## Security Requirement: SEC-001
### Threat Context
- **Threat**: SQL Injection in product search endpoint
- **STRIDE Category**: Tampering, Information Disclosure, Elevation of Privilege
- **Risk Score (DREAD)**: 8.8 (Critical)
- Damage: 9, Reproducibility: 10, Exploitability: 7, Affected Users: 10, Discoverability: 8
- **Attack Vector**: Attacker submits malicious SQL in search parameter
### Requirement
All database queries MUST use parameterized statements or ORM methods. String concatenation for SQL queries is PROHIBITED.
### Acceptance Criteria
- [ ] No string concatenation in any SQL query
- [ ] ORM (Sequelize) used for all database operations
- [ ] Input validation with allow-list for search terms (alphanumeric, max 100 chars)
- [ ] SQL injection testing included in automated test suite
- [ ] SAST tool (SonarQube) configured to detect SQL concatenation
### Implementation Notes
- **Use Sequelize ORM** for all queries
- For complex raw SQL: `sequelize.query()` with bound parameters
- **Input validation**: `validator.js` for sanitization
- **Test with**: SQLMap, OWASP ZAP, manual injection attempts
### Verification Method
- **Code Review**: Search for raw SQL, string interpolation (`+`, `${}`), `eval()`
- **SAST**: SonarQube rule S2077 (SQL injection detection)
- **DAST**: OWASP ZAP active scan, SQLMap automated testing
- **Manual**: Penetration testing with payloads (`' OR '1'='1`, `'; DROP TABLE--`)
### Owner
- **Team**: Backend Team
- **Primary**: @alice (backend lead)
- **Reviewer**: @bob (security team)
- **Due Date**: Sprint 23 (before v2.0 release)
### Dependencies
- Sequelize ORM already in use ✓
- SonarQube integration (in progress)
- Update test suite with security casesBest Practices
Process Integration
Design Phase:
- Conduct threat modeling before implementation begins
- Include security requirements in design documents
- Review with security team before development starts
- Update architecture diagrams with security annotations
Development Phase:
- Implement security controls from threat model
- Document security assumptions in code comments
- Create security test cases (unit, integration, E2E)
- Run SAST/DAST tools as part of CI/CD
Deployment Phase:
- Verify security controls in production environment
- Enable monitoring and alerting for identified threats
- Document operational security procedures (runbooks)
- Conduct pre-production security review
Maintenance Phase:
- Update threat model when features change
- Re-assess threats periodically (quarterly, annually)
- Track security incidents and update model accordingly
- Review and update mitigations based on new threats
Team Involvement
Stakeholders:
Developers:
- Implementation details, code-level threats
- Feasibility of security controls
- Performance impact assessment
Architects:
- System design, integration points
- Scalability and availability considerations
- Technology choices and trade-offs
Security Team:
- Threat expertise, attack scenarios
- Compliance requirements
- Security control recommendations
Operations:
- Deployment architecture, network topology
- Monitoring and incident response
- Operational security procedures
Product Owners:
- Business impact and priorities
- Risk acceptance decisions
- Feature vs. security trade-offs
Common Pitfalls
Avoid:
1. Threat modeling too late
- Don't wait until implementation is complete
- Retrofitting security is expensive and incomplete
2. Focusing only on external threats
- Don't ignore insider threats (malicious or accidental)
- Consider supply chain and third-party risks
3. Creating static threat models
- Don't let models gather dust
- Update as system evolves and threats emerge
4. Over-complicating diagrams
- Keep focused on security-relevant flows
- Too much detail obscures threats
5. Ignoring low-likelihood, high-impact threats
- Nation-state attacks, zero-days
- Consider business-critical scenarios
6. Failing to document assumptions
- What controls are assumed to exist?
- What's out of scope and why?
7. No follow-through
- Threats identified but not mitigated
- Requirements created but not implemented
- Must track to completion