Threat modeling methodologies using STRIDE, attack trees, and risk assessment for proactive security analysis. Use when designing secure systems, conducting security reviews, or identifying potential attack vectors in applications.
This skill inherits all available tools. When active, it can use any tool Claude has access to.
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.
Stages:
STRIDE is a threat classification framework developed by Microsoft that categorizes threats into six types.
Definition: Pretending to be someone or something else to gain unauthorized access.
Examples:
// 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:
Definition: Malicious modification of data in transit or at rest.
Examples:
// 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:
Definition: Denying actions or transactions without proof otherwise.
Examples:
// 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:
Definition: Exposing information to unauthorized individuals.
Examples:
// 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
});
});
Mitigations:
Definition: Making systems unavailable to legitimate users.
Examples:
// 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
});
});
Mitigations:
Definition: Gaining capabilities without proper authorization.
Examples:
// 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 });
});
Mitigations:
Definition: Hierarchical diagrams showing attack paths from goals to methods.
[Root: Attack Goal]
|
+-- [OR] Method 1
| |
| +-- [AND] Step 1.1
| +-- [AND] Step 1.2
|
+-- [OR] Method 2
|
+-- [AND] Step 2.1
[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 authentication
Process:
Attributes to Track:
Purpose: Visualize how data moves through the system to identify threat points.
Key Components:
[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)
For each data flow, consider STRIDE:
User → Web Server (HTTPS)
Application → Database (SQL)
Definition: Lines separating different trust levels in a system.
Network Boundaries
Process Boundaries
User Boundaries
Questions to Ask:
DREAD is a risk assessment framework for quantifying threat severity.
Each criterion scored 0-10, average = risk score
Question: How much damage if exploited?
Question: How easy to reproduce?
Question: How easy to exploit?
Question: How many users affected?
Question: How easy to discover?
Threat: SQL Injection in login form
Risk Score: (9 + 10 + 7 + 10 + 8) / 5 = 8.8 (CRITICAL)
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 |
1. Eliminate
2. Reduce
3. Transfer
4. Accept
Preventive: Stop threats before they occur
Detective: Identify threats in progress
Corrective: Respond to detected threats
Features:
Best Practices:
1. Start with high-level architecture
2. Break down into detailed DFDs
3. Define trust boundaries explicitly
4. Let tool generate STRIDE threats
5. Review and customize threats
6. Document mitigations
7. Export for security requirements
Features:
Advantages:
IriusRisk
ThreatModeler
CAIRIS
Design Phase:
Development Phase:
Deployment Phase:
Maintenance Phase:
Stakeholders:
Avoid:
1. Scope Definition (30 min)
2. Architecture Decomposition (1 hour)
3. Threat Identification (1-2 hours)
4. Risk Assessment (1 hour)
5. Mitigation Planning (1 hour)
6. Documentation (30 min)
From Threat Model:
Threat: SQL Injection in search endpoint
Risk Score: 8.8 (Critical)
Security Requirement:
- ID: SEC-001
- Component: Search API
- Requirement: All database queries MUST use parameterized statements
- Acceptance Criteria:
* No string concatenation in SQL queries
* ORM or prepared statements used exclusively
* Input validation with allow-list for search terms
* SQL injection testing included in test suite
- Owner: Backend Team
- Due Date: Sprint 23
- Verification: Code review + SAST + manual testing