Loading...
Loading...
Compare original and translation side by side
// Bad: Direct ID access
app.get('/api/users/:id', (req, res) => {
const user = await db.user.findUnique({ where: { id: req.params.id } });
res.json(user);
});
// Good: Authorization check
app.get('/api/users/:id', authorize(), (req, res) => {
if (req.user.role !== 'admin' && req.user.id !== req.params.id) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = await db.user.findUnique({ where: { id: req.params.id } });
res.json(user);
});// Bad: Direct ID access
app.get('/api/users/:id', (req, res) => {
const user = await db.user.findUnique({ where: { id: req.params.id } });
res.json(user);
});
// Good: Authorization check
app.get('/api/users/:id', authorize(), (req, res) => {
if (req.user.role !== 'admin' && req.user.id !== req.params.id) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = await db.user.findUnique({ where: { id: req.params.id } });
res.json(user);
});// Password hashing
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, SALT_ROUNDS);
}
async function verifyPassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
// Encryption
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
function encrypt(text: string, key: Buffer): string {
const iv = randomBytes(16);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString('base64');
}// Password hashing
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, SALT_ROUNDS);
}
async function verifyPassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
// Encryption
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
function encrypt(text: string, key: Buffer): string {
const iv = randomBytes(16);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, encrypted]).toString('base64');
}// SQL Injection - Use parameterized queries
// Bad
const query = `SELECT * FROM users WHERE email = '${email}'`;
// Good - Prisma (parameterized by default)
const user = await db.user.findUnique({ where: { email } });
// Good - Raw SQL with parameters
const user = await db.$queryRaw`SELECT * FROM users WHERE email = ${email}`;
// Command Injection
// Bad
exec(`convert ${filename} output.png`);
// Good - Use array form
execFile('convert', [filename, 'output.png']);
// XSS Prevention
// Bad
element.innerHTML = userInput;
// Good - Text content
element.textContent = userInput;
// Good - Sanitization
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);// SQL Injection - Use parameterized queries
// Bad
const query = `SELECT * FROM users WHERE email = '${email}'`;
// Good - Prisma (parameterized by default)
const user = await db.user.findUnique({ where: { email } });
// Good - Raw SQL with parameters
const user = await db.$queryRaw`SELECT * FROM users WHERE email = ${email}`;
// Command Injection
// Bad
exec(`convert ${filename} output.png`);
// Good - Use array form
execFile('convert', [filename, 'output.png']);
// XSS Prevention
// Bad
element.innerHTML = userInput;
// Good - Text content
element.textContent = userInput;
// Good - Sanitization
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://api.example.com"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "https://api.example.com"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));| Threat | Property | Examples |
|---|---|---|
| Spoofing | Authentication | Session hijacking, credential theft |
| Tampering | Integrity | SQL injection, MITM attacks |
| Repudiation | Non-repudiation | Missing audit logs |
| Information Disclosure | Confidentiality | Data breaches, verbose errors |
| Denial of Service | Availability | DDoS, resource exhaustion |
| Elevation of Privilege | Authorization | Privilege escalation |
| 威胁类型 | 影响属性 | 示例 |
|---|---|---|
| Spoofing(仿冒) | 身份认证 | 会话劫持、凭证窃取 |
| Tampering(篡改) | 完整性 | SQL注入、中间人攻击 |
| Repudiation(抵赖) | 不可抵赖性 | 缺失审计日志 |
| Information Disclosure(信息泄露) | 保密性 | 数据泄露、详细错误信息暴露 |
| Denial of Service(拒绝服务) | 可用性 | DDoS攻击、资源耗尽 |
| Elevation of Privilege(权限提升) | 授权 | 权限提升 |
undefinedundefinedundefinedundefinedundefinedundefined
**DAST (Dynamic Analysis):**
```bash
**DAST(动态分析):**
```bashundefinedundefined| Severity | Description | Response Time | Examples |
|---|---|---|---|
| Critical | Active breach | Immediate | Data exfiltration, ransomware |
| High | Imminent threat | 1 hour | Unpatched critical CVE |
| Medium | Potential risk | 24 hours | Suspicious activity |
| Low | Minor issue | 72 hours | Failed login attempts |
| 严重程度 | 描述 | 响应时间 | 示例 |
|---|---|---|---|
| 关键 | 正在发生的数据泄露 | 立即响应 | 数据外泄、勒索软件攻击 |
| 高 | 迫在眉睫的威胁 | 1小时内响应 | 未修复的关键CVE |
| 中 | 潜在风险 | 24小时内响应 | 可疑活动 |
| 低 | 轻微问题 | 72小时内响应 | 登录失败尝试 |
Layer 1: Perimeter
├── WAF
├── DDoS protection
└── Network firewall
Layer 2: Network
├── Segmentation
├── IDS/IPS
└── Network monitoring
Layer 3: Application
├── Input validation
├── Authentication
└── Authorization
Layer 4: Data
├── Encryption
├── Access controls
└── Backup/recovery
Layer 5: Endpoint
├── EDR
├── Patching
└── Configuration managementLayer 1: 边界层
├── WAF
├── DDoS防护
└── 网络防火墙
Layer 2: 网络层
├── 网络分段
├── IDS/IPS
└── 网络监控
Layer 3: 应用层
├── 输入验证
├── 身份认证
└── 授权控制
Layer 4: 数据层
├── 加密
├── 访问控制
└── 备份/恢复
Layer 5: 终端层
├── EDR
├── 补丁管理
└── 配置管理references/owasp_testing.mdreferences/threat_modeling.mdreferences/incident_response.mdreferences/compliance_checklist.mdreferences/owasp_testing.mdreferences/threat_modeling.mdreferences/incident_response.mdreferences/compliance_checklist.mdundefinedundefinedundefinedundefined