Security Audit — Trail of Bits Methodology
Comprehensive security audit combining insecure defaults detection, sharp edges analysis, and supply chain risk assessment. Adapted from Trail of Bits skills.
When to Use
- Pre-deployment security review of the full codebase
- Auditing configuration and secrets management
- Reviewing auth, crypto, API security, payment handling
- Evaluating dependency health and supply chain risk
- Periodic security checkups
When NOT to Use
- Test fixtures in test directories
- Example/template files (
.example, .env.example)
- Development-only configs (local Docker, dev scripts)
- Reviewing a single PR diff (use
/security-review instead)
Part 1: Insecure Defaults Detection
Finds fail-open vulnerabilities where the app runs insecurely with missing configuration.
- Fail-open (CRITICAL):
SECRET = env.get('KEY') or 'default' — App runs with weak secret
- Fail-secure (SAFE):
SECRET = env['KEY'] — App crashes if missing
Search Targets
Identify and scan project-specific high-risk areas, typically including:
- Auth/session secrets — JWT_SECRET, SESSION_KEY, etc. with fallback handling
- Payment/billing keys — Stripe, payment gateway secrets
- Database connections — DATABASE_URL fallback behavior
- CORS configuration — Origin allowlists
- External API keys — Third-party service credentials
- Cache/queue connections — Redis, RabbitMQ fallback behavior
- Debug/verbose modes — Debug flags, error verbosity settings
Search Patterns
# Fallback secrets
getenv.*\) or ['"]
os.environ.get.*default
process\.env\.[A-Z_]+ \|\| ['"]
# Hardcoded credentials
password.*=.*['"][^'"]{8,}['"]
api[_-]?key.*=.*['"][^'"]+['"]
secret.*=.*['"][^'"]+['"]
# Weak defaults
DEBUG.*=.*true|True
AUTH.*=.*false|False
CORS.*=.*\*
verify.*=.*false|False
# Crypto
MD5|SHA1|DES|RC4|ECB in security contexts
Verification Workflow
For each match:
- TRACE: Follow code path — does app run with the default or crash?
- VERIFY: Is this value used in auth/crypto/payment context?
- CHECK PROD: Does the deployment config provide the variable?
- REPORT: With file:line, pattern, exploitation scenario, production impact
Rationalizations to Reject
- "It's just a development default" — If it reaches production code, it's a finding
- "The production config overrides it" — Verify prod config exists
- "We'll fix it before release" — Document now
Part 2: Sharp Edges Analysis
Identifies error-prone APIs, dangerous configurations, and footgun designs.
Sharp Edge Categories
1. Configuration Cliffs
- Auth secrets accepting empty/weak values
- CORS accepting wildcard with credentials
- Cache/queue fallback to in-memory (security implications?)
- Webhook secret validation bypass scenarios
2. Silent Failures
- Auth middleware that silently skips on error
- Webhook signature verification failure handling
- Database connection fallback behavior
3. Input Validation Gaps
- ID/slug format validation
- Numeric field bounds checking
- Pagination: max page_size enforced?
- Request body size limits?
4. SQL Injection Surface
- Any raw SQL usage — ALL queries parameterized?
- Any string interpolation in SQL?
5. Type Confusion
- Token types (access vs refresh) distinguishable?
- Role/tier strings validated against enum?
Python-Specific Patterns (from Trail of Bits)
| Pattern |
Risk |
pickle.loads(user_data) |
Arbitrary code execution |
yaml.load() without safe_load |
Code execution |
subprocess.*(..., shell=True) |
Command injection |
eval(, exec( |
Code execution |
except: or except Exception: pass |
Swallowed security errors |
template.format(user_input) |
Format string injection |
def f(x=[]) mutable defaults |
Shared state bugs |
JavaScript/TypeScript Patterns
| Pattern |
Risk |
== instead of === |
Type coercion bugs |
obj[userInput] |
Prototype pollution |
eval(, new Function( |
Code execution |
as Type assertions |
Runtime type mismatch |
! non-null assertion |
Null pointer crash |
Missing await |
Race conditions |
Edge Case Probing
For each security-relevant API, ask:
- Zero/empty/null: What happens with
0, "", null?
- Negative values: What does
-1 mean?
- Type confusion: Can different security concepts be swapped?
- Default values: Is the default secure?
- Error paths: What happens on invalid input?
Part 3: Supply Chain Risk Audit
Evaluates dependencies for exploitation or takeover risk.
Risk Criteria
A dependency is high-risk if:
- Single maintainer — individual, not org-backed
- Unmaintained — stale, deprecated, archived
- Low popularity — few stars/downloads vs peers
- High-risk features — FFI, deserialization, code execution
- Past CVEs — high/critical severity
- No security contact — no SECURITY.md or responsible disclosure
Workflow
- Enumerate all direct dependencies from manifest files (requirements.txt, package.json, Cargo.toml, etc.)
- For each, check GitHub: stars, last commit, maintainer count, open issues
- Flag high-risk deps in report with risk factors and suggested alternatives
- Run language-appropriate audit tools (
pip audit, npm audit, cargo audit, etc.)
Report Template
# Supply Chain Risk Report
## Metadata
- Scan Date: YYYY-MM-DD
- Dependencies Scanned: N
## High-Risk Dependencies
| Dependency | Risk Factors | Notes | Suggested Alternative |
|------------|-------------|-------|-----------------------|
## Recommendations
Report Format
Generate a markdown report at a suitable location in the project (e.g., tasks/security-audit-report.md):
# Security Audit Report
## Executive Summary
| Severity | Count |
|----------|-------|
| CRITICAL | X |
| HIGH | Y |
| MEDIUM | Z |
| LOW | W |
## Findings
### [SEVERITY] Title
**File**: path:line
**Pattern**: [code pattern found]
**Verification**: [trace result]
**Production Impact**: [exploitability]
**Recommendation**: [specific fix]
## Supply Chain Summary
## Quality Checklist
- [ ] All env var fallbacks checked
- [ ] Auth flow verified
- [ ] Payment/webhook validation confirmed
- [ ] CORS configuration reviewed
- [ ] SQL injection surface audited
- [ ] Dependency audit complete
- [ ] Error handling reviewed (no silent failures)
1---2name: security-audit3description: Comprehensive security audit: detects insecure defaults, hardcoded secrets, sharp edges, supply chain risks, and OWASP vulnerabilities. Based on Trail of Bits methodology. Use when auditing security, reviewing config, or pre-deployment checks. For PR diffs, use /security-review instead.4---56# Security Audit — Trail of Bits Methodology78Comprehensive security audit combining insecure defaults detection, sharp edges analysis, and supply chain risk assessment. Adapted from [Trail of Bits skills](https://github.com/trailofbits/skills).910## When to Use1112- Pre-deployment security review of the full codebase13- Auditing configuration and secrets management14- Reviewing auth, crypto, API security, payment handling15- Evaluating dependency health and supply chain risk16- Periodic security checkups1718## When NOT to Use1920- Test fixtures in test directories21- Example/template files (`.example`, `.env.example`)22- Development-only configs (local Docker, dev scripts)23- Reviewing a single PR diff (use `/security-review` instead)2425---2627## Part 1: Insecure Defaults Detection2829Finds **fail-open** vulnerabilities where the app runs insecurely with missing configuration.3031- **Fail-open (CRITICAL):** `SECRET = env.get('KEY') or 'default'` — App runs with weak secret32- **Fail-secure (SAFE):** `SECRET = env['KEY']` — App crashes if missing3334### Search Targets3536Identify and scan project-specific high-risk areas, typically including:3738- **Auth/session secrets** — JWT_SECRET, SESSION_KEY, etc. with fallback handling39- **Payment/billing keys** — Stripe, payment gateway secrets40- **Database connections** — DATABASE_URL fallback behavior41- **CORS configuration** — Origin allowlists42- **External API keys** — Third-party service credentials43- **Cache/queue connections** — Redis, RabbitMQ fallback behavior44- **Debug/verbose modes** — Debug flags, error verbosity settings4546### Search Patterns4748```49# Fallback secrets50getenv.*\) or ['"]51os.environ.get.*default52process\.env\.[A-Z_]+ \|\| ['"]5354# Hardcoded credentials55password.*=.*['"][^'"]{8,}['"]56api[_-]?key.*=.*['"][^'"]+['"]57secret.*=.*['"][^'"]+['"]5859# Weak defaults60DEBUG.*=.*true|True61AUTH.*=.*false|False62CORS.*=.*\*63verify.*=.*false|False6465# Crypto66MD5|SHA1|DES|RC4|ECB in security contexts67```6869### Verification Workflow7071For each match:721. **TRACE**: Follow code path — does app run with the default or crash?732. **VERIFY**: Is this value used in auth/crypto/payment context?743. **CHECK PROD**: Does the deployment config provide the variable?754. **REPORT**: With file:line, pattern, exploitation scenario, production impact7677### Rationalizations to Reject78- "It's just a development default" — If it reaches production code, it's a finding79- "The production config overrides it" — Verify prod config exists80- "We'll fix it before release" — Document now8182---8384## Part 2: Sharp Edges Analysis8586Identifies error-prone APIs, dangerous configurations, and footgun designs.8788### Sharp Edge Categories8990**1. Configuration Cliffs**91- Auth secrets accepting empty/weak values92- CORS accepting wildcard with credentials93- Cache/queue fallback to in-memory (security implications?)94- Webhook secret validation bypass scenarios9596**2. Silent Failures**97- Auth middleware that silently skips on error98- Webhook signature verification failure handling99- Database connection fallback behavior100101**3. Input Validation Gaps**102- ID/slug format validation103- Numeric field bounds checking104- Pagination: max page_size enforced?105- Request body size limits?106107**4. SQL Injection Surface**108- Any raw SQL usage — ALL queries parameterized?109- Any string interpolation in SQL?110111**5. Type Confusion**112- Token types (access vs refresh) distinguishable?113- Role/tier strings validated against enum?114115### Python-Specific Patterns (from Trail of Bits)116117| Pattern | Risk |118|---------|------|119| `pickle.loads(user_data)` | Arbitrary code execution |120| `yaml.load()` without `safe_load` | Code execution |121| `subprocess.*(..., shell=True)` | Command injection |122| `eval(`, `exec(` | Code execution |123| `except:` or `except Exception: pass` | Swallowed security errors |124| `template.format(user_input)` | Format string injection |125| `def f(x=[])` mutable defaults | Shared state bugs |126127### JavaScript/TypeScript Patterns128129| Pattern | Risk |130|---------|------|131| `==` instead of `===` | Type coercion bugs |132| `obj[userInput]` | Prototype pollution |133| `eval(`, `new Function(` | Code execution |134| `as Type` assertions | Runtime type mismatch |135| `!` non-null assertion | Null pointer crash |136| Missing `await` | Race conditions |137138### Edge Case Probing139140For each security-relevant API, ask:141- **Zero/empty/null**: What happens with `0`, `""`, `null`?142- **Negative values**: What does `-1` mean?143- **Type confusion**: Can different security concepts be swapped?144- **Default values**: Is the default secure?145- **Error paths**: What happens on invalid input?146147---148149## Part 3: Supply Chain Risk Audit150151Evaluates dependencies for exploitation or takeover risk.152153### Risk Criteria154155A dependency is high-risk if:156- **Single maintainer** — individual, not org-backed157- **Unmaintained** — stale, deprecated, archived158- **Low popularity** — few stars/downloads vs peers159- **High-risk features** — FFI, deserialization, code execution160- **Past CVEs** — high/critical severity161- **No security contact** — no SECURITY.md or responsible disclosure162163### Workflow1641651. Enumerate all direct dependencies from manifest files (requirements.txt, package.json, Cargo.toml, etc.)1662. For each, check GitHub: stars, last commit, maintainer count, open issues1673. Flag high-risk deps in report with risk factors and suggested alternatives1684. Run language-appropriate audit tools (`pip audit`, `npm audit`, `cargo audit`, etc.)169170### Report Template171172```markdown173# Supply Chain Risk Report174175## Metadata176- Scan Date: YYYY-MM-DD177- Dependencies Scanned: N178179## High-Risk Dependencies180181| Dependency | Risk Factors | Notes | Suggested Alternative |182|------------|-------------|-------|-----------------------|183184## Recommendations185```186187---188189## Report Format190191Generate a markdown report at a suitable location in the project (e.g., `tasks/security-audit-report.md`):192193```markdown194# Security Audit Report195196## Executive Summary197| Severity | Count |198|----------|-------|199| CRITICAL | X |200| HIGH | Y |201| MEDIUM | Z |202| LOW | W |203204## Findings205### [SEVERITY] Title206**File**: path:line207**Pattern**: [code pattern found]208**Verification**: [trace result]209**Production Impact**: [exploitability]210**Recommendation**: [specific fix]211212## Supply Chain Summary213## Quality Checklist214- [ ] All env var fallbacks checked215- [ ] Auth flow verified216- [ ] Payment/webhook validation confirmed217- [ ] CORS configuration reviewed218- [ ] SQL injection surface audited219- [ ] Dependency audit complete220- [ ] Error handling reviewed (no silent failures)221```