Loading...
Loading...
Expert security engineering covering application security, infrastructure security, threat modeling, penetration testing, and compliance.
npx skill4agent add borghei/claude-skills senior-security// 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');
}// 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' },
}));| 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 |
# Threat Model: [System Name]
## System Overview
[Description of system and its components]
## Assets
1. User credentials
2. Payment information
3. Personal data
## Trust Boundaries
1. Internet → Load Balancer
2. Load Balancer → Application
3. Application → Database
## Data Flows
[Diagram of data flows]
## Threats Identified
### Threat 1: SQL Injection
- **Category**: Tampering
- **Asset**: Database
- **Attack Vector**: User input to search functionality
- **Impact**: High (full database access)
- **Likelihood**: Medium
- **Mitigation**: Parameterized queries, input validation
## Risk Assessment Matrix
[High/Medium/Low ratings for each threat]
## Recommended Controls
[Prioritized list of mitigations]# Semgrep
semgrep --config=p/owasp-top-ten ./src
# npm audit
npm audit --audit-level=high
# Trivy
trivy fs --severity HIGH,CRITICAL .# OWASP ZAP
zap-cli quick-scan --self-contained -t https://target.com
# Nuclei
nuclei -u https://target.com -t cves/| 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 |
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 managementreferences/owasp_testing.mdreferences/threat_modeling.mdreferences/incident_response.mdreferences/compliance_checklist.md# Security scanner
python scripts/security_scan.py --target ./src --type sast
# Dependency audit
python scripts/dep_audit.py --manifest package.json
# Compliance checker
python scripts/compliance_check.py --framework soc2
# Threat model generator
python scripts/threat_model.py --diagram architecture.yaml