Security Expert
Expert guidance for application security, vulnerability assessment, penetration testing, OWASP Top 10, secure coding practices, and security architecture.
Core Concepts
Security Principles
- Defense in depth
- Least privilege
- Secure by default
- Fail securely
- Complete mediation
- Separation of duties
- Zero trust architecture
OWASP Top 10 (2021)
- Broken Access Control
- Cryptographic Failures
- Injection
- Insecure Design
- Security Misconfiguration
- Vulnerable and Outdated Components
- Identification and Authentication Failures
- Software and Data Integrity Failures
- Security Logging and Monitoring Failures
- Server-Side Request Forgery (SSRF)
Security Domains
- Authentication & Authorization
- Cryptography
- Input validation
- Session management
- Error handling
- Secure communications
- Data protection
Cryptography
Encryption at Rest
const crypto = require('crypto');
const ALGORITHM = 'aes-256-gcm';
const KEY = Buffer.from(process.env.ENCRYPTION_KEY, 'hex'); // 32 bytes
function encrypt(plaintext) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return {
iv: iv.toString('hex'),
encrypted,
authTag: authTag.toString('hex'),
};
}
function decrypt(iv, encrypted, authTag) {
const decipher = crypto.createDecipheriv(
ALGORITHM,
KEY,
Buffer.from(iv, 'hex')
);
decipher.setAuthTag(Buffer.from(authTag, 'hex'));
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Store sensitive data
async function storeSensitiveData(userId, data) {
const { iv, encrypted, authTag } = encrypt(JSON.stringify(data));
await db.sensitiveData.create({
userId,
iv,
encrypted,
authTag,
});
}
Secure Random Generation
// ✅ Cryptographically secure random
const crypto = require('crypto');
function generateSecureToken(length = 32) {
return crypto.randomBytes(length).toString('hex');
}
function generateSecureId() {
return crypto.randomUUID();
}
// ❌ Don't use Math.random() for security
const insecureToken = Math.random().toString(36); // Predictable!
Input Validation
const { body, validationResult } = require('express-validator');
app.post(
'/api/users',
// Validation rules
body('email').isEmail().normalizeEmail(),
body('name').trim().isLength({ min: 2, max: 100 }).escape(),
body('age').optional().isInt({ min: 18, max: 120 }),
body('website').optional().isURL(),
async (req, res) => {
// Check validation results
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process validated data
const user = await User.create(req.body);
res.status(201).json(user);
}
);
// File upload validation
const multer = require('multer');
const upload = multer({
limits: {
fileSize: 5 * 1024 * 1024, // 5MB max
},
fileFilter: (req, file, cb) => {
// Check file type
const allowedMimes = ['image/jpeg', 'image/png', 'image/gif'];
if (!allowedMimes.includes(file.mimetype)) {
return cb(new Error('Invalid file type'));
}
// Check file extension
const ext = path.extname(file.originalname).toLowerCase();
if (!['.jpg', '.jpeg', '.png', '.gif'].includes(ext)) {
return cb(new Error('Invalid file extension'));
}
cb(null, true);
},
});
app.post('/upload', upload.single('image'), (req, res) => {
// Verify file content matches extension
// Store with random filename to prevent path traversal
const filename = `${crypto.randomUUID()}${path.extname(req.file.originalname)}`;
// Save file...
});
Security Headers
const helmet = require('helmet');
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Avoid unsafe-inline in production
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
frameguard: {
action: 'deny',
},
noSniff: true,
xssFilter: true,
})
);
// Additional headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
res.setHeader(
'Permissions-Policy',
'geolocation=(), microphone=(), camera=()'
);
next();
});
Secure Logging
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
// Log security events
function logSecurityEvent(event, details) {
logger.warn('Security Event', {
event,
...details,
timestamp: new Date().toISOString(),
});
}
// Failed login attempts
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || !(await verifyPassword(password, user.passwordHash))) {
logSecurityEvent('failed_login', {
email,
ip: req.ip,
userAgent: req.headers['user-agent'],
});
return res.status(401).json({ error: 'Invalid credentials' });
}
// Success
logSecurityEvent('successful_login', {
userId: user.id,
ip: req.ip,
});
// Generate tokens...
});
// ❌ Don't log sensitive data
logger.info('User data', user); // May contain passwordHash, tokens
// ✅ Sanitize before logging
logger.info('User data', {
id: user.id,
email: user.email,
// Omit sensitive fields
});
Best Practices
Secure Development Lifecycle
- Threat modeling
- Security requirements
- Secure coding standards
- Code review
- Security testing (SAST/DAST)
- Vulnerability scanning
- Penetration testing
- Security monitoring
Defense in Depth
- Multiple layers of security
- Assume breach mentality
- Principle of least privilege
- Input validation at every layer
- Output encoding
- Secure configuration
Security Testing
- Static Application Security Testing (SAST)
- Dynamic Application Security Testing (DAST)
- Interactive Application Security Testing (IAST)
- Software Composition Analysis (SCA)
- Penetration testing
- Bug bounty programs
Anti-Patterns to Avoid
❌ Storing passwords in plaintext: Always hash with bcrypt/argon2
❌ Rolling your own crypto: Use established libraries
❌ Trusting user input: Validate and sanitize everything
❌ Exposing sensitive errors: Use generic error messages
❌ No rate limiting: Implement rate limiting on all endpoints
❌ Weak session management: Use secure, httpOnly cookies
❌ No logging: Log security events for monitoring
❌ Hardcoded secrets: Use environment variables
Reference Documentation
Detailed material lives alongside this skill and is read on demand:
- Authentication & Authorization — Password Security, JWT Authentication, Multi-Factor Authentication (MFA)
- OWASP Top 10 Vulnerabilities — Broken Access Control, Injection (SQL, NoSQL, Command), Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Security Misconfiguration
Resources
1---2name: security-expert3version: 1.1.04description: >-5 Expert-level application security, OWASP Top 10, penetration testing, and security best6 practices. Use when the user mentions OWASP, pentesting, appsec, vulnerability,7 encryption, or authentication, or when the task involves Security Principles, OWASP Top8 10, Security Domains, or Broken Access Control.9category: security10tags:11 [security, owasp, pentest, appsec, vulnerability, encryption, authentication]12allowed-tools:13 - Read14 - Write15 - Edit16 - Bash(nmap:*, burpsuite:*, zap:*)17metadata:18 source: https://skillmd.com/skills/personamanagmentlayer/security-expert19---2021# Security Expert2223Expert guidance for application security, vulnerability assessment, penetration testing, OWASP Top 10, secure coding practices, and security architecture.2425## Core Concepts2627### Security Principles2829- Defense in depth30- Least privilege31- Secure by default32- Fail securely33- Complete mediation34- Separation of duties35- Zero trust architecture3637### OWASP Top 10 (2021)38391. Broken Access Control402. Cryptographic Failures413. Injection424. Insecure Design435. Security Misconfiguration446. Vulnerable and Outdated Components457. Identification and Authentication Failures468. Software and Data Integrity Failures479. Security Logging and Monitoring Failures4810. Server-Side Request Forgery (SSRF)4950### Security Domains5152- Authentication & Authorization53- Cryptography54- Input validation55- Session management56- Error handling57- Secure communications58- Data protection5960## Cryptography6162### Encryption at Rest6364```javascript65const crypto = require('crypto');6667const ALGORITHM = 'aes-256-gcm';68const KEY = Buffer.from(process.env.ENCRYPTION_KEY, 'hex'); // 32 bytes6970function encrypt(plaintext) {71 const iv = crypto.randomBytes(16);72 const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);7374 let encrypted = cipher.update(plaintext, 'utf8', 'hex');75 encrypted += cipher.final('hex');7677 const authTag = cipher.getAuthTag();7879 return {80 iv: iv.toString('hex'),81 encrypted,82 authTag: authTag.toString('hex'),83 };84}8586function decrypt(iv, encrypted, authTag) {87 const decipher = crypto.createDecipheriv(88 ALGORITHM,89 KEY,90 Buffer.from(iv, 'hex')91 );9293 decipher.setAuthTag(Buffer.from(authTag, 'hex'));9495 let decrypted = decipher.update(encrypted, 'hex', 'utf8');96 decrypted += decipher.final('utf8');9798 return decrypted;99}100101// Store sensitive data102async function storeSensitiveData(userId, data) {103 const { iv, encrypted, authTag } = encrypt(JSON.stringify(data));104105 await db.sensitiveData.create({106 userId,107 iv,108 encrypted,109 authTag,110 });111}112```113114### Secure Random Generation115116```javascript117// ✅ Cryptographically secure random118const crypto = require('crypto');119120function generateSecureToken(length = 32) {121 return crypto.randomBytes(length).toString('hex');122}123124function generateSecureId() {125 return crypto.randomUUID();126}127128// ❌ Don't use Math.random() for security129const insecureToken = Math.random().toString(36); // Predictable!130```131132## Input Validation133134```javascript135const { body, validationResult } = require('express-validator');136137app.post(138 '/api/users',139 // Validation rules140 body('email').isEmail().normalizeEmail(),141 body('name').trim().isLength({ min: 2, max: 100 }).escape(),142 body('age').optional().isInt({ min: 18, max: 120 }),143 body('website').optional().isURL(),144145 async (req, res) => {146 // Check validation results147 const errors = validationResult(req);148 if (!errors.isEmpty()) {149 return res.status(400).json({ errors: errors.array() });150 }151152 // Process validated data153 const user = await User.create(req.body);154 res.status(201).json(user);155 }156);157158// File upload validation159const multer = require('multer');160161const upload = multer({162 limits: {163 fileSize: 5 * 1024 * 1024, // 5MB max164 },165 fileFilter: (req, file, cb) => {166 // Check file type167 const allowedMimes = ['image/jpeg', 'image/png', 'image/gif'];168 if (!allowedMimes.includes(file.mimetype)) {169 return cb(new Error('Invalid file type'));170 }171172 // Check file extension173 const ext = path.extname(file.originalname).toLowerCase();174 if (!['.jpg', '.jpeg', '.png', '.gif'].includes(ext)) {175 return cb(new Error('Invalid file extension'));176 }177178 cb(null, true);179 },180});181182app.post('/upload', upload.single('image'), (req, res) => {183 // Verify file content matches extension184 // Store with random filename to prevent path traversal185 const filename = `${crypto.randomUUID()}${path.extname(req.file.originalname)}`;186 // Save file...187});188```189190## Security Headers191192```javascript193const helmet = require('helmet');194195app.use(196 helmet({197 contentSecurityPolicy: {198 directives: {199 defaultSrc: ["'self'"],200 scriptSrc: ["'self'", "'unsafe-inline'"], // Avoid unsafe-inline in production201 styleSrc: ["'self'", "'unsafe-inline'"],202 imgSrc: ["'self'", 'data:', 'https:'],203 connectSrc: ["'self'"],204 fontSrc: ["'self'"],205 objectSrc: ["'none'"],206 mediaSrc: ["'self'"],207 frameSrc: ["'none'"],208 },209 },210 hsts: {211 maxAge: 31536000,212 includeSubDomains: true,213 preload: true,214 },215 frameguard: {216 action: 'deny',217 },218 noSniff: true,219 xssFilter: true,220 })221);222223// Additional headers224app.use((req, res, next) => {225 res.setHeader('X-Content-Type-Options', 'nosniff');226 res.setHeader('X-Frame-Options', 'DENY');227 res.setHeader('X-XSS-Protection', '1; mode=block');228 res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');229 res.setHeader(230 'Permissions-Policy',231 'geolocation=(), microphone=(), camera=()'232 );233 next();234});235```236237## Secure Logging238239```javascript240const winston = require('winston');241242const logger = winston.createLogger({243 level: 'info',244 format: winston.format.json(),245 transports: [246 new winston.transports.File({ filename: 'error.log', level: 'error' }),247 new winston.transports.File({ filename: 'combined.log' }),248 ],249});250251// Log security events252function logSecurityEvent(event, details) {253 logger.warn('Security Event', {254 event,255 ...details,256 timestamp: new Date().toISOString(),257 });258}259260// Failed login attempts261app.post('/login', async (req, res) => {262 const { email, password } = req.body;263 const user = await User.findOne({ email });264265 if (!user || !(await verifyPassword(password, user.passwordHash))) {266 logSecurityEvent('failed_login', {267 email,268 ip: req.ip,269 userAgent: req.headers['user-agent'],270 });271272 return res.status(401).json({ error: 'Invalid credentials' });273 }274275 // Success276 logSecurityEvent('successful_login', {277 userId: user.id,278 ip: req.ip,279 });280281 // Generate tokens...282});283284// ❌ Don't log sensitive data285logger.info('User data', user); // May contain passwordHash, tokens286287// ✅ Sanitize before logging288logger.info('User data', {289 id: user.id,290 email: user.email,291 // Omit sensitive fields292});293```294295## Best Practices296297### Secure Development Lifecycle2982991. Threat modeling3002. Security requirements3013. Secure coding standards3024. Code review3035. Security testing (SAST/DAST)3046. Vulnerability scanning3057. Penetration testing3068. Security monitoring307308### Defense in Depth309310- Multiple layers of security311- Assume breach mentality312- Principle of least privilege313- Input validation at every layer314- Output encoding315- Secure configuration316317### Security Testing318319- Static Application Security Testing (SAST)320- Dynamic Application Security Testing (DAST)321- Interactive Application Security Testing (IAST)322- Software Composition Analysis (SCA)323- Penetration testing324- Bug bounty programs325326## Anti-Patterns to Avoid327328❌ **Storing passwords in plaintext**: Always hash with bcrypt/argon2329❌ **Rolling your own crypto**: Use established libraries330❌ **Trusting user input**: Validate and sanitize everything331❌ **Exposing sensitive errors**: Use generic error messages332❌ **No rate limiting**: Implement rate limiting on all endpoints333❌ **Weak session management**: Use secure, httpOnly cookies334❌ **No logging**: Log security events for monitoring335❌ **Hardcoded secrets**: Use environment variables336337## Reference Documentation338339Detailed material lives alongside this skill and is read on demand:340341- [Authentication & Authorization](references/AUTHENTICATION_AUTHORIZATION.md) — Password Security, JWT Authentication, Multi-Factor Authentication (MFA)342- [OWASP Top 10 Vulnerabilities](references/OWASP_TOP_10_VULNERABILITIES.md) — Broken Access Control, Injection (SQL, NoSQL, Command), Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Security Misconfiguration343344## Resources345346- OWASP: https://owasp.org/347- OWASP Top 10: https://owasp.org/Top10/348- CWE Top 25: https://cwe.mitre.org/top25/349- NIST Guidelines: https://www.nist.gov/cybersecurity350- Security Headers: https://securityheaders.com/351- SSL Labs: https://www.ssllabs.com/