| name | security-best-practices |
| description | Security-focused development skill covering OWASP Top 10 and secure coding. Use when implementing authentication, handling user data, or security review. Keywords: security, auth, authentication, authorization, OWASP, XSS, SQL injection, CSRF, secure |
| version | 1.0.0 |
| behaviors | ["review_and_suggest","investigate_codebase","generate_with_validation"] |
| dependencies | [] |
| token_estimate | {"min":1500,"typical":3500,"max":8000} |
🔐 Security Best Practices Skill
Philosophy: Security is not optional. Build it in from the start.
When to Use
Use this skill when:
- Implementing authentication/authorization
- Handling user input
- Working with sensitive data
- Doing security code review
- Building user-facing features
- Setting up deployment/infrastructure
Do NOT use this skill when:
- Just formatting code
- Pure UI/styling changes
- No user data involved
Prerequisites
Before starting:
OWASP Top 10 Quick Reference
1. Broken Access Control (A01:2021)
What: Users can access data/functions they shouldn't.
Prevention:
app.get('/users/:id', async (req, res) => {
const user = await db.users.findById(req.params.id);
res.json(user);
});
app.get('/users/:id', authorize(), async (req, res) => {
const user = await db.users.findById(req.params.id);
if (user.id !== req.user.id && req.user.role !== 'admin') {
throw new ForbiddenException();
}
res.json(user);
});
Checklist:
2. Cryptographic Failures (A02:2021)
What: Weak crypto, exposed sensitive data.
Prevention:
const hash = crypto.createHash('md5').update(password).digest('hex');
const hash = await bcrypt.hash(password, 12);
const API_KEY = "sk_live_abc123";
const API_KEY = process.env.API_KEY;
Checklist:
3. Injection (A03:2021)
What: Malicious data executed as code/query.
Prevention:
const query = `SELECT * FROM users WHERE email = '${email}'`;
const user = await db.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
exec(`convert ${filename} output.png`);
await sharp(filename).toFile('output.png');
Types to Prevent:
- SQL Injection
- NoSQL Injection
- Command Injection
- LDAP Injection
- XPath Injection
Checklist:
4. Insecure Design (A04:2021)
What: Missing security in design phase.
Prevention:
threat_modeling:
assets:
- User credentials
- Payment information
- Personal data
threats:
- Authentication bypass
- Data theft
- Privilege escalation
mitigations:
- MFA for sensitive operations
- Encryption at rest
- Audit logging
Checklist:
5. Security Misconfiguration (A05:2021)
What: Insecure settings, missing hardening.
Prevention:
app.use(express.errorHandler({ dumpExceptions: true }));
if (process.env.NODE_ENV === 'production') {
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ message: 'Internal error' });
});
}
Checklist:
Security Headers:
app.use(helmet());
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('Strict-Transport-Security', 'max-age=31536000');
res.setHeader('Content-Security-Policy', "default-src 'self'");
next();
});
6. Vulnerable Components (A06:2021)
What: Using libraries with known vulnerabilities.
Prevention:
npm audit
pip-audit
dotnet list package --vulnerable
npm audit fix
pip-audit --fix
Checklist:
7. Authentication Failures (A07:2021)
What: Broken login, session management.
Prevention:
const passwordPolicy = {
minLength: 12,
requireUppercase: true,
requireLowercase: true,
requireNumber: true,
requireSpecial: true,
preventCommon: true,
};
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: 'Too many login attempts'
});
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true,
httpOnly: true,
sameSite: 'strict',
maxAge: 3600000
}
}));
Checklist:
8. Software Integrity Failures (A08:2021)
What: Insecure updates, CI/CD pipeline attacks.
Prevention:
package-lock.json
npm ci
ci_security:
- Verify source code integrity
- Sign releases
- Secure deployment pipeline
- Review third-party actions
Checklist:
9. Logging Failures (A09:2021)
What: Insufficient logging for security events.
Prevention:
const securityLogger = {
loginSuccess: (userId: string, ip: string) => {
logger.info('LOGIN_SUCCESS', { userId, ip, timestamp: new Date() });
},
loginFailure: (email: string, ip: string, reason: string) => {
logger.warn('LOGIN_FAILURE', { email, ip, reason, timestamp: new Date() });
},
accessDenied: (userId: string, resource: string, ip: string) => {
logger.warn('ACCESS_DENIED', { userId, resource, ip, timestamp: new Date() });
},
suspiciousActivity: (details: object) => {
logger.error('SUSPICIOUS_ACTIVITY', { ...details, timestamp: new Date() });
}
};
Checklist:
10. SSRF (A10:2021)
What: Server-Side Request Forgery.
Prevention:
const response = await fetch(req.body.url);
const ALLOWED_DOMAINS = ['api.example.com', 'cdn.example.com'];
async function fetchUrl(userUrl: string) {
const parsed = new URL(userUrl);
if (!ALLOWED_DOMAINS.includes(parsed.hostname)) {
throw new Error('Domain not allowed');
}
if (parsed.protocol !== 'https:') {
throw new Error('HTTPS required');
}
return fetch(userUrl);
}
Checklist:
Input Validation Patterns
Universal Validation
const UserSchema = z.object({
email: z.string().email().toLowerCase().trim(),
password: z.string().min(12).max(128),
name: z.string().min(2).max(50).regex(/^[a-zA-Z\s]+$/),
age: z.number().int().min(13).max(120).optional(),
});
class CreateUserDto {
@IsEmail()
@Transform(({ value }) => value.toLowerCase().trim())
email: string;
@IsString()
@MinLength(12)
@MaxLength(128)
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/)
password: string;
@IsString()
@MinLength(2)
@MaxLength(50)
name: string;
}
XSS Prevention
element.innerHTML = userInput;
element.textContent = userInput;
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
Security Testing Checklist
security_tests:
authentication:
- Test login with invalid credentials
- Test brute force protection
- Test session timeout
- Test logout clears session
- Test password reset flow
authorization:
- Test accessing other users' data
- Test admin functions as normal user
- Test direct object references
- Test privilege escalation
input_validation:
- Test SQL injection payloads
- Test XSS payloads
- Test command injection
- Test path traversal
- Test file upload restrictions
configuration:
- Test HTTPS enforcement
- Test security headers present
- Test error messages sanitized
- Test debugging disabled
Guidelines
DO ✅
- Validate all input
- Use parameterized queries
- Hash passwords with bcrypt/argon2
- Log security events
- Keep dependencies updated
- Apply principle of least privilege
DON'T ❌
- Trust user input
- Store secrets in code
- Use weak cryptography
- Expose detailed errors
- Ignore security warnings
- Skip security testing
Success Criteria
Before considering code secure:
Related Skills
skills/kilo-kit/development/backend/ - For API security
skills/kilo-kit/quality/code-review/ - For security review
skills/kilo-kit/debugging/root-cause/ - For security incident analysis
Security Best Practices Skill v1.0.0 — Security is everyone's job