# Security Review Skill

> **OWASP Top 10 checklist, threat modeling, and security best practices.**

---

## 10-Point Security Checklist

### 1. Injection Prevention ✓

```python
# ❌ SQL Injection
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

# ✅ Parameterized query
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
```

```typescript
// ❌ Command injection
exec(`echo ${userInput}`);

// ✅ Safe execution
execFile('echo', [userInput]);
```

### 2. Authentication ✓

- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)
- [ ] JWT tokens have reasonable expiry (15min-1hr)
- [ ] Session tokens are cryptographically random
- [ ] Credentials never logged or in error messages

### 3. Authorization ✓

- [ ] Every endpoint checks permissions
- [ ] Resource ownership verified (IDOR prevention)
- [ ] Admin functions protected
- [ ] API keys have minimal scope

### 4. Data Exposure ✓

- [ ] Sensitive data encrypted at rest
- [ ] PII minimized and protected
- [ ] Error messages don't leak internals
- [ ] Logs sanitize sensitive data

### 5. Security Misconfiguration ✓

- [ ] Debug mode disabled in production
- [ ] Default credentials removed
- [ ] Security headers configured
- [ ] CORS properly restricted

### 6. XSS Prevention ✓

```typescript
// ❌ XSS vulnerable
element.innerHTML = userInput;

// ✅ Safe
element.textContent = userInput;

// ✅ React auto-escapes
<div>{userInput}</div>
```

### 7. Insecure Deserialization ✓

```python
# ❌ Never deserialize untrusted data
pickle.loads(user_data)

# ✅ Use safe formats
json.loads(user_data)
```

### 8. Vulnerable Dependencies ✓

```bash
# Python
pip-audit
safety check

# JavaScript
npm audit
```

### 9. Logging & Monitoring ✓

- [ ] Security events logged
- [ ] Failed auth attempts tracked
- [ ] Anomaly detection configured
- [ ] Logs don't contain secrets

### 10. Secrets Management ✓

- [ ] No hardcoded secrets in code
- [ ] Environment variables for config
- [ ] Secrets rotated regularly
- [ ] .env files in .gitignore

---

## OWASP Top 10 (2021)

| ID | Category | Key Controls |
|----|----------|--------------|
| A01 | Broken Access Control | AuthZ on every request |
| A02 | Cryptographic Failures | TLS, proper hashing |
| A03 | Injection | Parameterized queries |
| A04 | Insecure Design | Threat modeling |
| A05 | Security Misconfiguration | Hardening |
| A06 | Vulnerable Components | Dependency scanning |
| A07 | Auth Failures | Strong auth, session mgmt |
| A08 | Software Integrity | Code signing, SRI |
| A09 | Logging Failures | Audit logs |
| A10 | SSRF | URL validation |

---

## Secret Patterns to Detect

```regex
# AWS Keys
AKIA[0-9A-Z]{16}

# GitHub Tokens
ghp_[a-zA-Z0-9]{36}

# Generic API Keys
(?i)(api[_-]?key|apikey)\s*[:=]\s*['\"][a-zA-Z0-9]{20,}['\"]

# Private Keys
-----BEGIN (RSA|DSA|EC|OPENSSH) PRIVATE KEY-----

# Database URLs
(?i)(postgres|mysql|mongodb)://[^:]+:[^@]+@
```

---

## Security Headers

```python
# Essential headers
response.headers["Content-Security-Policy"] = "default-src 'self'"
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["X-XSS-Protection"] = "1; mode=block"
```

---

## Input Validation

```python
from pydantic import BaseModel, EmailStr, constr

class UserCreate(BaseModel):
    email: EmailStr
    username: constr(min_length=3, max_length=50, regex=r'^[a-zA-Z0-9_]+$')
    password: constr(min_length=8)
```

---

## Related Skills

- [coding-standards](../coding-standards/) - Secure coding patterns
- [backend-patterns](../backend-patterns/) - API security
