security-review
Security review and hardening patterns.
how to use
Do not rewrite entire files. Prefer minimal, targeted fixes.
when to apply
Reference these guidelines when:
- reviewing code for security vulnerabilities
- implementing authentication or authorization
- handling user input or external data
- configuring CORS, CSP, or CSRF protections
- writing Dockerfiles or container configs
- managing secrets or credentials
- setting up API endpoints
rule categories by priority
| priority |
category |
impact |
| 1 |
secrets management |
critical |
| 2 |
input validation |
critical |
| 3 |
authentication |
critical |
| 4 |
authorization |
critical |
| 5 |
injection prevention |
critical |
| 6 |
transport security |
high |
| 7 |
container security |
high |
| 8 |
headers and policies |
medium |
| 9 |
logging and monitoring |
medium |
quick reference
1. secrets management (critical)
- never hardcode secrets, API keys, tokens, or passwords in source code
- use environment variables or dedicated secrets managers (AWS Secrets Manager, Vault)
- add sensitive file patterns to
.gitignore: .env, *.pem, *.key, credentials.*
- rotate credentials immediately if committed to version control
- use
git-secrets or trufflehog for pre-commit scanning
- separate secrets by environment (dev/staging/prod)
2. input validation (critical)
- validate ALL external input at system boundaries (user input, API payloads, query params, headers)
- use allowlists over denylists
- validate type, length, range, and format
- sanitize output based on context (HTML, SQL, shell, URL)
- reject unexpected input early; fail closed
- never trust client-side validation alone
3. authentication (critical)
- use established libraries (passport, next-auth, django-auth) over custom implementations
- enforce strong password policies (min 12 chars, complexity)
- implement rate limiting on login endpoints
- use bcrypt/argon2 for password hashing (never MD5/SHA1)
- implement account lockout after repeated failures
- use secure session management (HttpOnly, Secure, SameSite cookies)
- implement MFA where possible
4. authorization (critical)
- enforce least privilege principle
- validate permissions server-side on every request
- use role-based (RBAC) or attribute-based (ABAC) access control
- never rely on hidden URLs or client-side role checks
- verify resource ownership before access (IDOR prevention)
- log authorization failures
5. injection prevention (critical)
- SQL: use parameterized queries / prepared statements; never string concatenation
- XSS: escape output by context; use framework auto-escaping (React JSX, Jinja2 autoescape)
- Command injection: avoid
os.system(), exec(), eval(); use subprocess with argument lists
- Path traversal: validate and canonicalize file paths; reject
.. sequences
- SSRF: validate and allowlist outbound URLs; block internal network ranges
- Template injection: never pass user input to template engines as template code
6. transport security (high)
- enforce HTTPS everywhere; redirect HTTP to HTTPS
- use TLS 1.2+ only; disable older protocols
- implement HSTS with long max-age
- validate SSL certificates; never disable verification in production
- use certificate pinning for mobile apps
7. container security (high)
- use minimal base images (alpine, distroless)
- run as non-root user
- pin image versions with digest hashes
- scan images for vulnerabilities (trivy, snyk)
- never store secrets in Docker images or layers
- use multi-stage builds to exclude build tools
- set read-only filesystem where possible
- limit container capabilities and resources
8. headers and policies (medium)
- set
Content-Security-Policy to restrict resource loading
- set
X-Content-Type-Options: nosniff
- set
X-Frame-Options: DENY (or use CSP frame-ancestors)
- configure CORS with specific origins; never use
* in production
- implement CSRF tokens for state-changing requests
- set
Referrer-Policy: strict-origin-when-cross-origin
9. logging and monitoring (medium)
- log authentication events (login, logout, failures)
- log authorization failures and privilege escalation attempts
- never log sensitive data (passwords, tokens, PII)
- implement alerting for anomalous patterns
- retain logs with appropriate rotation and access controls
- use structured logging (JSON) for machine parsing
common fixes
| problem |
fix |
| hardcoded API key |
move to env var, add to .gitignore, rotate key |
| SQL concatenation |
switch to parameterized query |
eval() with user input |
remove eval; use safe alternatives |
| missing CSRF token |
add CSRF middleware/token to forms |
| HTTP-only endpoint |
add TLS, redirect HTTP to HTTPS |
| root container user |
add USER nonroot to Dockerfile |
CORS: * |
specify allowed origins explicitly |
| bare except clause |
catch specific exceptions; log details |
secrets scanning in repositories (gitGraber patterns)
GitHub Dork Patterns
Search for accidentally committed secrets using targeted queries:
# API keys
"api_key" OR "apikey" OR "api-key" filename:.env
"AKIA" filename:.py OR filename:.js # AWS access keys
"sk-" filename:.py # OpenAI keys
"ghp_" OR "ghu_" OR "ghs_" filename:.env # GitHub tokens
# Database credentials
"DB_PASSWORD" OR "DATABASE_URL" filename:.env
"mongodb+srv://" filename:.py OR filename:.js
"postgres://" filename:.yml
# Private keys
"BEGIN RSA PRIVATE KEY" OR "BEGIN EC PRIVATE KEY"
"BEGIN OPENSSH PRIVATE KEY"
Pre-Commit Secret Prevention
# Install git-secrets
brew install git-secrets
# Register AWS patterns
git secrets --register-aws
# Add custom patterns
git secrets --add 'AKIA[0-9A-Z]{16}' # AWS access key
git secrets --add 'sk-[a-zA-Z0-9]{48}' # OpenAI key
git secrets --add 'ghp_[a-zA-Z0-9]{36}' # GitHub PAT
# Install hooks
git secrets --install
Automated Scanning
# TruffleHog: scan git history for secrets
trufflehog git file://. --only-verified
# Scan specific branch
trufflehog git file://. --branch main --only-verified
# Trivy: scan filesystem
trivy fs --scanners secret .
CI/CD security rules (from awesome-cicd-security)
pipeline hardening checklist
supply chain security
| Attack Vector |
Mitigation |
| Dependency confusion |
Pin versions, use lock files, verify checksums |
| Compromised action |
Pin to SHA, audit source code |
| Stolen CI secrets |
OIDC, short-lived tokens, secret rotation |
| Build tampering |
Reproducible builds, SLSA provenance |
| Registry poisoning |
Image signing (cosign), digest pinning |
cross-references
- offensive-security skill: Penetration testing methodology
- osint-recon skill: OSINT investigation workflows
- SECURITY_PLAYBOOK.md: 36 security rules
- SECURITY_ARSENAL.md: Complete tool inventory
- devops-patterns skill: CI/CD pipeline patterns
1---2name: security-review3description: Security review and hardening patterns. OWASP Top 10 checklist, secrets scanning, auth patterns, input validation, and container security. Use when auditing code, reviewing PRs for security, or implementing auth/authz.4---56# security-review78Security review and hardening patterns.910## how to use1112- `/security-review`13 Apply these security constraints to all code in this conversation.1415- `/security-review <file>`16 Review the file against all rules below and report:17 - violations (quote the exact line or snippet)18 - severity (critical / high / medium / low)19 - a concrete fix (code-level suggestion)2021Do not rewrite entire files. Prefer minimal, targeted fixes.2223## when to apply2425Reference these guidelines when:26- reviewing code for security vulnerabilities27- implementing authentication or authorization28- handling user input or external data29- configuring CORS, CSP, or CSRF protections30- writing Dockerfiles or container configs31- managing secrets or credentials32- setting up API endpoints3334## rule categories by priority3536| priority | category | impact |37|----------|----------|--------|38| 1 | secrets management | critical |39| 2 | input validation | critical |40| 3 | authentication | critical |41| 4 | authorization | critical |42| 5 | injection prevention | critical |43| 6 | transport security | high |44| 7 | container security | high |45| 8 | headers and policies | medium |46| 9 | logging and monitoring | medium |4748## quick reference4950### 1. secrets management (critical)5152- never hardcode secrets, API keys, tokens, or passwords in source code53- use environment variables or dedicated secrets managers (AWS Secrets Manager, Vault)54- add sensitive file patterns to `.gitignore`: `.env`, `*.pem`, `*.key`, `credentials.*`55- rotate credentials immediately if committed to version control56- use `git-secrets` or `trufflehog` for pre-commit scanning57- separate secrets by environment (dev/staging/prod)5859### 2. input validation (critical)6061- validate ALL external input at system boundaries (user input, API payloads, query params, headers)62- use allowlists over denylists63- validate type, length, range, and format64- sanitize output based on context (HTML, SQL, shell, URL)65- reject unexpected input early; fail closed66- never trust client-side validation alone6768### 3. authentication (critical)6970- use established libraries (passport, next-auth, django-auth) over custom implementations71- enforce strong password policies (min 12 chars, complexity)72- implement rate limiting on login endpoints73- use bcrypt/argon2 for password hashing (never MD5/SHA1)74- implement account lockout after repeated failures75- use secure session management (HttpOnly, Secure, SameSite cookies)76- implement MFA where possible7778### 4. authorization (critical)7980- enforce least privilege principle81- validate permissions server-side on every request82- use role-based (RBAC) or attribute-based (ABAC) access control83- never rely on hidden URLs or client-side role checks84- verify resource ownership before access (IDOR prevention)85- log authorization failures8687### 5. injection prevention (critical)8889- **SQL**: use parameterized queries / prepared statements; never string concatenation90- **XSS**: escape output by context; use framework auto-escaping (React JSX, Jinja2 autoescape)91- **Command injection**: avoid `os.system()`, `exec()`, `eval()`; use subprocess with argument lists92- **Path traversal**: validate and canonicalize file paths; reject `..` sequences93- **SSRF**: validate and allowlist outbound URLs; block internal network ranges94- **Template injection**: never pass user input to template engines as template code9596### 6. transport security (high)9798- enforce HTTPS everywhere; redirect HTTP to HTTPS99- use TLS 1.2+ only; disable older protocols100- implement HSTS with long max-age101- validate SSL certificates; never disable verification in production102- use certificate pinning for mobile apps103104### 7. container security (high)105106- use minimal base images (alpine, distroless)107- run as non-root user108- pin image versions with digest hashes109- scan images for vulnerabilities (trivy, snyk)110- never store secrets in Docker images or layers111- use multi-stage builds to exclude build tools112- set read-only filesystem where possible113- limit container capabilities and resources114115### 8. headers and policies (medium)116117- set `Content-Security-Policy` to restrict resource loading118- set `X-Content-Type-Options: nosniff`119- set `X-Frame-Options: DENY` (or use CSP frame-ancestors)120- configure CORS with specific origins; never use `*` in production121- implement CSRF tokens for state-changing requests122- set `Referrer-Policy: strict-origin-when-cross-origin`123124### 9. logging and monitoring (medium)125126- log authentication events (login, logout, failures)127- log authorization failures and privilege escalation attempts128- never log sensitive data (passwords, tokens, PII)129- implement alerting for anomalous patterns130- retain logs with appropriate rotation and access controls131- use structured logging (JSON) for machine parsing132133## common fixes134135| problem | fix |136|---------|-----|137| hardcoded API key | move to env var, add to .gitignore, rotate key |138| SQL concatenation | switch to parameterized query |139| `eval()` with user input | remove eval; use safe alternatives |140| missing CSRF token | add CSRF middleware/token to forms |141| HTTP-only endpoint | add TLS, redirect HTTP to HTTPS |142| root container user | add `USER nonroot` to Dockerfile |143| `CORS: *` | specify allowed origins explicitly |144| bare except clause | catch specific exceptions; log details |145146## secrets scanning in repositories (gitGraber patterns)147148### GitHub Dork Patterns149Search for accidentally committed secrets using targeted queries:150151```152# API keys153"api_key" OR "apikey" OR "api-key" filename:.env154"AKIA" filename:.py OR filename:.js # AWS access keys155"sk-" filename:.py # OpenAI keys156"ghp_" OR "ghu_" OR "ghs_" filename:.env # GitHub tokens157158# Database credentials159"DB_PASSWORD" OR "DATABASE_URL" filename:.env160"mongodb+srv://" filename:.py OR filename:.js161"postgres://" filename:.yml162163# Private keys164"BEGIN RSA PRIVATE KEY" OR "BEGIN EC PRIVATE KEY"165"BEGIN OPENSSH PRIVATE KEY"166```167168### Pre-Commit Secret Prevention169```bash170# Install git-secrets171brew install git-secrets172173# Register AWS patterns174git secrets --register-aws175176# Add custom patterns177git secrets --add 'AKIA[0-9A-Z]{16}' # AWS access key178git secrets --add 'sk-[a-zA-Z0-9]{48}' # OpenAI key179git secrets --add 'ghp_[a-zA-Z0-9]{36}' # GitHub PAT180181# Install hooks182git secrets --install183```184185### Automated Scanning186```bash187# TruffleHog: scan git history for secrets188trufflehog git file://. --only-verified189190# Scan specific branch191trufflehog git file://. --branch main --only-verified192193# Trivy: scan filesystem194trivy fs --scanners secret .195```196197## CI/CD security rules (from awesome-cicd-security)198199### pipeline hardening checklist200201- [ ] Pin all GitHub Action versions to full SHA (not tags)202- [ ] Set minimum `permissions` block in workflows (never use `write-all`)203- [ ] Use OIDC for cloud authentication (no long-lived secrets)204- [ ] Enable branch protection: require reviews + status checks205- [ ] Scan dependencies: Dependabot/Renovate + vulnerability alerts206- [ ] Run SAST (Semgrep/CodeQL) on every PR207- [ ] Scan container images (Trivy) before pushing208- [ ] Never log secrets — use masking in CI output209- [ ] Separate build and deploy with approval gates210- [ ] Audit third-party actions before using (check source, publisher)211- [ ] Sign artifacts and container images212- [ ] Use ephemeral runners when possible213214### supply chain security215216| Attack Vector | Mitigation |217|--------------|------------|218| Dependency confusion | Pin versions, use lock files, verify checksums |219| Compromised action | Pin to SHA, audit source code |220| Stolen CI secrets | OIDC, short-lived tokens, secret rotation |221| Build tampering | Reproducible builds, SLSA provenance |222| Registry poisoning | Image signing (cosign), digest pinning |223224## cross-references225226- **offensive-security** skill: Penetration testing methodology227- **osint-recon** skill: OSINT investigation workflows228- **SECURITY_PLAYBOOK.md**: 36 security rules229- **SECURITY_ARSENAL.md**: Complete tool inventory230- **devops-patterns** skill: CI/CD pipeline patterns