Neue Skills, Referenzen & OpenWiki-Doku integriert

Umfangreiche Erweiterung der Skill-Bibliothek: Neue Skills für Humanisierung (Englisch/PT-BR), Design-Validierung, AI-SEO und Coolify-Deployment inkl. Regelwerke, Presets, Pattern-Referenzen, Testfälle und Automatisierungsskripte. Zusätzliche Skills für Revenue-Centric Design, Pier Cloud, OKF, Lebenslauf- und LinkedIn-Optimierung sowie zahlreiche Referenzdateien, Checklisten und YAML/JSON/Markdown-Templates. Einführung einer vollständigen OpenWiki-Dokumentation mit Architektur-, Domain- und Workflow-Beschreibungen, zentralem Index und automatisierten Updates. Modularer Aufbau, restriktive Lizenzen und umfassende Qualitäts- und Evaluationsmechanismen für alle neuen Inhalte.
This commit is contained in:
Tim Krampitz
2026-07-26 14:00:58 +02:00
parent 070727d5cd
commit 01046b01e4
202 changed files with 31290 additions and 0 deletions

View File

@@ -0,0 +1,150 @@
# Attack Path Tracing
## Purpose
Map the exploitation path for a confirmed or suspected vulnerability. Starts from a finding, traces backward to entry point and forward to impact. Produces a realistic severity assessment based on actual exploitability — not theoretical worst-case.
## When to Use
- A finding from `steering/full-scan.md` or `steering/discovery.md` needs severity validation
- Triaging whether a vulnerability is actually reachable
- Building proof-of-concept narratives for critical findings
- Disputing or confirming a severity rating
## Step 1: Start from the Finding
Document the vulnerability anchor:
- **What:** The vulnerable code (file, line, function)
- **Class:** Injection, auth bypass, IDOR, SSRF, path traversal, etc.
- **Primitive:** What the attacker gains if this fires (read arbitrary data, execute code, escalate privilege)
## Step 2: Trace Entry Point → Vulnerability
Work backward. How does attacker-controlled input reach the vulnerable code?
Map the chain:
```
Entry Point (HTTP route, message queue, CLI arg)
→ Input processing (parsing, deserialization)
→ Validation (what checks exist between entry and sink)
→ Intermediate transforms (encoding, type conversion, mapping)
→ Vulnerable code (the sink)
```
At each hop, document:
- What data flows through
- What transformations or filters apply
- Whether the attacker retains control over the data
If a hop breaks the chain (e.g., input is cast to integer before reaching SQL query), the path is dead. Document why and downgrade.
## Step 3: Identify Prerequisites
What must be true for the attack to work?
| Factor | Questions |
|---|---|
| **Authentication** | Does the attacker need a valid session? What role? |
| **Network position** | Must they be on the internet, internal network, localhost? |
| **Application state** | Does a specific condition need to exist (feature flag, data in DB)? |
| **Race condition** | Is timing critical? How tight is the window? |
| **User interaction** | Does a victim need to click/visit something? |
| **Chaining** | Does this require another vulnerability to be exploitable first? |
Each prerequisite reduces exploitability. Stack them honestly.
## Step 4: Map Impact Forward
From the vulnerable code, what happens when it fires?
```
Vulnerable code triggers
→ Immediate effect (SQL executes, file reads, command runs)
→ Data accessed/modified (what exactly)
→ Lateral movement possible? (pivot to other services, escalate)
→ Final impact (data breach, RCE, account takeover, DoS)
```
Be specific about impact scope:
- Single user's data vs. all users
- Read-only vs. read-write
- Contained to one service vs. cross-service pivot
- Persistent vs. one-shot
## Step 5: Check Existing Mitigations
Before finalizing severity, verify what's already blocking this path:
- **WAF/rate limiting** — does it catch this payload pattern?
- **Framework protections** — auto-escaping, parameterized queries, CSRF tokens
- **Network policy** — is the target service isolated?
- **Monitoring/alerting** — would exploitation trigger alerts?
- **Input validation upstream** — is there a check we missed?
If mitigations exist, document them and assess residual risk. A mitigated path is still a finding (defense in depth matters), but severity drops.
## Step 6: Assign Severity
Use this matrix — exploitability × impact:
| | Critical Impact | High Impact | Medium Impact | Low Impact |
|---|---|---|---|---|
| **Easy to exploit** (unauth, no prereqs) | Critical | High | Medium | Low |
| **Moderate** (auth required, simple chain) | High | High | Medium | Low |
| **Difficult** (multi-step chain, race, internal network) | High | Medium | Low | Info |
| **Very difficult** (requires prior RCE, admin, physical) | Medium | Low | Info | Info |
Impact levels:
- **Critical** — RCE, full data breach, complete auth bypass
- **High** — significant data exposure, privilege escalation, account takeover
- **Medium** — limited data leak, single-user impact, partial bypass
- **Low** — information disclosure, minor integrity issue
## Step 7: Document the Path
Output format:
```
## Attack Path: <Title>
**Finding Reference:** <link to finding in scan DB>
**Final Severity:** <Critical/High/Medium/Low/Info>
### Chain
1. Attacker sends [specific input] to [entry point]
2. Input passes through [component] where [transform happens]
3. Reaches [vulnerable code] at [file:line]
4. Triggers [primitive] resulting in [immediate effect]
5. Attacker gains [final impact]
### Prerequisites
- [List each requirement]
### Mitigations Present
- [List what partially blocks this]
### Mitigations Absent
- [List what should exist but doesn't]
### Evidence
[Code snippets, data flow diagram, or PoC outline]
```
## Step 8: Recommend Action
Based on the path analysis:
- **Critical/High with easy exploit** → Fix immediately, consider if already exploited
- **Medium** → Fix in next sprint, add detection
- **Low/Info** → Track, fix opportunistically
- **Mitigated but structurally present** → Harden, don't ignore. Mitigations fail.
## Notes
- Real severity comes from the PATH, not the pattern. SQLi behind three auth gates and only reaching a public data table is not critical.
- Conversely, a "low-severity" IDOR that leaks all customer records is critical regardless of what the textbook says about IDORs.
- If you can't trace a complete path from entry to impact, the finding might be theoretical. Say so explicitly rather than inflating.
- Attack paths compound. Two medium findings that chain into a critical outcome should be reported as critical.

View File

@@ -0,0 +1,126 @@
# Security-Focused Diff Review
## Purpose
Review a code diff (PR, commit range, branch comparison) for security regressions. Lighter and faster than a full scan — scoped strictly to what changed.
## Step 1: Obtain the Diff
Identify what you're reviewing:
- PR: the full diff between base and head
- Commit: single commit's changeset
- Branch comparison: `git diff base..head`
Read the diff in its entirety. Don't skip files — even test changes can reveal security assumptions.
## Step 2: Understand Context
Before hunting bugs, understand intent:
- What feature/fix does this change implement?
- What's the PR description / commit message saying?
- Which components are touched?
This prevents false positives from misunderstanding purpose.
## Step 3: Map Changed Attack Surface
Identify which changes affect security-relevant areas:
| Change Type | Security Relevance |
|---|---|
| New HTTP route/endpoint | New attack surface — needs auth + input validation check |
| Modified auth logic | Possible bypass, privilege escalation |
| New user input accepted | Injection, XSS, path traversal surface |
| Database query changes | SQL/NoSQL injection |
| File I/O changes | Path traversal, TOCTOU |
| Dependency added/updated | Known CVEs, supply chain risk |
| Config/env changes | Secret exposure, permissive settings |
| Error handling changes | Information disclosure |
| Crypto changes | Weak algorithms, key mishandling |
| Logging changes | Sensitive data in logs |
## Step 4: Security Regression Checklist
For each changed file, check:
### Input Handling
- [ ] New inputs validated before use?
- [ ] Existing validation still applies after refactor?
- [ ] Type coercion handled safely?
- [ ] Size/length limits enforced?
### Authentication & Authorization
- [ ] New endpoints require auth?
- [ ] Permission checks not accidentally removed?
- [ ] Auth bypass possible through new code paths?
- [ ] Token/session handling unchanged or improved?
### Data Exposure
- [ ] No secrets added to code (API keys, passwords, tokens)
- [ ] No sensitive data in new log statements
- [ ] Error messages don't leak internals
- [ ] New API responses don't over-expose data
### Dependencies
- [ ] New deps checked for known CVEs
- [ ] Version pinned (not floating ranges)
- [ ] Dep source is legitimate (not typosquat)
### Crypto & Secrets
- [ ] No hardcoded keys or salts
- [ ] Crypto usage correct (proper modes, IV handling, key derivation)
- [ ] Secrets accessed through proper secret management
## Step 5: Produce Findings
For each issue, document:
```
### [SEVERITY] Title
**File:** path/to/file.ext L42-48
**Change:** What was modified
**Issue:** What's wrong, specifically
**Attack:** How this gets exploited
**Fix:** Concrete remediation
Evidence:
\`\`\`
<the vulnerable code from the diff>
\`\`\`
```
## Step 6: Assess Severity in Context
Diff review severity considers:
- Is this code deployed yet? (PR = pre-deploy, post-merge = live)
- Does existing infrastructure mitigate? (WAF, rate limiting, network isolation)
- Is the vulnerable path reachable without auth?
- What data is at risk?
Don't inflate severity. A medium finding behind two auth gates isn't critical just because the code pattern looks bad.
## Step 7: Summary Verdict
End with a clear recommendation:
- **APPROVE** — no security issues found
- **APPROVE WITH NOTES** — informational findings, no blockers
- **REQUEST CHANGES** — security issues that must be fixed before merge
- **BLOCK** — critical vulnerability, must not merge
Include the finding count by severity and the single most important issue if requesting changes.
## Output Format
Deliver as markdown. Structure:
1. One-line verdict (approve/block/changes needed)
2. Scope summary (files reviewed, what the change does)
3. Findings (if any), ordered by severity
4. Notes (informational observations, future concerns)
## Notes
- Review test files too — they often reveal what the developer thinks the security boundary is (and where they're wrong).
- Deleted code matters. Removed validation, removed auth checks, removed error handling — these are findings.
- If the diff touches auth or crypto and you can't fully assess impact from the diff alone, say so. Recommend a broader review.

View File

@@ -0,0 +1,142 @@
# Targeted Vulnerability Discovery
## Purpose
Focused security analysis on a subset of files. Used after a threat model identifies high-risk components, after a dependency alert, or when investigating a specific concern. More surgical than a full scan — assumes you already know WHERE to look.
## When to Use
- Threat model flagged specific components as high-risk
- A new entry point or data flow was added
- Dependency alert requires assessing blast radius
- Post-incident investigation of specific modules
- Reviewer wants depth on auth, payments, or other critical subsystems
## Step 1: Receive Target Scope
Input is one of:
- A file list (explicit paths)
- A component/module name (resolve to files)
- A directory subtree
- A functional area ("all auth code", "payment processing")
If given a vague scope, resolve to concrete files before proceeding.
## Step 2: Generate Ranked Worklist
```bash
python3 scripts/rank_files.py --files <file1> <file2> ... --output worklist.json
```
The ranker scores files by:
- Proximity to entry points (routes, handlers, consumers)
- Presence of security-sensitive patterns (SQL, exec, file I/O, crypto, auth checks)
- Complexity metrics (cyclomatic complexity, line count)
- History of changes (frequently modified = higher churn risk)
Output: ordered list of files with priority scores and reason tags.
## Step 3: Analyze Each File
Work through the worklist in priority order. For each file:
### 3a. Understand Role
- What does this file do in the system?
- What data flows through it?
- Who calls it? What does it call?
- What trust level is the caller at?
### 3b. Check Input Boundaries
- Where does external data enter this code?
- Is it validated before use? (type, format, length, range)
- Are there implicit assumptions about input shape?
### 3c. Check Security Controls
- Authentication enforced? At what level?
- Authorization checked? Against what?
- Rate limiting present?
- Error handling safe? (no stack traces, no sensitive data in errors)
### 3d. Check Dangerous Operations
- SQL/NoSQL queries — parameterized or string-built?
- Command execution — input reaches shell?
- File operations — path controlled by user?
- Deserialization — untrusted data deserialized?
- Crypto usage — correct algorithms, modes, key management?
- Logging — sensitive data written to logs?
### 3e. Check Framework-Specific Issues
Adapt to the stack:
- **Node/Express** — prototype pollution, ReDoS, missing helmet headers
- **Python/Django/Flask** — template injection, pickle deserialization, debug mode
- **Go** — integer overflow, unsafe pointer use, goroutine leaks with user input
- **Java/Spring** — SpEL injection, XXE in XML parsing, actuator exposure
- **Ruby/Rails** — mass assignment, unsafe render, YAML deserialization
- **Rust** — unsafe blocks, FFI boundary issues, panic in handlers
## Step 4: Record Findings
For each issue discovered:
```bash
python3 scripts/scan_db.py add-finding \
--severity <critical|high|medium|low|info> \
--category <auth|injection|crypto|data-exposure|config|logic> \
--file <relative-path> \
--line <line-number> \
--title "<concise title>" \
--evidence "<vulnerable code snippet>" \
--impact "<what an attacker gains>" \
--recommendation "<specific fix, not generic advice>"
```
### Evidence Standard
Every finding requires:
- Exact location (file + line range)
- The vulnerable code, quoted
- A concrete attack scenario: "An attacker with [access level] sends [input] to [endpoint], which reaches [this code] and causes [effect]"
- Why existing protections (if any) don't prevent it
## Step 5: Cross-Reference
After analyzing all files in the worklist:
- Do any findings chain together? (e.g., IDOR + missing auth = account takeover)
- Do findings contradict the threat model assumptions?
- Are there patterns? (same mistake repeated = systemic issue, not one-off)
If chains exist, document them using `steering/attack-paths.md`.
## Step 6: Report Findings
Output a summary scoped to this discovery pass:
```
## Discovery: <Area Name>
Date: <date>
Scope: <file count> files in <component>
Findings: <count by severity>
### Critical
### High
### Medium
### Low
### Observations (no finding, but notable)
```
## Completion Criteria
Discovery is complete when:
- Every file in the worklist has been analyzed
- All findings are recorded in the scan DB
- Cross-references and chains are documented
- No file was skipped without explicit justification
## Notes
- Discovery is depth-first, not breadth-first. Go deep on each file rather than skimming many.
- If a file pulls in dependencies you haven't seen, follow the call chain. Vulnerabilities hide in utility code.
- "No findings" for a critical file is a valid and useful result. Record it — confirms the component is clean as of this review.
- If you discover the scope should be wider (e.g., auth module calls a helper that's not in the target list), expand and document why.

View File

@@ -0,0 +1,188 @@
# Full Repository Security Scan
## Propósito
Auditoria de segurança estruturada de um repositório inteiro. Pipeline de 6 fases com agentes paralelos, validação adversarial, e verificação independente.
---
## Pipeline de 6 Fases
```
Phase 1: Recon → architecture.md (agentes paralelos mapeiam o alvo)
Phase 2: Hunt → findings brutos (agentes paralelos por attack class)
Phase 3: Validate → findings confirmados (adversarial — tenta DISprovar)
Phase 4: Report → security-report.html + report.json
Phase 5: Schema → findings.json validado contra report-schema.json
Phase 6: Verify → verificação independente de cada claim factual
```
---
## Phase 1: Reconnaissance
Lance **múltiplos agentes em paralelo** para mapear aspectos diferentes do codebase:
**Agent 1a: Overview, stack e baseline comparável**
- O que é esta aplicação? Que tipo de software?
- Quem usa e como? (end users, devs, operadores, outros services)
- Tech stack? (languages, frameworks, databases, runtime, deployment model)
- Qual software mainstream comparável existe? Que tradeoffs de security o comparável aceita?
- Estrutura de diretórios high-level com file paths para entry points chave
**Agent 1b: Trust boundaries e access control**
- Trust boundaries — onde input não-confiável entra? (HTTP, CLI, file reads, IPC, message queues, env vars, config)
- Authentication — como callers provam identidade?
- Authorization — como permissions são enforced?
- Privilege separation — roda como root? Drop privileges? Sandboxing?
- Bypass mechanisms (dev-only modes, test helpers, setup flows, debug flags)
**Agent 1c: Input surface inventory**
- Network-facing surfaces (HTTP endpoints, gRPC, WebSocket, TCP/UDP) com method/verb e propósito
- File-based input (uploads, config parsing, import/export)
- IPC e inter-service (message queues, shared memory, Unix sockets, env vars, CLI args)
- User-generated content surfaces
- External integrations (OAuth, webhooks, third-party APIs, plugin loading, dynamic code execution)
- Todos os lugares onde input alcança dangerous sinks
### Síntese
Colete outputs dos 3 agentes e sintetize em `architecture.md`:
- 1-2 páginas com application type, tech stack, trust model, input surfaces, baseline comparável
- Key file paths de todos agentes — starting points para Phase 2
- Se codebase é maior/mais complexo que esperado (plugin system, multi-tenant, complex auth chains), lance agentes adicionais antes de prosseguir
### Multi-Run Additive
Se runs anteriores existem (cheque `.security/scans/`):
1. **Skip known findings** — não re-descubra o mesmo bug. Mencione prior findings no report mas foque hunting em ground novo.
2. **Target gaps** — se runs anteriores focaram em injection e auth, pese este run para business logic, creative attacks, e wildcard.
3. **Resolve disagreements** — se runs anteriores deram verdicts conflitantes no mesmo finding, valide definitivamente.
Se nenhum run anterior existe, note no report que coverage melhora com runs adicionais.
---
## Phase 2: Hunt
Siga `steering/hunting.md` para:
- Selecionar attack classes relevantes ao application type
- Lançar agentes paralelos (um por classe × subsistema)
- Cada agente recebe architecture.md + hunting methodology + validation rules
- Agentes podem spawnar sub-agents para deep dives
---
## Phase 3: Validate (Adversarial)
**Consolidar duplicatas primeiro** — Phase 2 deliberadamente overlapa scopes.
Para cada finding restante, lance um **agente de validação separado** que tenta **DISprovar** o finding:
```
Seu trabalho é DISPROVAR este finding. Leia o source code real em cada step.
Se não conseguir disprovar, confirme com o código exato que o torna explorável.
Retorne um de:
- "CONFIRMED: [explicação com code evidence]"
- "REJECTED: [o que o finding errou, com code evidence]"
```
**Testes de validação:**
1. **Exploitation test**: Leia o código real em cada step do trace. O data flow funciona como claimed? Pode construir o exact input que triggera?
2. **Impact test**: O que o atacante realmente ganha? Se "aprende field names" ou "causa error" = LOW máximo.
3. **Baseline test**: O comparável tem o mesmo pattern? Se sim, foi explorado? Se nunca explorado em anos de produção, entenda por quê antes de reportar.
4. **Mitigation test**: Existe outra layer que previne exploitation? Cheque middleware, DB constraints, framework defaults.
5. **Parser/runtime behavior test**: Se o exploit depende de como parser/runtime handles input específico, verifique contra spec ou implementação — não reasoning from intuition.
**Kill false positives agressivamente, mas não mate findings reais.** Report curto com 3 findings reais vale mais que report longo com 30 teóricos.
---
## Phase 4: Report
Gere o report usando `steering/reporting.md`. Siga `references/report-format.md` para o HTML.
Adições ao report padrão para full-scan com pipeline:
- Seção de coverage: quais attack classes foram exercitadas, quais subsistemas
- Seção de findings rejeitados (colapsável): mostra rigor sem cluttering findings reais
- Positive patterns: o que o codebase faz bem (calibra confiança na auditoria)
---
## Phase 5: Structured Output e Schema Check
Para cada finding que sobreviveu Phase 3, produza JSON conformando ao schema em `references/report-schema.json`.
1. Leia `references/report-schema.json` antes de escrever output. Siga exatamente — `additionalProperties: false` enforced.
2. Para cada finding, popule todo required field. Se não pode preencher `trace` com real file paths e line numbers verificados, o finding não está suficientemente verificado — volte e verifique ou rejeite.
3. Valide com: `node scripts/validate-findings.cjs <output>/findings.json`
4. Fix qualquer falha antes de prosseguir.
Escreva em: `.security/scans/<timestamp>/findings.json`
---
## Phase 6: Independent Verification
O structured output de Phase 5 força self-validation, mas o mesmo agente que escreveu o finding também escreveu o JSON. Esta phase usa agentes frescos para verificar independentemente.
Lance **um agente por finding confirmado**, todos em paralelo:
```
Você é um verificador independente. Você NÃO escreveu este finding.
Seu trabalho é ler o source code real e verificar que todo claim factual está correto.
1. Leia file e line number citados em CADA trace step. Verifique:
- File existe no path citado
- Line number corresponde ao código descrito
- Scope (function name) está correto
- Description reflete acuradamente o que o código faz
2. Verifique root_cause lendo o file citado e confirmando que o defeito descrito existe.
3. Verifique execution payloads:
- Endpoint existe na URL claimed?
- HTTP method corresponde?
- Input passaria validation como descrito?
- Auth/access checks passariam como descrito?
4. Verifique conditions — há pré-requisitos que o finding não mencionou?
5. Cheque remediation code_changes — o fix preveniria o ataque sem quebrar funcionalidade normal?
Retorne um de:
- "VERIFIED" — todos claims checked contra source
- "CORRECTED: [field]: [errado] → [correto]"
- "REJECTED: [razão]"
```
Aplique correções:
- **VERIFIED**: nenhuma mudança
- **CORRECTED**: atualize campos específicos, re-run schema validation
- **REJECTED**: mude verdict para `"rejected"` ou remova
Após correções, reconcilie deliverables: atualize HTML report e findings.json para que não discordem.
---
## Inicialização e Persistência
```bash
python3 scripts/scan_db.py init --repo <path>
```
Findings são persistidos no SQLite durante todo o processo. O `finalize.py` sela ambos os formatos (JSON + HTML) no final.
---
## Completion Criteria
O scan está completo quando:
- [ ] Phase 1 produziu architecture.md com trust model e input surfaces
- [ ] Phase 2 exercitou attack classes relevantes com agentes paralelos
- [ ] Phase 3 validou adversarially cada finding (confirmado ou rejeitado)
- [ ] Phase 4 produziu HTML report conforme template
- [ ] Phase 5 produziu findings.json válido contra schema
- [ ] Phase 6 verificou independentemente cada claim factual
- [ ] Report e findings.json concordam (sem discrepâncias)

View File

@@ -0,0 +1,184 @@
# Vulnerability Hunting
## Propósito
Caça ativa de vulnerabilidades usando agentes paralelos especializados por classe de ataque. Este é o motor principal do `full-scan` — Phase 2 na pipeline de 6 fases.
## Orquestração
Lance **múltiplos agentes em paralelo** via Task tool. Cada agente recebe:
1. O resumo de arquitetura da Phase 1 (verbatim)
2. A classe de ataque específica e escopo
3. File paths relevantes como ponto de partida
4. A hunting methodology (abaixo)
5. As validation rules (abaixo)
**Quantos agentes?** Use Phase 1 para decidir. Agentes focados produzem melhores resultados que agentes amplos. Para uma biblioteca pequena, 3-4 agentes. Para uma aplicação grande com subsistemas distintos, lance 8-12+ — divididos por classe de ataque E por subsistema.
---
## Attack Classes
Selecione classes relevantes ao tipo de aplicação. Nem toda classe se aplica a todo codebase.
### Injection
Trace input não-confiável do entry point ao dangerous sink:
- **Web apps**: SQL queries, HTML output, shell commands, template engines, file paths, HTTP redirects, deserialization
- **Libraries**: funções que processam dados do caller sem validação — buffer operations, parsers, format strings
- **CLI tools**: construção de shell commands, file path handling, interpolação de environment variables
- **Services**: query construction, message serialization, log injection, LDAP/XPATH queries
Não cheque apenas paths diretos. Procure:
- Injection indireta: dado armazenado safe, depois retrieved e usado em contexto perigoso por código diferente
- Injection via field names, keys, headers e metadata — não só values
- Injection em sistemas secundários (logs, caches, search indexes, analytics)
### Access Control
Pode um caller fazer algo que não deveria? Vá além de verificar se permission checks existem — verifique se checam a *permissão correta* para o *recurso correto* via o *mecanismo correto*:
- Existe path para o mesmo state change que checa uma permissão diferente (mais fraca)?
- Um field no request body pode override o que o permission system pretendia restringir?
- Existem endpoints que gate em authentication mas esquecem authorization?
- O mesmo recurso tem múltiplos access paths com checks inconsistentes?
- Operações bulk/batch/export/import enforcam per-item permissions?
### Resource and File Handling
- Path traversal (read/write fora do diretório pretendido) — incluindo via symlinks, encoded sequences, null bytes
- SSRF (fazer a aplicação fetch URLs controladas pelo atacante) — incluindo via redirects, DNS rebinding, URL parser differentials
- Unsafe deserialization, archive extraction (zip slip), temp file handling
- Memory safety (se aplicável): buffer overflows, use-after-free, integer overflow
- Race conditions em file operations (TOCTOU entre check e use)
### Cryptography and Secrets
- Weak randomness para valores security-critical (tokens, keys, nonces)
- Hardcoded secrets, secrets em logs, error messages, URLs, ou client-visible responses
- Broken key derivation, missing HMAC verification, nonce reuse
- Timing side-channels em secret comparison
- Misuse de crypto primitives (ECB mode, unauthenticated encryption, static IVs)
- O que acontece quando crypto operations falham? O error path faz fallback para no-crypto?
### Business Logic
Onde os bugs reais se escondem. Scanners não encontram logic errors.
Para cada major workflow:
- **State machine violations**: Pode pular steps? Ir backwards? Alcançar estado inválido? Replay de um flow completed? Partial failure — se step 2 de 3 falha, step 1 é rolled back?
- **Race conditions com business impact**: Operações concorrentes que produzem estados inválidos (double-spend, double-approve, lost updates). Foque em operações check-then-act não-atômicas.
- **Numeric/quantity manipulation**: Negative values, zero, overflow, precision loss, type coercion string↔number.
- **Access boundary violations**: Não "o permission check existe" mas "é o check certo para a business rule?" Input em uma operação bypass restrição enforced em operação diferente para mesmo efeito?
- **Implicit trust assumptions**: Data de storage, config, outros componentes assumida safe porque "validamos na entrada." E se um code path diferente escreveu?
- **Time-based logic**: Expiry checks, scheduling, rate windows, clock skew. O que acontece em boundary moments exatos? Timezone differences entre componentes?
- **Default and fallback behavior**: Qual a security posture quando config está missing? Feature flag off? Dependência unavailable? Sistema mid-migration?
### Feature Abuse and Data Leakage
Features legítimas usadas para propósitos não-pretendidos. Não procure bugs no código — procure bugs no design:
- **Export/backup como exfiltration**: Low-privilege user pode trigger export que inclui dados above their access? Export de outros users? Dados deleted/draft/private?
- **Import/restore como injection**: Import pode overwrite dados existentes? Criar records que bypass validação normal? Inject em collections sem write access?
- **Search/filter/sort como oracle**: Search queries revelam se content existe que o user não pode acessar diretamente? Filter params permitem probe de statuses/roles/fields que não deveriam ser visíveis?
- **Enumeration via side effects**: Error messages diferem entre "não existe" e "sem acesso"? Response times diferem? Sizes? Status codes?
- **Preview/draft/staging leakage**: Preview tokens scoped a um item ou unlock acesso mais amplo? Draft discoverable via search, RSS, sitemaps, API listing?
- **Notification/webhook como SSRF**: User pode set notification/webhook/callback URL que o server fetches? Validado contra internal networks?
### Chained Attacks and Trust Boundaries
Comportamentos individualmente safe que se tornam perigosos em combinação:
- **Multi-step chains**: Mapeie o que um low-privilege user CAN do, depois procure combinações. Info disclosure + IDOR + missing rate limit. Open redirect + OAuth callback = token theft.
- **Cross-component trust gaps**: Component A valida input e passa para B. B re-valida ou confia em A? E se validação de A é sutilmente diferente do que B precisa?
- **Second-order attacks**: Dados safe quando stored mas perigosos quando usados em contexto diferente. Field name safe em SQL vira key em JSON path expression. Slug safe em URL vira parte de file path.
- **Scope and capability escalation**: Tokens/API keys/OAuth scopes que grant acesso mais amplo que o nome implica. Session cookies que sobrevivem role downgrade.
- **Timing and ordering**: Usar feature antes de setup complete? Agir em resource entre soft-delete e hard-delete? Usar token entre revocation e cache expiry?
### Wildcard
Não recebe categoria. Recebe o codebase e a instrução de quebrá-lo. Ignore vulnerability classes padrão — outros agentes cobrem isso. Encontre o que ninguém pensou em procurar:
- Código mais estranho do codebase? Por que existe? O que acontece se abusado?
- Features half-finished/experimentais/bolted-on? Segurança mais fraca, menos review.
- API usada de forma que o frontend nunca faria? UI constrains users, API não.
- Endpoints/parâmetros/headers hidden ou undocumented?
- Mix de features não desenhadas para funcionar juntas?
- Git history: reverted security fixes, commented-out auth checks, secrets committed then removed?
- Com valid account: máximo dano sem detecção? Corrupting data, poisoning caches, exhausting resources.
### Obvious Things
Outros agentes caçam bugs sutis. Este checa o "óbvio" que é fácil ignorar:
- Hardcoded passwords, API keys, tokens, secrets no source?
- TODO/FIXME/HACK/XXX comments referenciando security?
- Debug mode/dev mode proper gated? Habilitável em prod via env var, query param, header?
- Test/example/seed credentials que funcionam em prod?
- Endpoints `/debug`, `/admin`, `/test`, `/status`, `/health`, `/metrics`, `/env`, `/.env`, `/config` unprotected?
- Arquivos `.env`, `credentials.json`, `*.pem`, `*.key` checked into repo?
- `.gitignore` cobre secrets, uploads, e local config?
- Dependencies pinned? CVEs conhecidos no dependency tree?
- `eval()`, `exec()`, `child_process`, `Function()`, `vm.runInContext`, `import()` com dynamic input?
- CORS headers `*` ou overly permissive com `Access-Control-Allow-Credentials`?
- Cookies missing `HttpOnly`, `Secure`, ou `SameSite`?
- Open redirects? (params named `redirect`, `return`, `next`, `url`, `goto`, `continue`)
- TLS enforced? HTTP-only endpoints?
- Error responses em prod retornando stack traces, internal paths, SQL errors?
**IMPORTANTE**: Para qualquer finding deste agente, verificar o full code path, não só surface appearance. Um flag não é um finding — trace o impacto antes de reportar.
---
## Hunting Methodology — 12 Ângulos
Inclua em todo prompt de agente Phase 2:
### Como caçar
Não apenas cheque se defesas existem. Tente quebrá-las. LEIA O CÓDIGO EM PROFUNDIDADE. Não pare na primeira função. Siga os dados por cada layer — de entry point até validation, transformation, storage, retrieval, e output. Bugs vivem nos gaps entre layers.
1. **O HAPPY PATH ESTÁ DEFENDIDO. ATAQUE O SAD PATH.** Error handlers, fallback branches, catch blocks, default cases, timeout paths, retry logic, cleanup routines. Erros são handled com o mesmo rigor que success? Failed validation deixa state half-modified?
2. **O QUE ACONTECE NAS BOUNDARIES?** Empty input. Maximum-length. Null vs undefined vs missing. Zero. Negativo. Unicode edge cases. Primeiro e último item. Um mais que o máximo. Exatamente no rate limit. Momento de token expiry.
3. **O QUE COMPONENTES ASSUMEM SOBRE OUTROS?** DB layer assume que API layer validou? Renderer assume content sanitized no write? Auth middleware assume que routes se registram corretamente? Encontre onde trust é implícito e teste se é justificado.
4. **E SE OPERAÇÕES ACONTECEM NA ORDEM ERRADA?** Call step 3 antes de step 1. Delete durante create. Callback antes do request. Confirmation endpoint sem iniciar o flow. Replay de flow completed.
5. **E SE DUAS COISAS ACONTECEM SIMULTANEAMENTE?** Dois requests ao mesmo resource. Modify durante read. Delete durante iterate. Publish enquanto outro edita. Dois users claiming mesmo unique resource.
6. **ONDE DOIS PARSERS OU VALIDATORS DISCORDAM?** Input aceito pelo schema mas rejeitado pelo DB. URL parsed diferente pelo router vs app code. Content-type diz uma coisa, body é outra. Filename extension vs MIME type vs magic bytes.
7. **O QUE SOBREVIVE UM ROUND TRIP?** Data stored e retrieved — é o mesmo? Encoding muda? Escaping double-up? Relative path resolved diferente em read vs write? Serialization perde type info?
8. **O QUE A CONFIGURAÇÃO CONTROLA?** Config missing ou default — o que acontece? Environment variable pode override security control? Feature flag desabilita validation? Security posture durante setup/first-run antes de config completo?
9. **SIGA O DINHEIRO (OU O PRIVILÉGIO).** Para toda operação que muda state: quem autorizou? Trace back ao permission check. Checa a permissão certa? Contra o recurso certo? Existe path paralelo para o mesmo state change que checa diferente ou não checa?
10. **PROCURE CONTEXTO VAZADO.** Error messages que revelam internal paths. Stack traces em prod. Timing differences que revelam se record existe. Response size differences. HTTP headers com versões. Debug endpoints que sobreviveram para prod.
11. **QUE PARÂMETROS OVERRIDAM DEFAULTS SECURITY-RELEVANT?** Onde default é safe mas user-supplied parameter pode mudar. Procure todo input que override security-relevant default e cheque se o override é gated por permissions apropriados.
12. **ONDE CLAIMS NÃO-VERIFICADOS DIRIGEM DECISÕES DE TRUST?** Self-declared identity, capability, ou metadata influenciando access/trust decision sem verificação independente.
---
## Validation Rules — Aplicar antes de reportar QUALQUER finding
1. Você DEVE construir um ataque concreto (exact inputs, requests, ou action sequence)
2. O ataque DEVE alcançar impacto meaningful (não apenas "aprender field names" ou "causar um error")
3. Cheque se outra layer já previne exploitation — se sim, é hardening note, não finding
4. Se o baseline comparável tem o mesmo pattern, note se foi explorado lá
5. Se seu exploit depende de parser/runtime behavior, verifique contra a spec ou implementação — não assuma
6. Retorne APENAS findings confirmados com ataques concretos, ou "Nenhuma vulnerabilidade explorável encontrada" se isso é honesto
---
## Spawn Sub-Agents
Se precisar entender um subsistema em profundidade para avaliar um potential finding — use o Task tool para lançar um research agent. Não tente segurar tudo no seu próprio contexto. Vá fundo onde importa.
**SEU ESCOPO É SEU FOCO PRIMÁRIO, NÃO UMA FRONTEIRA.** Se ao investigar sua área atribuída notar algo errado em categoria diferente — um permission issue ao tracing injection, uma race condition ao reviewing auth — reporte. Não ignore um bug porque "não é sua área." Atacantes não respeitam fronteiras de categoria.

View File

@@ -0,0 +1,224 @@
# Penetration Testing
Active security assessment against a live target. Unlike code-only analysis, this involves running tools against actual systems — reconnaissance, scanning, exploitation attempts, and evidence collection.
**When to use:** The user has a target (domain, IP, web app URL) and wants an offensive assessment, not just source code review. This is the "attacker's perspective" workflow.
## Prerequisites
- For **localhost/dev targets**: no authorization needed — it's the user's own machine.
- For **remote/production targets**: explicit written authorization from the target owner.
- Clear rules of engagement for remote targets (scope, testing window).
- Do NOT probe remote systems without confirmation.
## Default Flow (Path + Dev)
When the user provides a codebase path without a remote URL:
1. Run SAST via `steering/full-scan.md` on the source code
2. Detect how to start the dev server:
- Look for `package.json``npm run dev` / `npm start`
- Look for `docker-compose.yml``docker compose up -d`
- Look for `Makefile``make run`
- Look for `manage.py``python manage.py runserver`
- Ask the user if unclear
3. Start the dev server, wait for it to be ready
4. Run DAST against `localhost:<port>` (phases 2-4 below)
5. Correlate: match DAST findings to source code locations from SAST
6. Stop the dev server
## Extended Flow (Path + Production URL)
When the user also provides a production URL:
1. Complete the default flow above (SAST + DAST localhost)
2. Show gate: "This will send active probes to [URL]. Authorized? [y/n]"
3. On confirmation: run DAST against production URL
4. Compare: findings present in dev but absent in prod (mitigated by infra?) and vice versa
5. Final report correlates all three layers
## Phase 1: Reconnaissance
Gather information without touching the target directly, then move to active probing.
### Passive (no direct contact with target)
```bash
python3 scripts/pentest.py recon-passive --target <domain>
```
The script runs:
- WHOIS lookup (registrar, nameservers, creation date)
- DNS enumeration (A, AAAA, MX, NS, TXT, CNAME records)
- Subdomain discovery via certificate transparency logs
- Technology fingerprinting from public sources
### Active (direct contact — requires authorization)
```bash
python3 scripts/pentest.py recon-active --target <ip_or_domain> --ports <range>
```
The script wraps:
- Host discovery (ping sweep or TCP probe)
- Port scanning (top 1000 or full 65535 based on `--ports`)
- Service version detection on open ports
- OS fingerprinting
Record all discovered hosts, ports, and services. This becomes the attack surface map.
## Phase 2: Enumeration
Dig deeper into discovered services.
### Web targets
```bash
python3 scripts/pentest.py enumerate-web --url <base_url>
```
Covers:
- Directory and file brute-forcing (common paths, backup files, admin panels)
- Subdomain enumeration (DNS brute, certificate transparency)
- Technology stack detection (frameworks, CMS, WAF identification)
- robots.txt, sitemap.xml, .well-known paths
- HTTP method testing on discovered endpoints
- Authentication mechanism identification
### Infrastructure targets
- Banner grabbing on non-HTTP services
- SMB share enumeration
- SNMP community string testing
- Default credential checks on known services
## Phase 3: Vulnerability Identification
Map discovered services to known vulnerabilities and potential attack vectors.
### Automated scanning
```bash
python3 scripts/pentest.py vuln-scan --target <url_or_ip> --type <web|infra>
```
For web targets, check OWASP Top 10:
1. **Injection** — SQLi, command injection, LDAP injection, template injection
2. **Broken Auth** — default creds, weak passwords, session fixation
3. **Sensitive Data Exposure** — cleartext transmission, backup files, source disclosure
4. **XXE** — XML entity injection in upload/API endpoints
5. **Broken Access Control** — IDOR, privilege escalation, path traversal
6. **Misconfig** — default pages, directory listing, verbose errors, CORS
7. **XSS** — reflected, stored, DOM-based
8. **Insecure Deserialization** — object injection in serialized data
9. **Known CVEs** — version-matched CVE checks against detected software
10. **SSRF** — server-side request forgery in URL parameters
### Manual testing
After automated scans, test for logic flaws that scanners miss:
- Business logic bypasses (price manipulation, workflow skipping)
- Race conditions in state-changing operations
- Chained vulnerabilities (low-severity issues combining into high-impact)
## Phase 4: Exploitation (Proof of Concept)
For each identified vulnerability, attempt controlled exploitation to confirm impact.
**Rules:**
- Minimal impact — demonstrate the bug, don't destroy data
- Document every step — screenshot, request/response, timestamp
- Stop if unexpected damage occurs
- Stay within authorized scope
Record results:
```bash
python3 scripts/scan_db.py add-finding \
--scan-id <id> \
--title "SQL Injection in /api/search" \
--severity critical \
--category injection \
--file "api/routes/search.js" \
--line 42 \
--description "Unsanitized user input in search parameter passed directly to SQL query" \
--evidence "Request: GET /api/search?q=1' OR 1=1-- Response: 200 OK with all database records"
```
## Phase 5: Post-Exploitation (if in scope)
When rules of engagement allow:
- Lateral movement mapping (what else can you reach from compromised position)
- Privilege escalation attempts
- Data access assessment (what sensitive data is reachable)
- Persistence mechanism identification (not deployment — just identifying)
## Phase 6: Reporting
```bash
python3 scripts/finalize.py --scan-dir .security
```
The pentest report adds to the standard report format:
| Section | Content |
|---------|---------|
| Executive Summary | Business impact in non-technical language |
| Scope | Authorized targets, testing window, methodology |
| Attack Narrative | Chronological story of the assessment |
| Findings | Sorted by severity with full reproduction steps |
| Evidence | Screenshots, request/response dumps, tool output |
| Remediation | Prioritized fix recommendations with effort estimates |
| Positive Observations | What's working well (defenders need wins too) |
## Severity Rating
Follow `references/severity-policy.md`, but with CVSS alignment for pentest context:
| Severity | CVSS Range | Pentest Context |
|----------|-----------|-----------------|
| Critical | 9.010.0 | RCE, full auth bypass, mass data exfil, supply chain |
| High | 7.08.9 | SQLi with data access, stored XSS + session theft, priv esc |
| Medium | 4.06.9 | Reflected XSS, info disclosure, missing security controls |
| Low | 0.13.9 | Missing headers, version disclosure, theoretical issues |
| Info | — | Best practices, hardening suggestions, architecture notes |
## Tools Reference
The `scripts/pentest.py` script wraps system tools when available and falls back to Python alternatives.
### Tool Matrix
| Function | System Tool | Python Alternative (pip) | Stdlib Fallback |
|----------|------------|--------------------------|-----------------|
| Port scanning | `nmap` | `python-nmap` or `python3-nmap` | `socket` connect scan |
| DNS enumeration | `dig`, `host` | `dnspython` | `socket.getaddrinfo` |
| WHOIS lookup | `whois` | `python-whois` | crt.sh HTTPS query |
| Subdomain enum | `subfinder`, `amass` | `bbot` | crt.sh CT log query |
| Dir brute-force | `gobuster`, `feroxbuster` | `dirsearch` | `urllib` common-path check |
| Tech detection | `whatweb`, `wappalyzer` | `builtwith`, `webtech` | HTTP header analysis |
| Web vuln scan | `nikto` | `wapiti3` | Manual checks |
| Template scan | `nuclei` | `wapiti3` (module-based) | Header/config checks |
| SQL injection | `sqlmap` | `sqlmap` (is Python) | Parameter probing |
| XSS detection | — | `wapiti3`, `xsser` | Reflected input check |
| OSINT recon | `theHarvester` | `theHarvester` (is Python) | Search API queries |
| HTTP proxy | `burpsuite`, `mitmproxy` | `mitmproxy` (is Python) | — |
### Installation
```bash
# Minimal (covers most use cases)
pip install dnspython python-whois requests
# Full pentest stack
pip install dnspython python-whois python3-nmap wapiti3 dirsearch bbot webtech mitmproxy
```
### Priority Order
The script tries tools in this order:
1. **System binary** (fastest, most features) — e.g., `nmap` on PATH
2. **Python pip package** (portable, no root needed) — e.g., `python3-nmap`
3. **Stdlib fallback** (always works, limited) — e.g., `socket` scan
If nothing external is available, the stdlib fallback still produces useful results — just slower and less comprehensive.

View File

@@ -0,0 +1,110 @@
# Steering: Remediation
Fix a specific confirmed vulnerability. The goal is a minimal, correct patch that closes the security gap without introducing regressions.
## Step 1: Understand the Root Cause
Read the finding details from the scan database:
```bash
python3 scripts/scan_db.py show --finding-id <id>
```
Then answer:
- What is the **root cause**? (not the symptom — the actual design flaw or missing control)
- Where does untrusted data enter the system? (the source)
- What dangerous operation consumes it? (the sink)
- What check/transform is missing between source and sink?
Example: The symptom is "XSS in search results page." The root cause is "user input from query parameter is interpolated into HTML without encoding." The fix isn't "sanitize this one field" — it's "ensure all template output is auto-escaped, and this specific path uses the escaping mechanism."
## Step 2: Identify the Minimal Correct Fix
Pick the fix that:
1. Addresses the root cause, not just the specific instance
2. Uses the framework's built-in security mechanisms when available
3. Doesn't change unrelated behavior
4. Is consistent with how the rest of the codebase handles the same pattern
### Common Fix Patterns
**Injection (SQLi, NoSQLi, command injection):**
- Use parameterized queries / prepared statements. Never string concatenation.
- For OS commands: use array-based exec (no shell interpretation), or better — avoid shelling out entirely.
**Cross-Site Scripting (XSS):**
- Enable auto-escaping in the template engine (most modern frameworks do this by default).
- For cases requiring raw HTML: use a strict allowlist sanitizer (DOMPurify, bleach).
- Set `Content-Security-Policy` headers as defense-in-depth.
**Authentication/Authorization:**
- Add the missing auth check at the correct layer (middleware/decorator, not deep in business logic).
- Use the existing auth framework — don't invent a new check.
- Verify the check covers all HTTP methods, not just GET.
**Path Traversal:**
- Resolve the path, then verify it's within the allowed directory (use `realpath` comparison).
- Never rely on blacklisting `../` — normalize first, check after.
**SSRF:**
- Validate the target URL against an allowlist of permitted hosts/schemes.
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 169.254.0.0/16, fd00::/8).
- Disable redirects or re-validate after each redirect.
**Insecure Deserialization:**
- Don't deserialize untrusted data with unsafe deserializers (pickle, Java ObjectInputStream, PHP unserialize).
- Use data-only formats (JSON, protobuf) with schema validation.
**Secrets/Credentials:**
- Remove the hardcoded secret from code.
- Load from environment variable or secrets manager.
- Rotate the exposed credential immediately.
## Step 3: Implement the Fix
Write the patch. Keep the diff small and focused:
- Touch only files relevant to the vulnerability.
- If you discover a systemic issue (same pattern in 20 places), fix them all — but in a way that's reviewable (e.g., introduce a helper function, then replace all call sites).
- Add a code comment referencing the finding ID if the fix is non-obvious: `// Fix for SEC-042: parameterize user input`
## Step 4: Verify No Regressions
Run the project's existing test suite:
```bash
# Whatever the project uses — detect from package.json, Makefile, etc.
npm test / pytest / go test ./... / cargo test
```
If tests fail, the fix is wrong or incomplete. Adjust until green.
If no tests cover the affected code path, write a minimal test that exercises the fixed path with safe input and confirms it still works.
## Step 5: Verify the Fix Closes the Vulnerability
Re-run the scanner or analysis that found the issue:
```bash
python3 scripts/run_scan.py --target <file_or_dir> --rules <relevant_rule_id>
```
The finding should no longer appear. If it does, the fix is incomplete.
For manually-validated findings: re-trace the data flow. Confirm the dangerous operation is no longer reachable with attacker-controlled input, or that proper sanitization/validation now gates it.
## Step 6: Update the Scan Database
Mark the finding as fixed:
```bash
python3 scripts/scan_db.py update-status \
--finding-id <id> \
--status fixed
```
## Step 7: Document
If the fix introduced a new security pattern (new helper function, new middleware, new validation rule), document it briefly so future code follows the same pattern. Update the project's security guidelines or CONTRIBUTING.md if appropriate.
## Principles
- Fix the class of bug, not just the instance — but only if the codebase supports it without massive refactoring.
- The best fix uses mechanisms already present in the framework. Don't add a custom sanitizer when the template engine has auto-escape.
- A fix that breaks functionality is not a fix. Tests must pass.
- If the correct fix requires significant architectural change, flag it and propose a phased approach.

View File

@@ -0,0 +1,142 @@
# Steering: Generate Scan Report
Produce the final deliverable: a structured report of all findings from a scan, in both machine-readable (JSON) and human-readable (Markdown) formats.
## Step 1: Load All Findings
Pull the complete findings set from the scan database:
```bash
python3 scripts/scan_db.py list --scan-dir <dir> --format json > /tmp/findings_raw.json
```
Verify the data includes:
- All triaged findings (confirmed + false-positive + needs-more-info)
- Validated severity for each
- Status (open, fixed, tracked, false-positive)
- Location, category, evidence, and triage rationale
If any findings lack triage data, go back to the `triage` workflow first. Don't report un-triaged findings.
## Step 2: Compute Statistics
Calculate:
**By severity:**
- Critical: count
- High: count
- Medium: count
- Low: count
- Informational: count
- False positives excluded from totals
**By category:**
- Group by CWE or vulnerability class (injection, XSS, auth, crypto, etc.)
- Show count per category
**By location:**
- Which files/directories have the most findings
- Hotspots (files with 3+ findings)
**By status:**
- Open (unresolved)
- Fixed (remediated and verified)
- Tracked (exported to issue tracker)
- False positive (dismissed with rationale)
## Step 3: Generate JSON Report
Structure:
```json
{
"scan_metadata": {
"scan_id": "<uuid>",
"timestamp": "<ISO 8601>",
"target": "<repository or directory scanned>",
"tools_used": ["semgrep", "trufflehog", ...],
"scan_duration_seconds": <int>
},
"summary": {
"total_findings": <int>,
"by_severity": {"critical": 0, "high": 0, "medium": 0, "low": 0, "informational": 0},
"by_status": {"open": 0, "fixed": 0, "tracked": 0, "false_positive": 0},
"by_category": {"CWE-79": 3, "CWE-89": 1, ...}
},
"findings": [
{
"id": "<finding-id>",
"title": "<short description>",
"severity": "<validated severity>",
"category": "<CWE-XXX>",
"location": {"file": "<path>", "line": <int>, "function": "<name>"},
"status": "<open|fixed|tracked|false_positive>",
"evidence": "<code snippet or trace>",
"rationale": "<triage reasoning>",
"tracking_url": "<url if tracked, null otherwise>"
}
]
}
```
Write to: `<scan-dir>/report.json`
## Step 4: Generate HTML Report
The human-readable report is a **self-contained HTML file** (`security-report.html`). Follow the template in `references/report-format.md` **exactly** — it is a prescriptive spec, not a suggestion.
Key features:
- Dark theme, color-coded severity badges
- Collapsible evidence and remediation sections
- Interactive filter buttons (filter by severity)
- CVE analysis table with exploitability cross-reference
- Pentest results with all tests numbered (P1, P2...)
- Negative results table (what was tested and passed)
- **Footer with skill attribution** (mandatory — see template)
- Zero external dependencies — opens offline
Build the HTML by replacing `{{placeholders}}` in the template with actual data. Repeat blocks for each finding/CVE/test.
**After generating the HTML, run the Report Compliance Checklist from SKILL.md against your output.** If any element is missing, fix it before proceeding.
Write to: `<scan-dir>/security-report.html` (and also repo root for easy access)
## Step 5: Structured Output (Full-Scan Only)
Se este report vem de um full-scan com pipeline de 6 fases, produza também o `findings.json` estruturado:
1. Leia `references/report-schema.json` — siga exatamente
2. Para cada finding confirmado, popule todos required fields incluindo trace, conditions, execution, confidence
3. Valide: `node scripts/validate-findings.cjs <scan-dir>/findings.json`
4. Fix erros antes de prosseguir
Para workflows não-pipeline (discovery, diff-review, pentest), o format simples do SQLite é suficiente.
## Step 6: Finalize
Run the finalization script to seal both reports and compute integrity hashes:
```bash
python3 scripts/finalize.py --scan-dir <dir>
```
This script:
- Validates both report files exist and are well-formed (JSON valid, HTML parseable)
- Computes SHA-256 hashes of report.json and security-report.html
- Writes a `manifest.json` with file hashes and completion timestamp
- Marks the scan as complete in the database
## Step 6: Present to User
Show:
- The executive summary
- The findings table
- Location of the full report files
- Any findings that still need action (open critical/high)
## Principles
- Reports are for two audiences: machines (JSON) and humans (HTML). Both must be complete.
- The HTML report is self-contained, interactive, and opens offline in any browser.
- False positives go in a collapsible appendix — they prove rigor but shouldn't clutter the main findings.
- Severity in the report is the **validated** severity (cross-referenced against project context), not the scanner's original rating.
- Every recommendation must be specific enough that a developer can act on it without further research.
- The executive summary is for people who won't read the rest. Make it count.
- All pentest tests performed must appear in the report — positive and negative results.

View File

@@ -0,0 +1,143 @@
# Threat Model
## Purpose
Build or update a structured threat model for the repository. Output is `.security/threat-model.md` — a living document that informs scan priorities and attack path analysis.
## Step 1: Identify the System
Answer these questions by reading the codebase:
- **What does it do?** — Core functionality in one paragraph
- **Who uses it?** — User roles (anonymous, authenticated, admin, service-to-service)
- **Where does it run?** — Cloud provider, container orchestration, serverless, bare metal, edge
- **What data does it handle?** — PII, financial, credentials, health data, public content
- **What's the deployment model?** — Single tenant, multi-tenant, self-hosted, managed
Document answers at the top of the threat model.
## Step 2: Map Trust Boundaries
Draw the lines between zones of different trust:
- **External → Application** — internet-facing load balancer, API gateway
- **Application → Database** — app server to data store
- **Application → External Services** — third-party APIs, payment processors
- **User tiers** — anonymous vs authenticated vs admin
- **Service-to-service** — internal microservice communication
- **CI/CD → Production** — deployment pipeline access
For each boundary, note:
- What crosses it (data, commands, credentials)
- How it's protected (TLS, auth tokens, network policy, nothing)
## Step 3: Identify Entry Points
Every place external input enters the system:
| Entry Point | Protocol | Auth Required | Input Type |
|---|---|---|---|
| `POST /api/login` | HTTPS | No | JSON body |
| `GET /api/users/:id` | HTTPS | Yes (JWT) | URL param |
| WebSocket `/ws` | WSS | Yes (session) | Messages |
| Message queue consumer | AMQP | Service account | Serialized events |
| CLI commands | Local | OS user | Arguments + stdin |
| File upload endpoint | HTTPS | Yes | Multipart binary |
Be exhaustive. Every entry point is a potential attack vector.
## Step 4: Map Data Flows
For each significant data type, trace its lifecycle:
1. **Ingestion** — where it enters the system
2. **Processing** — what transforms or validates it
3. **Storage** — where it persists (DB, cache, file, log)
4. **Transmission** — where it's sent (other services, external APIs, user responses)
5. **Deletion** — how/when it's purged
Flag any data flow that crosses a trust boundary without adequate protection.
## Step 5: Enumerate Threats (STRIDE)
For each entry point and data flow, apply STRIDE:
| Category | Question |
|---|---|
| **Spoofing** | Can an attacker impersonate a legitimate user or service? |
| **Tampering** | Can data be modified in transit or at rest without detection? |
| **Repudiation** | Can actions be performed without audit trail? |
| **Information Disclosure** | Can sensitive data leak through errors, logs, side channels? |
| **Denial of Service** | Can the system be exhausted or crashed? |
| **Elevation of Privilege** | Can a low-privilege user gain higher access? |
For each identified threat, document:
```
### T-<number>: <Title>
**Category:** Spoofing / Tampering / Repudiation / Info Disclosure / DoS / EoP
**Entry Point:** <where the attack starts>
**Affected Component:** <what's at risk>
**Likelihood:** High / Medium / Low
**Impact:** Critical / High / Medium / Low
**Current Mitigations:** <what's already in place, or "None">
**Residual Risk:** <what remains after mitigations>
```
## Step 6: Assess Likelihood and Impact
Likelihood considers:
- Is the entry point internet-facing or internal-only?
- Does exploitation require authentication?
- Is the vulnerability pattern common and well-tooled?
- Are there known exploits in the wild for this class?
Impact considers:
- What data is compromised? (PII = high, public content = low)
- Can the attacker pivot to other systems?
- Is there financial, legal, or reputational damage?
- How many users are affected?
## Step 7: Document Assumptions
Every threat model rests on assumptions. Make them explicit:
- "Internal network is trusted" — is it?
- "Admin users are not adversaries" — always true?
- "TLS terminates at the load balancer" — verified?
- "Database is not internet-accessible" — checked?
- "Third-party dependencies are not compromised" — hope so
These assumptions are the first thing to revisit when the system changes.
## Step 8: Write Output
Save to `.security/threat-model.md` with this structure:
```
# Threat Model — <Project Name>
Last updated: <date>
## System Description
## Trust Boundaries
## Entry Points
## Data Flows
## Threats
## Assumptions
## Review History
```
## When to Update
- New entry point added (route, consumer, endpoint)
- Architecture change (new service, new data store, new external dependency)
- Deployment model change (moved to different infra, added multi-tenancy)
- After a security incident (assumptions proved wrong)
- Every 6 months as a hygiene check
## Notes
- A threat model isn't a findings list. It's a map of WHERE to look and WHAT to worry about.
- Don't over-enumerate. Focus on threats with realistic attack paths, not theoretical exercises.
- If the system is simple (static site, no user data), keep the model proportionally simple. One page is fine.

View File

@@ -0,0 +1,152 @@
# Steering: Export Findings to Tracking Systems
Push confirmed findings to external issue trackers (GitHub Issues, GitHub Security Advisories, Jira, Linear) so they're visible to the engineering team and can be assigned/scheduled.
## Step 1: Select Findings to Export
Query the scan database for findings ready to track:
```bash
python3 scripts/scan_db.py list --status confirmed --not-tracked
```
Decide what to export. Typical filters:
- All confirmed findings above a severity threshold (e.g., high+critical)
- All findings from a specific scan
- A hand-picked set by finding ID
Don't export false positives or informational findings to issue trackers — they create noise.
## Step 2: Determine Target System
Identify the project's tracking system:
- **GitHub Issues** — default for open source and most SaaS teams
- **GitHub Security Advisories** — for vulnerabilities that need CVEs or coordinated disclosure
- **Jira** — enterprise, use the project's existing security issue type
- **Linear** — startup teams, use appropriate team and label
Check the project for existing conventions: issue templates, labels (e.g., `security`, `vulnerability`), custom fields, linked projects.
## Step 3: Format the Issue
### Title Format
```
[<SEVERITY>] <Vulnerability Type> in <Location>
```
Examples:
- `[HIGH] SQL Injection in /api/users search endpoint`
- `[CRITICAL] Authentication bypass via JWT algorithm confusion`
- `[MEDIUM] Stored XSS in comment rendering`
Keep titles scannable. Someone triaging a backlog should understand the issue from the title alone.
### Body Structure
```markdown
## Summary
One paragraph: what's wrong, where, and why it matters.
## Finding Details
- **ID:** <finding-id from scan database>
- **Category:** <CWE-XXX / OWASP category>
- **Severity:** <Critical/High/Medium/Low>
- **Location:** `<file:line>` or `<endpoint + parameter>`
- **Detected by:** <tool name or manual review>
## Evidence
<Code snippet showing the vulnerable pattern, or request/response demonstrating the issue>
## Impact
What can an attacker do if this is exploited? Be specific:
- What data is accessible?
- What actions can be performed?
- What's the blast radius?
## Recommended Fix
Brief guidance on the correct remediation approach. Not a full patch — just enough for the developer to understand the direction.
## References
- CWE link
- OWASP page
- Relevant framework documentation for the secure pattern
```
### For GitHub Security Advisories
Additional fields required:
- Affected versions / commits
- CVSS score (calculate from the validated severity + exploitability)
- Patched version (if fix exists)
- Credit (if from bug bounty or external reporter)
## Step 4: Show User for Approval
Before creating anything externally, present the formatted payload:
```
I'm about to create the following issue in <system>:
Title: [HIGH] SQL Injection in /api/users search endpoint
Labels: security, priority-high
Assignee: (none — or suggest based on git blame)
Body:
<full body text>
Approve? (yes/no/edit)
```
Never auto-create external issues without explicit user confirmation. These are visible to teams and may trigger notifications.
## Step 5: Create the Issue
Use the appropriate CLI tool:
**GitHub Issues:**
```bash
gh issue create --title "<title>" --body "<body>" --label "security,<severity>"
```
**GitHub Security Advisory:**
```bash
gh api repos/{owner}/{repo}/security-advisories --method POST --input payload.json
```
**Jira:**
```bash
# Use project-specific Jira CLI or API
curl -X POST "https://<instance>.atlassian.net/rest/api/3/issue" \
-H "Authorization: Basic <token>" \
-H "Content-Type: application/json" \
-d @payload.json
```
**Linear:**
```bash
# Use Linear CLI or GraphQL API
linear issue create --title "<title>" --description "<body>" --team "<team>" --label "Security"
```
Capture the returned URL/ID of the created issue.
## Step 6: Update Scan Database
Link the finding to the external tracker:
```bash
python3 scripts/scan_db.py update-status \
--finding-id <id> \
--status tracked \
--tracking-url <url>
```
## Step 7: Batch Operations
When exporting multiple findings:
- Group related findings into a single issue if they share the same root cause (e.g., "Missing CSRF protection on 8 endpoints" = 1 issue with a checklist)
- Keep unrelated findings as separate issues — don't create mega-issues
- Apply consistent labels and severity tags across the batch
## Principles
- Issues should be actionable. A developer reading it should know what to fix without needing to re-do the analysis.
- Don't over-classify. If in doubt about severity, round down — you can escalate later.
- Include enough evidence that the issue can be verified independently, but don't paste entire exploit chains in public repos.
- For security advisories: coordinate with maintainers on disclosure timeline before publishing.

View File

@@ -0,0 +1,101 @@
# Steering: Triage Findings
Intake a batch of security findings from any source (SARIF, scanner JSON, bug bounty reports, prior scan DB entries) and produce validated, deduplicated, severity-rated findings ready for action.
## Step 1: Ingest and Normalize
Load all input findings into a common internal format. Each normalized finding must have:
- `id`: unique identifier (generate one if source doesn't provide)
- `title`: short description of the issue
- `category`: CWE number or OWASP category (e.g., CWE-79, A03:2021-Injection)
- `location`: file path + line number (or URL + parameter for dynamic findings)
- `source`: which tool/report produced this (semgrep, snyk, burp, manual, etc.)
- `original_severity`: what the source assigned
- `raw_snippet`: relevant code or request/response excerpt
- `description`: what the finding claims is wrong
Run:
```bash
python3 scripts/scan_db.py import --format <sarif|json|csv|manual> --input <path>
```
This writes normalized findings into the scan database. Verify import count matches expectation.
## Step 2: Deduplicate
Same vulnerability reported by multiple tools = one finding. Dedup criteria:
- Same file + same line range (±5 lines) + same CWE = duplicate
- Same endpoint + same parameter + same vulnerability class = duplicate
- Different manifestations of the same root cause = group under one finding, note variants
Run:
```bash
python3 scripts/scan_db.py dedup --scan-dir <dir>
```
Review the dedup report. If the tool merged things that are actually distinct, split them manually.
## Step 3: Contextual Assessment
For each unique finding, answer these questions **by reading the actual code**:
1. **Is it real?** Does the vulnerable pattern actually exist at that location? Scanners hallucinate. Read the file.
2. **Is it reachable?** Can user-controlled input actually reach the vulnerable code path? Trace backwards from the sink to any entry point.
3. **Are there mitigations?** WAF rules, input validation earlier in the chain, framework-level protections, CSP headers — anything that reduces or eliminates exploitability.
4. **What's the blast radius?** If exploited: data loss? RCE? privilege escalation? Information disclosure only? Account takeover?
5. **What's the attack complexity?** Does exploitation require authentication? Specific race conditions? Social engineering?
## Step 4: Assign Validated Severity
Do NOT blindly accept the scanner's severity. Recalculate using:
| Severity | Criteria |
|----------|----------|
| **Critical** | RCE, auth bypass, mass data exfil, no mitigations, reachable from unauthenticated context |
| **High** | SQLi/XSS with clear exploit path, privilege escalation, SSRF to internal services |
| **Medium** | Exploitable but requires auth, limited blast radius, or partial mitigations exist |
| **Low** | Theoretical risk, defense-in-depth issue, requires unlikely preconditions |
| **Informational** | Best practice violation, no direct exploitability, hardening recommendation |
If a scanner says "Critical" but the finding is behind authentication + rate limiting + the data exposed is non-sensitive → it's Medium at best.
## Step 5: Record Triage Decisions
For each finding, record:
```
finding_id: <id>
validated_severity: <critical|high|medium|low|informational>
verdict: <confirmed|false-positive|needs-validation>
rationale: <2-3 sentences explaining WHY this severity, what you checked>
```
Run:
```bash
python3 scripts/scan_db.py triage \
--finding-id <id> \
--severity <level> \
--verdict <confirmed|false-positive|needs-validation> \
--rationale "explanation here"
```
## Step 6: Produce Triage Summary
After all findings are triaged, generate the summary:
```bash
python3 scripts/scan_db.py triage-summary --scan-dir <dir>
```
Output includes:
- Total findings ingested vs. unique vs. false positives
- Breakdown by validated severity
- List of findings needing deeper validation (verdict = needs-validation)
- Recommended priority order for remediation
## Key Principles
- Scanner severity is a suggestion, not a verdict. Your job is to validate.
- A finding you can't trace to reachable code is `needs-validation`, not `confirmed`.
- False positives are fine — document why and move on. Don't waste time on them.
- When in doubt about exploitability, escalate to the `validation` workflow.
- Group related findings (e.g., 15 instances of the same missing input validation) — fix the pattern, not each instance individually.

View File

@@ -0,0 +1,137 @@
# Steering: Validate a Finding
Determine se um finding reportado é real e explorável. Produza um verdict: `confirmed`, `rejected`, ou `needs-more-info`.
## Princípio: Validação Adversarial
O agente que valida NUNCA deve ser o agente que encontrou o finding. Hunting agents são biased para encontrar coisas; validation agents são biased para matar false positives. Este step adversarial é crítico.
---
## Step 1: Load Finding Details
```bash
python3 scripts/scan_db.py show --finding-id <id>
```
Extraia:
- Tipo de vulnerabilidade claimed (CWE)
- Location (file, line, function, ou endpoint)
- Source do report (qual scanner, ou manual)
- Evidência ou PoC existente
- Trace claimed (se disponível)
## Step 2: Read the Code at the Finding Location
Abra o file. Leia a function. Entenda o que faz. Não confie no snippet do scanner — scanners truncam contexto e perdem surrounding logic.
Perguntas:
- O pattern que o scanner flagged realmente existe aqui?
- É dead code? (unreachable, commented out, behind permanent feature flag)
- Foi refatorado desde o scan? (cheque git log)
- Se o código não bate com o report → provável **false positive** de resultados stale.
## Step 3: Testes de Validação (5 Gates)
Aplique **todos** os testes abaixo. O finding deve sobreviver cada um:
### 3a. Exploitation Test
Leia o código real em cada step do trace. O data flow funciona como claimed?
- Pode construir o exact input (HTTP request, CLI invocation, API call, crafted file) que triggera isto?
- O input realmente alcança o sink sem ser blocked/transformed/validated no caminho?
### 3b. Impact Test
O que o atacante **realmente ganha**?
- Se a resposta é "aprende field names" ou "causa um error" → LOW máximo
- Se não pode descrever dano concreto em 2 frases → severity provavelmente está inflada
### 3c. Baseline Test
O comparável identificado em Phase 1 tem o mesmo pattern?
- Se sim e já foi explorado → finding MAIS FORTE, não mais fraco
- Se sim e nunca explorado em anos de produção → entenda por quê antes de reportar
- Se não tem comparável ou comparável não tem o pattern → proceda normalmente
### 3d. Mitigation Test
Existe outra layer que previne exploitation?
- WAF rules
- Middleware de input validation upstream
- Framework defaults (auto-escape, parameterized queries, CSRF tokens)
- Database constraints
- Network isolation
- Rate limiting
Mitigações não tornam false positive — reduzem severity. Note mas ainda confirme o flaw subjacente.
### 3e. Parser/Runtime Behavior Test
Se o exploit depende de como parser/runtime handles input específico:
- Verifique contra a spec ou implementação REAL
- NÃO assuma behavior de intuição
- Cite a spec ou teste dinamicamente
- Os false positives mais convincentes vêm de reasoning "o parser vai interpretar isso como..." sem verificar
## Step 4: Trace the Data Flow
### Identify the Source
- HTTP request parameters (query, body, headers, cookies)
- File uploads
- Database records (se populated por user input elsewhere)
- Message queues / event payloads
### Trace Through Transformations
- Validado? (type check, regex, allowlist)
- Sanitizado? (HTML encoding, SQL escaping, shell quoting)
- Transformado em safe type? (parsed as integer, resolved as enum)
- Passa por framework-level protection? (ORM parameterization, template auto-escape)
### Document the Chain
```
Source: req.query.search (user-controlled, string, sem length limit)
→ passed to: buildQuery(search) em db/queries.js:45
→ buildQuery concatena em SQL string (SEM parameterization)
→ executed via: db.raw(query) em db/queries.js:52
Sink: raw SQL execution
Mitigations: nenhuma encontrada
Verdict: CONFIRMED — SQL injection clássica
```
## Step 5: Attempt Proof-of-Concept
Se pode demonstrar exploitation safety sem causar dano:
**Para injection flaws:** Construa payload que produz observable side effect.
**Para auth bypasses:** Mostre o request que alcança protected resources sem credentials válidos.
**Para path traversal:** Mostre o path que resolve fora do diretório intended.
### Quando Dynamic Testing Não É Viável
- Rely em static trace: source → transforms → sink
- State: "Static analysis only — no dynamic confirmation"
- Note o que seria necessário para confirmar dinamicamente
- Ainda válido para `confirmed` se static trace é unambíguo
## Step 6: Render Verdict
| Verdict | Critérios |
|---------|----------|
| **confirmed** | Data attacker-controlled alcança dangerous sink com proteção insuficiente. Exploit path claro. Todos 5 gates passed. |
| **rejected** | Pattern não existe, código unreachable, ou mitigações previnem completamente exploitation. Evidência concreta de por quê. |
| **needs-more-info** | Não pode determinar. Especifique exatamente o que está faltando. |
## Step 7: Record
```bash
python3 scripts/scan_db.py validate \
--finding-id <id> \
--verdict <confirmed|rejected|needs-more-info> \
--evidence "source: req.query.q → sink: db.raw() em queries.js:52, sem parameterization" \
--poc "GET /api/search?q=' OR 1=1--" \
--notes "Static trace only, no dynamic confirmation"
```
## Princípios
- Finding sem traceable data flow não é confirmed — é hipótese.
- Scanners reportam patterns, não exploits. Seu job é determinar se o pattern é explorável em contexto.
- "Rejected" é fine. Documente por quê e siga em frente.
- "Needs-more-info" é honesto. Melhor que adivinhar.
- Mitigações reduzem risco mas não eliminam findings. SQLi behind WAF ainda é SQLi.
- **Kill false positives agressivamente, mas não mate findings reais.** Report curto com 3 findings reais vale mais que report longo com 30 teóricos.