security-expert
Expert-level application security, OWASP Top 10, penetration testing, and security best practices
What this skill does
# 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)
1. Broken Access Control
2. Cryptographic Failures
3. Injection
4. Insecure Design
5. Security Misconfiguration
6. Vulnerable and Outdated Components
7. Identification and Authentication Failures
8. Software and Data Integrity Failures
9. Security Logging and Monitoring Failures
10. Server-Side Request Forgery (SSRF)
### Security Domains
- Authentication & Authorization
- Cryptography
- Input validation
- Session management
- Error handling
- Secure communications
- Data protection
## OWASP Top 10 Vulnerabilities
### 1. Broken Access Control
```javascript
// ❌ Vulnerable: No authorization check
app.get('/api/users/:id/profile', async (req, res) => {
const profile = await db.users.findById(req.params.id);
res.json(profile);
});
// ✅ Secure: Verify user owns the resource
app.get('/api/users/:id/profile', authenticate, async (req, res) => {
if (req.user.id !== req.params.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
const profile = await db.users.findById(req.params.id);
res.json(profile);
});
// ✅ Better: Use middleware
const authorizeResource = (resourceType) => async (req, res, next) => {
const resourceId = req.params.id;
const resource = await db[resourceType].findById(resourceId);
if (!resource) {
return res.status(404).json({ error: 'Not found' });
}
if (resource.userId !== req.user.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
req.resource = resource;
next();
};
app.delete('/api/posts/:id', authenticate, authorizeResource('posts'), async (req, res) => {
await req.resource.delete();
res.status(204).send();
});
```
### 2. Injection (SQL, NoSQL, Command)
```javascript
// ❌ SQL Injection vulnerability
app.get('/users', (req, res) => {
const query = `SELECT * FROM users WHERE name = '${req.query.name}'`;
db.query(query, (err, results) => {
res.json(results);
});
});
// Attack: ?name=' OR '1'='1
// ✅ Secure: Use parameterized queries
app.get('/users', async (req, res) => {
const results = await db.query(
'SELECT * FROM users WHERE name = ?',
[req.query.name]
);
res.json(results);
});
// ❌ Command Injection
const { exec } = require('child_process');
app.post('/convert', (req, res) => {
exec(`convert ${req.body.filename} output.pdf`, (err, stdout) => {
res.send(stdout);
});
});
// Attack: filename="; rm -rf / #"
// ✅ Secure: Use safe APIs, validate input
const { spawn } = require('child_process');
app.post('/convert', (req, res) => {
const filename = path.basename(req.body.filename); // Remove path traversal
if (!/^[a-zA-Z0-9_-]+\.(jpg|png)$/.test(filename)) {
return res.status(400).json({ error: 'Invalid filename' });
}
const process = spawn('convert', [filename, 'output.pdf']);
// Handle process output safely
});
// ❌ NoSQL Injection (MongoDB)
app.post('/login', async (req, res) => {
const user = await User.findOne({
username: req.body.username,
password: req.body.password
});
});
// Attack: {"username": {"$ne": null}, "password": {"$ne": null}}
// ✅ Secure: Sanitize input, use proper types
app.post('/login', async (req, res) => {
const { username, password } = req.body;
if (typeof username !== 'string' || typeof password !== 'string') {
return res.status(400).json({ error: 'Invalid input' });
}
const user = await User.findOne({ username });
if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Create session
});
```
### 3. Cross-Site Scripting (XSS)
```javascript
// ❌ Reflected XSS
app.get('/search', (req, res) => {
res.send(`<h1>Results for: ${req.query.q}</h1>`);
});
// Attack: ?q=<script>alert(document.cookie)</script>
// ✅ Secure: Escape output
const escapeHtml = (unsafe) => {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
};
app.get('/search', (req, res) => {
res.send(`<h1>Results for: ${escapeHtml(req.query.q)}</h1>`);
});
// ✅ Better: Use templating engine with auto-escaping
app.get('/search', (req, res) => {
res.render('search', { query: req.query.q }); // Automatically escaped
});
// ✅ Content Security Policy
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;"
);
next();
});
```
### 4. Cross-Site Request Forgery (CSRF)
```javascript
// ❌ Vulnerable: No CSRF protection
app.post('/api/transfer', authenticate, async (req, res) => {
await transferMoney(req.user.id, req.body.to, req.body.amount);
res.json({ success: true });
});
// ✅ Secure: Use CSRF tokens
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });
app.get('/transfer', csrfProtection, (req, res) => {
res.render('transfer', { csrfToken: req.csrfToken() });
});
app.post('/api/transfer', csrfProtection, authenticate, async (req, res) => {
await transferMoney(req.user.id, req.body.to, req.body.amount);
res.json({ success: true });
});
// ✅ Also use SameSite cookies
app.use(session({
cookie: {
httpOnly: true,
secure: true,
sameSite: 'strict'
}
}));
```
### 5. Security Misconfiguration
```javascript
// ❌ Exposed sensitive information
app.use((err, req, res, next) => {
res.status(500).json({
error: err.message,
stack: err.stack // Exposes internal details
});
});
// ✅ Secure: Generic error messages
app.use((err, req, res, next) => {
console.error(err); // Log internally
if (process.env.NODE_ENV === 'production') {
res.status(500).json({ error: 'Internal server error' });
} else {
res.status(500).json({ error: err.message, stack: err.stack });
}
});
// ✅ Security headers
const helmet = require('helmet');
app.use(helmet());
// ✅ Disable unnecessary features
app.disable('x-powered-by');
// ✅ Rate limiting
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/api/', limiter);
```
## Authentication & Authorization
### Password Security
```javascript
const bcrypt = require('bcrypt');
const SALT_ROUNDS = 12;
// Hash password
async function hashPassword(password) {
// Validate password strength
if (password.length < 12) {
throw new Error('Password must be at least 12 characters');
}
if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) ||
!/[0-9]/.test(password) || !/[^A-Za-z0-9]/.test(password)) {
throw new Error('Password must contain uppercase, lowercase, number, and special character');
}
return await bcrypt.hash(password, SALT_ROUNDS);
}
// Verify password
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
// Registration
app.post('/register', async (req, res) => {
const { email, password } = req.body;
// Check if user exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: 'Email already registered' });
}
// Hash password
const passwordHash = await hashPassword(password);
// Create user
const user = await User.create({
email: email.toLowerCase(),
passwordHash
});
res.status(201).json({ id: user.id });
});
```
### JWT Authentication
```javascript
const jwt = require('jsonwebtoken');
const JWT_SECRET = process.env.JWT_SECRET; // Use strong secret
const JWT_EXPIRY = '15m';Related in security
web-pentest
IncludedAuthorized web application penetration testing — reconnaissance, vulnerability analysis, proof-based exploitation, and professional reporting. Adapts Shannon's "No Exploit, No Report" methodology with hard guardrails for scope, authorization, and aux-client leakage. Active testing against running applications you own or have written authorization to test.
oss-forensics
IncludedSupply chain investigation, evidence recovery, and forensic analysis for GitHub repositories. Covers deleted commit recovery, force-push detection, IOC extraction, multi-source evidence collection, hypothesis formation/validation, and structured forensic reporting. Inspired by RAPTOR's 1800+ line OSS Forensics system.
agent-skill-trust-check
IncludedStatic pre-install trust review for SKILL.md, OpenClaw, Hermes, MCP, and agent-skill marketplace packages before they request local, account, payment, or external access.
container-security-hardening
IncludedHarden Docker/container images and runtime deployments with secure base images, non-root users, CVE scanning, SBOM/signing, seccomp/AppArmor, and Kubernetes pod security controls. Use for Dockerfile security reviews, container CVEs, image scanning, distroless images, or production hardening.
bumblebee
IncludedRun Bumblebee supply-chain inventory and exposure scans on macOS/Linux to detect compromised packages, extensions, and MCP host configs.
harden
IncludedApplies NIST/CWE security hardening to Python and Rust code. Use when auditing code for vulnerabilities or proposing concrete security remediations.