Vulnerability Patterns
SQL Injection
// VULNERABLE
const query = `SELECT * FROM users WHERE id = ${userId}`;
const query = `SELECT * FROM users WHERE name = '${name}'`;
// SECURE - Parameterized queries
const query = 'SELECT * FROM users WHERE id = $1';
db.query(query, [userId]);
// SECURE - ORM
const user = await User.findOne({ where: { id: userId } });
XSS (Cross-Site Scripting)
// VULNERABLE - Direct HTML injection
element.innerHTML = userInput;
document.write(userInput);
// SECURE - Text content
element.textContent = userInput;
// SECURE - Sanitization
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
// SECURE - React (auto-escaped)
return <div>{userInput}</div>;
// VULNERABLE - React dangerouslySetInnerHTML
return <div dangerouslySetInnerHTML={{ __html: userInput }} />;
Path Traversal
// VULNERABLE
const file = path.join(uploadDir, req.query.filename);
res.sendFile(file);
// SECURE - Validate and normalize
const filename = path.basename(req.query.filename);
const file = path.resolve(uploadDir, filename);
if (!file.startsWith(path.resolve(uploadDir))) {
throw new Error('Invalid path');
}
res.sendFile(file);
Command Injection
// VULNERABLE
exec(`ls ${userInput}`);
exec('git clone ' + repoUrl);
// SECURE - Use arrays, avoid shell
execFile('ls', [userInput]);
spawn('git', ['clone', repoUrl]);
// SECURE - Validation
const allowedCommands = ['status', 'log'];
if (!allowedCommands.includes(cmd)) throw new Error('Invalid');
IDOR (Insecure Direct Object Reference)
// VULNERABLE - No authorization check
app.get('/documents/:id', async (req, res) => {
const doc = await Document.findById(req.params.id);
res.json(doc);
});
// SECURE - Verify ownership
app.get('/documents/:id', async (req, res) => {
const doc = await Document.findOne({
_id: req.params.id,
userId: req.user.id // Ensure user owns document
});
if (!doc) return res.status(404).json({ error: 'Not found' });
res.json(doc);
});
Insecure Deserialization
// VULNERABLE - Python pickle
import pickle
data = pickle.loads(user_input)
// SECURE - Use JSON
import json
data = json.loads(user_input)
// VULNERABLE - Node.js
const obj = eval('(' + userInput + ')');
// SECURE
const obj = JSON.parse(userInput);
Sensitive Data Exposure
// VULNERABLE - Logging sensitive data
logger.info('User login', { email, password });
console.log('Token:', authToken);
// SECURE - Redact sensitive fields
logger.info('User login', { email, password: '[REDACTED]' });
// VULNERABLE - Error response exposes internals
res.status(500).json({ error: err.stack });
// SECURE - Generic error
res.status(500).json({ error: 'Internal server error' });
Quick Reference
| Vulnerability |
Input Vector |
Prevention |
| SQL Injection |
Query params |
Parameterized queries |
| XSS |
User content |
Output encoding |
| Path Traversal |
File paths |
path.basename + validation |
| Command Injection |
Shell args |
execFile, no shell |
| IDOR |
Resource IDs |
Authorization checks |
| Deserialization |
Serialized data |
JSON only |
| Data Exposure |
Logs, errors |
Redaction, generic errors |
OWASP Top 10 Mapping
| OWASP |
Vulnerabilities |
| A01 Broken Access Control |
IDOR, path traversal |
| A02 Cryptographic Failures |
Weak encryption, plaintext |
| A03 Injection |
SQL, XSS, command |
| A04 Insecure Design |
Missing auth, IDOR |
| A05 Security Misconfiguration |
Debug mode, default creds |
| A06 Vulnerable Components |
Outdated dependencies |
| A07 Auth Failures |
Weak passwords, session issues |
| A08 Data Integrity |
Insecure deserialization |
| A09 Logging Failures |
Missing logs, exposed data |
| A10 SSRF |
Unvalidated URLs |