# Pentest Reporting

> PTES Phase 6 - Reporting for AWS security assessments

- Skill: `bob-reis/pentest-reporting` (Agent Skill)
- Install (CLI): `npx skillmds@latest add bob-reis/pentest-reporting`
- Raw SKILL.md: https://api.skillmd.com/api/skills/bob-reis/pentest-reporting/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: DevOps & Infra
- Author: bob-reis (https://skillmd.com/u/bob-reis)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/bob-reis/pentest-reporting

---


# PTES Phase 6: Reporting

## 🎯 pfSense Detection & Routing

> **DETECTION:** Se o alvo for **pfSense**, ative a skill `pentest-pfsense` para metodologia completa.

### Detection Signals
- [ ] Web GUI title contains "pfSense"
- [ ] HTTP headers: `Server: pfsense`, `X-Powered-By: pfSense`
- [ ] Default paths: `/firewall_rules.php`, `/system.php`, `/diag_logs.php`
- [ ] Shodan: `http.title:"pfSense"`, `http.favicon.hash:-1295592153`
- [ ] nmap: `http.title` script returns "pfSense"

### Action
→ **Activate `pentest-pfsense` skill** for:
- Complete pentest methodology (12 phases)
- 27+ CVEs organized by exploitability
- Feature-based testing checklist (158 features)
- Stealth scanning guidance (firewall-aware)
- PoC templates and exploitation workflows

---

## 🎯 pfSense Findings Integration

> **IMPORTANTE:** Se **pfSense** foi testado durante o engagement, use a skill `pentest-pfsense` como referência para findings específicos.

### pfSense Finding Templates

#### Critical Findings (CVSS 9.0+)
```
- CVE-2022-40624: pfBlockerNG Host Header RCE (CVSS 9.8)
- CVE-2022-31814: pfBlockerNG Path Traversal RCE (CVSS 9.8)
- CVE-2025-12490: Suricata Path Traversal → RCE (CVSS 8.8)
- CVE-2023-42326: Command Injection (GIF/GRE interfaces) (CVSS 8.8)
- CVE-2023-48123: Packet Capture RCE (CVSS 8.8)
```

#### High Findings (CVSS 7.0-8.9)
```
- CVE-2023-27253: RRD Restore Command Injection (CVSS 8.8)
- CVE-2023-48795: Terrapin SSH Attack (CVSS 5.9, EPSS 99º)
- CVE-2025-34172: HAProxy XSS + Socket Injection (CVSS 6.1)
- CVE-2025-34175: Suricata Reflected XSS (CVSS 6.1)
```

#### Medium Findings (CVSS 4.0-6.9)
```
- CVE-2025-53392: Arbitrary File Read (CVSS 6.5)
- CVE-2022-29273: Stored XSS via URL Alias (CVSS 6.1)
- CVE-2024-57273: OpenVPN DoS (CVSS 5.3)
- CVE-2025-34174: Status Traffic Totals XSS (CVSS 5.4)
```

### Remediation Guidance

```
pfSense-Specific Recommendations:

1. UPGRADE IMEDIATO
   - pfSense CE: 2.7.x → 2.8.0+
   - pfSense Plus: 23.09 → 24.03+
   - Packages: pfBlockerNG, Suricata, Snort (latest)

2. MITIGAÇÕES TEMPORÁRIAS
   - System Patches package (Netgate recomendado)
   - Desabilitar serviços não essenciais
   - Restringir acesso à webGUI por IP
   - Remover privilégios de diagnóstico

3. MONITORAMENTO
   - Alertas de login falho
   - Log de alterações de config
   - Detecção de comandos suspeitos
```

### Compliance Mapping

```
pfSense Findings → Frameworks:

| Finding | MITRE ATT&CK | CIS Control | NIST |
|---------|--------------|-------------|------|
| RCE via diag_command.php | T1190 (Exploit Public-Facing App) | 7.1 (Vuln Mgmt) | SI-2 |
| Default credentials | T1078 (Valid Accounts) | 5.2 (Account Mgmt) | IA-2 |
| Config file access | T1003 (Credential Dumping) | 3.5 (Access Control) | AC-3 |
| HA sync abuse | T1563 (Service Session Hijack) | 4.4 (Comm Protection) | SC-23 |
```

---

## Objetivo
Documentar detalhadamente todos os achados, riscos associados, evidências e recomendações de correção para o cliente.

## Referências PTES Section 6

### PTES 6.1 Executive-Level Reporting
- Business Impact
- Customization for audience
- Talking to the business
- Affect bottom line
- Strategic Roadmap
- Maturity model
- Appendix with terms for risk rating

### PTES 6.2 Technical Reporting
- Identify systemic issues and technical root cause analysis
- Maturity Model
- Technical Findings (Description, Screenshots, PII redacted, Request/Response, PoC)
- Reproducible Results (Test Cases, Fault triggers)
- Incident response and monitoring capabilities
- Common elements (Methodology, Objective, Scope, Summary, Risk rating appendix)

### PTES 6.3 Quantifying the Risk
- Evaluate incident frequency
- Risk matrix (Probability × Impact)
- CVSS scoring integration
- Business context weighting

### PTES 6.4 Deliverable
- Final report formats (PDF, HTML, JSON, CSV)
- Presentation to stakeholders
- Lessons learned documentation
- Re-testing recommendations

---

## Geração de Relatórios com WorstAssume

### 0. OWASP Nettacker Export Formats (PTES 6.4 - Deliverable)

> **NOTE:** Nettacker supports **5 output formats** for different stakeholders and integrations.

#### Output Formats Available

```bash
# HTML Report (with graphs) - For executives and non-technical stakeholders
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m port_scan,vuln \
  --graph-output /tmp/nettacker_report.html

# JSON - For programmatic processing and SIEM integration
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m port_scan,vuln \
  --json-output /tmp/nettacker_report.json

# CSV - For spreadsheet analysis and filtering
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m port_scan,vuln \
  --csv-output /tmp/nettacker_report.csv

# SARIF - For GitHub Security tab and code scanning tools
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m port_scan,vuln \
  --sarif-output /tmp/nettacker_report.sarif

# DefectDojo (.dd.json) - For DefectDojo vulnerability management platform
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m port_scan,vuln \
  --dd-output /tmp/nettacker_report.dd.json
```

#### Format Comparison

| Format | Best For | Stakeholder | Integration |
|--------|----------|-------------|-------------|
| **HTML** | Executive presentations, visual reports | Management, Clients | Standalone |
| **JSON** | SIEM, automation, custom processing | Security Engineers | Splunk, ELK |
| **CSV** | Spreadsheet analysis, filtering | Analysts | Excel, Google Sheets |
| **SARIF** | GitHub Security, DevOps pipelines | Developers | GitHub, Azure DevOps |
| **DefectDojo** | Vulnerability management | Security Teams | DefectDojo |

#### Nettacker + WorstAssume Combined Export

```bash
# Step 1: Nettacker external scan
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET.com -m port_scan,vuln,ssl_*_vuln \
  --json-output /tmp/nettacker_external.json \
  --graph-output /tmp/nettacker_external.html

# Step 2: WorstAssume AWS enumeration
worst enumerate --profile <profile> --output json > /tmp/worstassume_aws.json

# Step 3: Consolidate findings
jq -s '{
  nettacker: .[0],
  worstassume: .[1],
  generated_at: now
}' /tmp/nettacker_external.json /tmp/worstassume_aws.json \
  > /tmp/consolidated_findings.json

# Step 4: Generate executive summary
jq -r '.nettacker.results[] | "Finding: \(.title)\nSeverity: \(.severity)\nTarget: \(.target)"' \
  /tmp/nettacker_external.json > /tmp/executive_summary.txt
```

### 1. Exportar Dados do Assessment

```bash
# Exportar findings em JSON estruturado
worst privesc --from <arn> --output json > attack-paths.json

# Exportar grafo completo para análise
worst graph-export --output graph.json

# Dashboard web para visualização
worst viz --port 3000
# Acessar http://localhost:3000 e usar Export
```

### 2. Comandos de Export Específicos

```bash
# Listar todas as cadeias de ataque detectadas
worst privesc --db findings.db --all

# Filtrar por severidade mínima
worst privesc --db findings.db --min-severity HIGH

# Exportar por família de ataque
worst privesc --db findings.db --family "IAM Self-Modification" --output family-iam.json
worst privesc --db findings.db --family "PassRole+Compute" --output family-passrole.json
worst privesc --db findings.db --family "Compute Credential Theft" --output family-compute.json
worst privesc --db findings.db --family "Secret Exfiltration" --output family-secret.json
worst privesc --db findings.db --family "Account Takeover" --output family-account.json
worst privesc --db findings.db --family "Group Membership" --output family-group.json
worst privesc --db findings.db --family "Cross-Account Lateral Movement" --output family-crossaccount.json

# Exportar todos os PATH-IDs descobertos
worst privesc --db findings.db --output all-paths.json --include-all
```

### 3. Estrutura do JSON de Export (SecurityFinding Schema)

```json
{
  "finding_id": "FINDING-001",
  "path_id": "PATH-001",
  "category": "WEAK_TRUST",
  "subcategory": "WildcardTrustNoCondition",
  "severity": "CRITICAL",
  "original_severity": "CRITICAL",
  "downgrade_reason": null,
  "principal_arn": "arn:aws:iam::123456789012:role/ExampleRole",
  "principal_type": "ROLE",
  "account_id": "123456789012",
  "region": "us-east-1",
  "trust_policy": {
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": "*",
      "Action": "sts:AssumeRole"
    }]
  },
  "permissions": ["iam:*", "ec2:*", "s3:*"],
  "managed_policies": ["arn:aws:iam::aws:policy/AdministratorAccess"],
  "inline_policies": ["FullAccess"],
  "groups": ["Admins"],
  "risk_factors": {
    "has_wildcard_trust": true,
    "has_external_account_trust": false,
    "has_dangerous_managed_policy": true,
    "has_resource_wildcard": true,
    "missing_condition_keys": true
  },
  "attack_chain": {
    "family": "IAM Self-Modification",
    "chain_id": "CreatePolicy+Attach",
    "hops": 2,
    "outcome": "Self Admin Escalation"
  },
  "evidence": {
    "command": "aws iam get-role --role-name ExampleRole",
    "output": "{...}"
  },
  "recommendation": "Remove wildcard principal from trust policy. Add condition keys: aws:PrincipalArn, aws:SourceAccount",
  "remediation_effort": "LOW",
  "cvss_score": 9.8,
  "created_at": "2026-04-24T10:30:00Z"
}
```

### 4. Query Direta no Banco SQLite

```bash
# Exportar todos os findings CRITICAL
sqlite3 findings.db "SELECT * FROM SecurityFinding WHERE severity='CRITICAL';"

# Count por categoria
sqlite3 findings.db "SELECT category, COUNT(*) as count FROM SecurityFinding GROUP BY category;"

# Count por severidade
sqlite3 findings.db "SELECT severity, COUNT(*) as count FROM SecurityFinding GROUP BY severity ORDER BY severity;"

# Findings com AdministratorAccess
sqlite3 findings.db "SELECT principal_arn, path_id FROM SecurityFinding WHERE managed_policies LIKE '%AdministratorAccess%';"

# Exportar em formato JSON
sqlite3 findings.db ".mode json" ".output findings.json" "SELECT * FROM SecurityFinding;"
```

### 5. Dashboard Viz - Exportação

```bash
# Iniciar dashboard
worst viz --db findings.db --port 3000

# No browser (http://localhost:3000):
# 1. Filtrar por severidade (dropdown)
# 2. Filtrar por categoria (dropdown)
# 3. Click em "Export JSON" ou "Export CSV"
# 4. Download do arquivo formatado
```

### 6. Database Schema para Export

```sql
-- Tabela principal: SecurityFinding
CREATE TABLE SecurityFinding (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    finding_id TEXT UNIQUE NOT NULL,      -- FINDING-0001
    path_id TEXT NOT NULL,                 -- PATH-001
    category TEXT NOT NULL,                -- WEAK_TRUST, PERMISSIVE_POLICY, etc.
    subcategory TEXT NOT NULL,             -- WildcardTrustNoCondition, etc.
    severity TEXT NOT NULL,                -- CRITICAL, HIGH, MEDIUM, LOW, INFO
    original_severity TEXT NOT NULL,       -- Severidade antes do downgrade
    downgrade_reason TEXT,                 -- Motivo do downgrade se aplicável
    principal_arn TEXT NOT NULL,           -- ARN do principal afetado
    principal_type TEXT NOT NULL,          -- USER, ROLE, GROUP, ROOT
    account_id TEXT NOT NULL,              -- 123456789012
    region TEXT,                           -- us-east-1, etc.
    trust_policy TEXT,                     -- JSON do trust policy
    permissions TEXT,                      -- JSON array de permissões
    managed_policies TEXT,                 -- JSON array de managed policies
    inline_policies TEXT,                  -- JSON array de inline policies
    groups TEXT,                           -- JSON array de grupos
    risk_factors TEXT,                     -- JSON com fatores de risco
    attack_chain TEXT,                     -- JSON da attack chain
    evidence TEXT,                         -- JSON com evidências
    recommendation TEXT,                   -- Texto da recomendação
    remediation_effort TEXT,               -- LOW, MEDIUM, HIGH
    cvss_score REAL,                       -- 0.0-10.0
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Índices para performance
CREATE INDEX idx_severity ON SecurityFinding(severity);
CREATE INDEX idx_category ON SecurityFinding(category);
CREATE INDEX idx_account ON SecurityFinding(account_id);
CREATE INDEX idx_principal ON SecurityFinding(principal_arn);
```

### 7. Workflow de Export para Relatório

```bash
# Passo 1: Exportar todos os findings
sqlite3 findings.db ".mode json" ".output all-findings.json" "SELECT * FROM SecurityFinding ORDER BY severity, category;"

# Passo 2: Exportar apenas CRITICAL + HIGH
sqlite3 findings.db ".mode json" ".output critical-high.json" "SELECT * FROM SecurityFinding WHERE severity IN ('CRITICAL', 'HIGH') ORDER BY severity DESC;"

# Passo 3: Gerar resumo estatístico
sqlite3 findings.db <<EOF
.mode column
.headers on
.output summary.txt
SELECT 
    severity,
    COUNT(*) as total,
    COUNT(DISTINCT account_id) as accounts_affected,
    COUNT(DISTINCT category) as categories
FROM SecurityFinding 
GROUP BY severity 
ORDER BY 
    CASE severity 
        WHEN 'CRITICAL' THEN 1 
        WHEN 'HIGH' THEN 2 
        WHEN 'MEDIUM' THEN 3 
        WHEN 'LOW' THEN 4 
        WHEN 'INFO' THEN 5 
    END;
EOF

# Passo 4: Exportar por categoria para análise separada
for category in WEAK_TRUST PERMISSIVE_POLICY RESOURCE_WILDCARD USER_CONFIG GROUP_CONFIG; do
    sqlite3 findings.db ".mode json" ".output category-${category}.json" "SELECT * FROM SecurityFinding WHERE category='${category}';"
done

# Passo 5: Gerar CSV para tracking em planilhas
sqlite3 findings.db <<EOF
.mode csv
.headers on
.output findings.csv
SELECT 
    finding_id,
    severity,
    category,
    subcategory,
    principal_arn,
    recommendation
FROM SecurityFinding 
ORDER BY severity, finding_id;
EOF
```

### 8. Template de Finding Técnico (PTES 6.2)

```markdown
# FINDING-XXX: [Título do Finding]

## Metadados
- **Severity:** [CRITICAL/HIGH/MEDIUM/LOW/INFO]
- **Category:** [WEAK_TRUST/PERMISSIVE_POLICY/RESOURCE_WILDCARD/USER_CONFIG/GROUP_CONFIG]
- **Path-ID:** [PATH-XXX]
- **CVSS Score:** [X.X]
- **Affected Principal:** `arn:aws:iam::ACCOUNT:resource/name`
- **Account:** [123456789012]
- **Region:** [us-east-1]

## Descrição
[Descrição técnica detalhada do finding, explicando a vulnerabilidade
e como foi descoberta através do WorstAssume.]

## Evidência
```json
{
  "principal_arn": "arn:aws:iam::123456789012:role/ExampleRole",
  "trust_policy": {...},
  "permissions": ["iam:*", "ec2:*", "s3:*"],
  "managed_policies": ["arn:aws:iam::aws:policy/AdministratorAccess"]
}
```

## Attack Path
```
[Identidade Inicial]
    │
    │ [Ação 1: iam:CreatePolicy]
    ▼
[Recurso Intermediário]
    │
    │ [Ação 2: iam:AttachUserPolicy]
    ▼
[Objetivo Final - Admin Access]
```

## Impacto
[Descrição do impacto se explorado, incluindo:
- Dados que podem ser acessados
- Ações que podem ser executadas
- Contas que podem ser comprometidas]

## Recomendação
[Passos específicos para remediar, incluindo comandos AWS CLI exatos.]

### Comando de Correção
```bash
aws iam [comando específico]
```

### Policy Corrigida
```json
{
  "Version": "2012-10-17",
  "Statement": [...]
}
```

## Referências
- [AWS IAM Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
- [AWS Security Best Practices](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-best-practices.html)
```

### 9. Validação de Qualidade do Export

```bash
# Verificar count total de findings
TOTAL=$(sqlite3 findings.db "SELECT COUNT(*) FROM SecurityFinding;")
echo "Total findings: $TOTAL"

# Verificar distribuição por severidade
sqlite3 findings.db "SELECT severity, COUNT(*) FROM SecurityFinding GROUP BY severity;"

# Verificar findings sem recomendação (erro de qualidade)
sqlite3 findings.db "SELECT finding_id FROM SecurityFinding WHERE recommendation IS NULL OR recommendation = '';"

# Verificar findings sem evidence (erro de qualidade)
sqlite3 findings.db "SELECT finding_id FROM SecurityFinding WHERE evidence IS NULL OR evidence = '{}';"

# Validar JSON exports
for f in *.json; do
    jq empty "$f" && echo "$f: OK" || echo "$f: INVALID JSON"
done
```

---

## 2. Estrutura do Relatório

### Seção 1: Executive Summary
```
RESUMO EXECUTIVO

ENGAGEMENT: [Nome do Projeto]
PERÍODO: [Data início] - [Data fim]
CLASSIFICAÇÃO: [Confidencial]

VISÃO GERAL:
[Parágrafo descrevendo o escopo e objetivos do teste]

SUMÁRIO DE RISCOS:
┌─────────────┬───────┬────────────┐
│ Severidade  │ Count │ Trend      │
├─────────────┼───────┼────────────┤
│ CRITICAL    │   X   │ [↑↓→]      │
│ HIGH        │   X   │ [↑↓→]      │
│ MEDIUM      │   X   │ [↑↓→]      │
│ LOW         │   X   │ [↑↓→]      │
│ INFO        │   X   │ [↑↓→]      │
└─────────────┴───────┴────────────┘

PRINCIPAIS ACHADOS:
1. [Finding crítico #1 - 1 linha]
2. [Finding crítico #2 - 1 linha]
3. [Finding crítico #3 - 1 linha]

RISCO GERAL: [CRITICAL / HIGH / MEDIUM / LOW]

RECOMENDAÇÕES PRIORITÁRIAS:
1. [Recomendação crítica #1]
2. [Recomendação crítica #2]
3. [Recomendação crítica #3]
```

### Seção 2: Escopo e Metodologia
```
ESCOPO E METODOLOGIA

CONTAS AWS TESTADAS:
- Account ID: [123456789012] - [Nome/Nome do ambiente]
- Account ID: [234567890123] - [Nome/Nome do ambiente]
- Total: [X] contas

REGIÕES TESTADAS:
- [us-east-1, us-west-2, eu-west-1, ...]

SERVIÇOS TESTADOS:
- IAM (Identity and Access Management)
- EC2 (Elastic Compute Cloud)
- S3 (Simple Storage Service)
- Lambda (Serverless Computing)
- ECS (Elastic Container Service)
- [Outros serviços...]

METODOLOGIA:
Este assessment seguiu o PTES (Penetration Testing Execution Standard)
com as seguintes fases:

1. Pre-Engagement Interactions
2. Intelligence Gathering
3. Threat Modeling
4. Vulnerability Analysis
5. Exploitation
6. Post-Exploitation
7. Reporting

FERRAMENTAS UTILIZADAS:
- WorstAssume v[X.X.X] - AWS IAM enumeration and attack graph analysis
- AWS CLI v[X.X.X] - Manual verification and exploitation
- [Outras ferramentas...]

TIPO DE TESTE:
[ ] Black Box
[ ] Grey Box
[✓] White Box

LIMITAÇÕES:
- [Serviços não testados]
- [Restrições de tempo]
- [Restrições de acesso]
```

### Seção 3: Findings Detalhados
```
FINDINGS DETALHADOS

═══════════════════════════════════════════════════════════════════════════
FINDING #1: [Título do Finding]
═══════════════════════════════════════════════════════════════════════════

SEVERIDADE: [CRITICAL / HIGH / MEDIUM / LOW / INFO]
CATEGORIA: [WEAK_TRUST / PERMISSIVE_POLICY / RESOURCE_WILDCARD / etc.]
PATH-ID: [PATH-XXX]
CVSS SCORE: [X.X] (opcional)

AFETADOS:
- Tipo: [IAM User / IAM Role / EC2 Instance / etc.]
- ARN: arn:aws:iam::ACCOUNT:resource/name
- Conta: [123456789012]
- Região: [us-east-1]

DESCRIÇÃO:
[Descrição detalhada da vulnerabilidade em 2-3 parágrafos. Explicar o que
foi encontrado, por que é um problema, e como foi descoberto.]

IMPACTO:
[Descrição do impacto potencial se esta vulnerabilidade for explorada.
Incluir cenários de pior caso e dados que podem ser comprometidos.]

PROVA DE CONCEITO:
# Comandos executados durante o teste
aws [comando 1]
aws [comando 2]

# Output observado
{
  "evidence": "output aqui"
}

ATTACK PATH:
[A] Identidade Inicial (arn:aws:iam::...)
    │
    │ iam:CreatePolicyVersion
    ▼
[B] Policy Version Criada
    │
    │ iam:AttachUserPolicy
    ▼
[C] Admin Access Obtido

RECOMENDAÇÃO:
[Passos específicos para remediar esta vulnerabilidade. Ser o mais
específico possível, incluindo comandos ou configurações exatas.]

REMEDIATION EXAMPLE:
# Exemplo de comando para corrigir
aws iam [comando de correção]

# Exemplo de policy corrigida
{
  "Version": "2012-10-17",
  "Statement": [...]
}

PRIORIDADE: [IMEDIATA / ALTA / MÉDIA / BAIXA]
ESFORÇO ESTIMADO: [X horas/dias]
DIFFICULDADE: [Fácil / Média / Difícil]

REFERÊNCIAS:
- AWS IAM Best Practices: https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html
- AWS Security Best Practices: https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-best-practices.html
- [Outras referências relevantes]
```

### Seção 4: Attack Paths Descobertos
```
ATTACK PATHS DESCOBERTOS

PATH #1: [Nome do Attack Path]
─────────────────────────────────
SEVERIDADE: CRITICAL
HOPS: [X]
DE → PARA: [Identidade inicial] → [Objetivo final]

SEQUÊNCIA DE AÇÕES:
┌────┬─────────────────────────────────┬──────────────────────────────────┐
│ #  │ Ação                            │ Explicação                       │
├────┼─────────────────────────────────┼──────────────────────────────────┤
│ 1  │ iam:CreatePolicyVersion         │ Criar versão admin da policy     │
│ 2  │ iam:AttachUserPolicy            │ Attach policy ao próprio user    │
│ 3  │ sts:GetCallerIdentity           │ Verificar permissões elevadas    │
└────┴─────────────────────────────────┴──────────────────────────────────┘

TEMPO ESTIMADO DE EXPLORAÇÃO: [X minutos/horas]
DETECÇÃO: [Baixa / Média / Alta]
MITIGAÇÃO: [Resumo da mitigação]

[Incluir diagrama visual se possível]
```

### Seção 5: Matriz de Riscos
```
MATRIZ DE RISCOS

                    IMPACTO
              Baixo  Médio  Alto  Crítico
PROB.  Alta    [M]    [H]    [C]    [C]
       Média   [L]    [M]    [H]    [C]
       Baixa   [L]    [L]    [M]    [H]

FINDINGS NA MATRIZ:
┌─────────────────────────────────────┬────────────┬───────────┬───────────┐
│ Finding                             │ Probabilidade │ Impacto   │ Risco     │
├─────────────────────────────────────┼────────────┼───────────┼───────────┤
│ Wildcard Trust Policy               │ Alta       │ Crítico   │ CRITICAL  │
│ IAM Admin via Policy Version        │ Média      │ Crítico   │ CRITICAL  │
│ Cross-Account Lateral Movement      │ Média      │ Alto      │ HIGH      │
│ IMDSv1 Credential Theft             │ Alta       │ Médio     │ HIGH      │
│ Stale Access Keys                   │ Baixa      │ Médio     │ MEDIUM    │
└─────────────────────────────────────┴────────────┴───────────┴───────────┘
```

### Seção 6: Apêndices
```
APÊNDICES

APÊNDICE A: COMANDOS EXECUTADOS
[Lista completa de todos os comandos AWS CLI executados]

APÊNDICE B: EVIDÊNCIAS
[Screenshots, outputs, logs de todas as explorações]

APÊNDICE C: GLOSSÁRIO
[Definições de termos técnicos usados no relatório]

APÊNDICE D: REFERÊNCIAS
[Lista completa de referências e documentação AWS]

APÊNDICE E: HISTÓRICO DE MUDANÇAS
┌────────────┬───────────────┬────────────────────────────────────────────┐
│ Versão     │ Data          │ Mudanças                                   │
├────────────┼───────────────┼────────────────────────────────────────────┤
│ 1.0        │ YYYY-MM-DD    │ Versão inicial do relatório                │
│ 1.1        │ YYYY-MM-DD    │ Adicionado finding #X, atualizado finding #Y│
└────────────┴───────────────┴────────────────────────────────────────────┘
```

---

## 9. Nettacker Report Templates

### HTML Report Template (Executive)

```bash
# Generate HTML report with graphs
docker run --rm -v $(pwd):/reports owasp/nettacker \
  -i TARGET.com -m port_scan,vuln,ssl_*_vuln \
  --graph-output /reports/executive_report.html

# Open in browser for presentation
firefox /reports/executive_report.html
```

**HTML Report Sections:**
- Executive Summary with severity charts
- Vulnerability timeline
- Network topology graph
- CVE details with CVSS scores
- Remediation recommendations

### JSON Export for SIEM Integration

```bash
# Generate JSON for Splunk/ELK
docker run --rm -v $(pwd):/reports owasp/nettacker \
  -i TARGET.com -m port_scan,vuln \
  --json-output /reports/siem_export.json

# Parse for specific findings
jq '.results[] | select(.severity == "CRITICAL")' /reports/siem_export.json

# Convert to ECS format for Elasticsearch
jq '.results[] | {
  "@timestamp": .date,
  "host": {"ip": .target},
  "vulnerability": {
    "cve": .cve_id,
    "severity": .severity,
    "description": .description
  }
}' /reports/siem_export.json > /reports/ecs_format.json
```

### CSV Export for Spreadsheet Analysis

```bash
# Generate CSV for Excel/Google Sheets
docker run --rm -v $(pwd):/reports owasp/nettacker \
  -i TARGET.com -m port_scan,vuln \
  --csv-output /reports/findings.csv

# Filter in Excel/Sheets:
# - Sort by severity
# - Filter by target
# - Pivot by vulnerability type
```

**CSV Columns:**
```
Target,Port,Vulnerability,Severity,CVSS,Description,Remediation,Date
```

### SARIF Export for GitHub Security

```bash
# Generate SARIF for GitHub Security tab
docker run --rm -v $(pwd):/reports owasp/nettacker \
  -i TARGET.com -m vuln \
  --sarif-output /reports/github_security.sarif

# Upload to GitHub
gh api \
  --method POST \
  /repos/OWNER/REPO/code-scanning/sarifs \
  -f commit_sha=$(git rev-parse HEAD) \
  -f ref=refs/heads/main \
  -f sarif=$(base64 -i /reports/github_security.sarif)
```

### DefectDojo Integration

```bash
# Generate DefectDojo format
docker run --rm -v $(pwd):/reports owasp/nettacker \
  -i TARGET.com -m port_scan,vuln \
  --dd-output /reports/defectdojo.json

# Upload to DefectDojo via API
curl -X POST "https://defectdojo.local/api/v2/import-scan/" \
  -H "Authorization: Token $DD_API_KEY" \
  -F "file=@/reports/defectdojo.json" \
  -F "engagement=$ENGAGEMENT_ID" \
  -F "scan_type=Nettacker Scan"
```

---

## 10. Templates de Export

### JSON Export (Estruturado)
```json
{
  "reportMetadata": {
    "engagementName": "AWS Security Assessment",
    "client": "Client Name",
    "dateRange": {
      "start": "YYYY-MM-DD",
      "end": "YYYY-MM-DD"
    },
    "reportVersion": "1.0",
    "classification": "Confidential"
  },
  "executiveSummary": {
    "totalFindings": 15,
    "bySeverity": {
      "CRITICAL": 3,
      "HIGH": 5,
      "MEDIUM": 4,
      "LOW": 2,
      "INFO": 1
    },
    "overallRisk": "HIGH"
  },
  "findings": [...],
  "attackPaths": [...],
  "scope": {...},
  "methodology": {...}
}
```

### CSV Export (Para planilhas)
```csv
FindingID,Severity,Category,Title,AffectedResource,Recommendation,Status
FINDING-001,CRITICAL,WEAK_TRUST,Wildcard Trust Policy,arn:aws:iam::123:role/X,Remove wildcard principal,Open
FINDING-002,HIGH,PERMISSIVE_POLICY,Admin Access,arn:aws:iam::123:user/Y,Remove admin policy,Open
```

---

## 11. Checklist de Qualidade do Relatório

### Conteúdo
- [ ] Executive summary claro e conciso
- [ ] Todos os findings documentados com evidências
- [ ] Attack paths visualmente representados
- [ ] Recomendações acionáveis e específicas
- [ ] Priorização clara (CRITICAL > HIGH > MEDIUM > LOW)
- [ ] Referências relevantes incluídas

### Formatação
- [ ] Numeração consistente de findings
- [ ] Headers e subheaders hierárquicos
- [ ] Código formatado em blocks monospace
- [ ] Tabelas alinhadas e legíveis
- [ ] Diagramas/imagens com legendas
- [ ] Índice/TOC para relatórios longos

### Revisão
- [ ] Verificar ortografia e gramática
- [ ] Validar todos os ARNs e comandos
- [ ] Confirmar severidades estão corretas
- [ ] Remover dados sensíveis do relatório
- [ ] Verificar consistência de terminologia
- [ ] Revisar por múltiplos revisores

---

## 12. Apresentação para Stakeholders

### Slide Deck Structure
```
SLIDE 1: Title Slide
- Project name, date, presenter

SLIDE 2: Executive Summary
- Overall risk rating
- Key findings (top 3-5)

SLIDE 3: Scope & Methodology
- What was tested
- How it was tested

SLIDE 4-8: Critical Findings
- One slide per critical finding
- Visual representation of attack path

SLIDE 9: Risk Matrix
- Visual risk matrix with findings plotted

SLIDE 10: Recommendations
- Prioritized remediation roadmap

SLIDE 11: Timeline
- Remediation timeline with milestones

SLIDE 12: Q&A
```

---

## 12. Risk Quantification (PTES 6.3)

### Risk Matrix Template
```
                    IMPACTO
              Baixo  Médio  Alto  Crítico
PROB.  Alta    [M]    [H]    [C]    [C]
       Média   [L]    [M]    [H]    [C]
       Baixa   [L]    [L]    [M]    [H]

Finding Placement Example:
┌─────────────────────────────────────┬────────────┬───────────┬───────────┐
│ Finding                             │ Probabilidade │ Impacto   │ Risco     │
├─────────────────────────────────────┼────────────┼───────────┼───────────┤
│ Wildcard Trust Policy               │ Alta       │ Crítico   │ CRITICAL  │
│ SQL Injection                       │ Média      │ Crítico   │ CRITICAL  │
│ Cross-Account Lateral Movement      │ Média      │ Alto      │ HIGH      │
│ Stored XSS                          │ Alta       │ Médio     │ HIGH      │
│ Missing Security Headers            │ Baixa      │ Baixo     │ LOW       │
└─────────────────────────────────────┴────────────┴───────────┴───────────┘
```

### Business Impact Weighting
```
Industry-Specific Considerations:

Healthcare (HIPAA):
- PHI exposure = Automatic HIGH/CRITICAL
- Patient safety impact = CRITICAL

Financial (PCI-DSS, SOX):
- Cardholder data = CRITICAL
- Financial fraud potential = CRITICAL

E-commerce:
- Customer PII = HIGH/CRITICAL
- Payment processing = CRITICAL

SaaS/Cloud:
- Multi-tenant data exposure = CRITICAL
- Authentication bypass = CRITICAL
```

---

## 13. Ferramentas de Report

### WorstAssume Export Commands
```bash
# Via dashboard web (worst viz)
# Click em "Export" → Select format (HTML/JSON/CSV)

# JSON export via CLI
worst privesc --from <arn> --output json > paths.json

# Graph export
worst graph-export --output graph.json
```

### AWS CLI para Evidências
```bash
# Capturar evidências em formato estruturado
aws sts get-caller-identity --output json > evidence-identity.json
aws iam get-role --role-name <role> --output json > evidence-role.json
```

### hping3 para Evidências de Network Testing
```bash
# Capturar output de scans para evidência
hping3 -S -p 80 -c 10 target.com 2>&1 | tee evidence-syn-scan.txt

# Documentar firewall mapping
hping3 -A -p 80 target.com 2>&1 | tee evidence-ack-scan.txt

# Salvar resultados de port scanning
hping3 -S -p 1-1000 --scan target.com 2>&1 | tee evidence-port-scan.txt

# Gerar relatório de IDS evasion testing
{
  echo "=== XMAS Scan Test ==="
  hping3 -F -P -U -p 80 -c 10 target.com
  echo ""
  echo "=== NULL Scan Test ==="
  hping3 -O -p 80 -c 10 target.com
  echo ""
  echo "=== Fragmented Packet Test ==="
  hping3 -S -p 80 -f -c 10 target.com
} | tee evidence-ids-evasion.txt
```

### Template de Finding de Rede para Relatório (PTES 6.2)
```markdown
# FINDING-NET-XXX: [Título do Finding de Rede]

## Metadados
- **Severity:** [CRITICAL/HIGH/MEDIUM/LOW/INFO]
- **Category:** NETWORK_VULNERABILITY
- **Tool:** hping3
- **CVSS Score:** [X.X]
- **Affected Host:** `target.com (IP)`
- **Portas/Services:** [lista]

## Descrição
[Descrição técnica da vulnerabilidade de rede identificada
através de scans com hping3.]

## Evidência (hping3 output)
```
HPING target.com (IP): S set, 40 headers + 0 data bytes
<-- [output do hping3 capturado] -->
```

## Técnica Utilizada
- **Scan Type:** [SYN/ACK/XMAS/NULL/ICMP]
- **Flags:** [-S/-A/-FPU/-O/etc.]
- **Portas:** [range ou lista]
- **Evasion:** [fragmentation/spoofing/timing]

## Impacto
[Descrição do impacto se explorado, incluindo:
- Serviços expostos
- Possibilidade de lateral movement
- Risco de comprometimento de rede]

## Recomendação
[Passos específicos para remediar, incluindo:
- Configuração de firewall
- Regras de filtragem
- IDS/IPS tuning]

## Referências
- PTES 2.5.4 - Active Footprinting
- PTES 3.1.1 - Vulnerability Testing
- PTES 4.1.1 - Countermeasure Bypass
```

---

## 14. Report Writing com pentest-advisor Agent

### Professional Report Structure (pentest-advisor)
```
EXECUTIVE SUMMARY Structure:
1. Engagement Overview (1 paragraph)
2. Overall Risk Rating (CRITICAL/HIGH/MEDIUM/LOW)
3. Key Findings Summary (3-5 bullet points)
4. Strategic Recommendations (prioritized)

TECHNICAL REPORT Structure:
1. Scope and Methodology
2. Detailed Findings (per vulnerability)
3. Attack Paths Discovered
4. Risk Matrix
5. Remediation Roadmap
6. Appendices (evidence, commands, references)
```

### CVSS Scoring Integration (pentest-advisor)
```
Risk Assessment Framework:

Attack Vector (AV):
- Network (N): Vulnerability exploitable remotely
- Adjacent (A): Local network access required
- Local (L): Local access required
- Physical (P): Physical access required

Attack Complexity (AC):
- Low (L): No special conditions
- High (H): Specialized conditions required

Privileges Required (PR):
- None (N): No authentication needed
- Low (L): Basic user privileges
- High (H): Administrative privileges

User Interaction (UI):
- None (N): No user interaction
- Required (R): User action needed

Impact Metrics (C/I/A):
- None (N): No impact
- Low (L): Limited impact
- High (H): Complete loss

CVSS Score Calculation:
- 9.0-10.0: CRITICAL
- 7.0-8.9: HIGH
- 4.0-6.9: MEDIUM
- 0.1-3.9: LOW
```

### Report Templates por Severidade
```
CRITICAL Finding Template:
┌─────────────────────────────────────────────────────────────────┐
│ FINDING: [Title]                                                │
│ SEVERITY: CRITICAL (CVSS: 9.X)                                  │
│                                                                 │
│ DESCRIPTION:                                                    │
│ [Clear explanation of the vulnerability]                        │
│                                                                 │
│ BUSINESS IMPACT:                                                │
│ - Complete system compromise                                    │
│ - Full data breach potential                                    │
│ - Regulatory implications (GDPR, HIPAA, PCI-DSS)                │
│                                                                 │
│ IMMEDIATE ACTION REQUIRED:                                      │
│ 1. [Specific remediation step]                                  │
│ 2. [Specific remediation step]                                  │
│ 3. [Specific remediation step]                                  │
│                                                                 │
│ TIMELINE: Remediate within 24-48 hours                          │
└─────────────────────────────────────────────────────────────────┘

HIGH Finding Template:
┌─────────────────────────────────────────────────────────────────┐
│ FINDING: [Title]                                                │
│ SEVERITY: HIGH (CVSS: 7.X-8.X)                                  │
│                                                                 │
│ DESCRIPTION:                                                    │
│ [Clear explanation of the vulnerability]                        │
│                                                                 │
│ BUSINESS IMPACT:                                                │
│ - Significant data exposure                                     │
│ - Privilege escalation possible                                 │
│                                                                 │
│ RECOMMENDED ACTION:                                             │
│ 1. [Specific remediation step]                                  │
│ 2. [Specific remediation step]                                  │
│                                                                 │
│ TIMELINE: Remediate within 7 days                               │
└─────────────────────────────────────────────────────────────────┘
```

---

## 15. Responsible Disclosure com bug-bounty-hunter Agent

### Disclosure Timeline (bug-bounty-hunter)
```
Day 0: Submit report to program
Day 1-3: Initial triage (expect confirmation)
Day 7-14: Validation by security team
Day 30-90: Fix development and testing
Day 90+: Public disclosure (if agreed)
```

### Communication Best Practices
```
DO:
✅ Be patient - security teams are often busy
✅ Be responsive - answer questions quickly
✅ Be collaborative - help validate fixes
✅ Be professional - maintain good relationships
✅ Follow program policies and scope

DON'T:
❌ Send constant status requests
❌ Share vulnerability publicly before fix
❌ Be rude or demanding
❌ Threaten to disclose
❌ Submit duplicate reports
```

### Report Quality Checklist (bug-bounty-hunter)
```
Before Submitting:
□ Tested thoroughly
□ Clear reproduction steps
□ Proper security terminology
□ Remediation suggestions included
□ Professional tone
□ All relevant evidence attached
□ Checked for duplicates
□ Within scope

Report Structure:
□ Title: Clear and concise
□ Severity: Appropriate (CVSS if possible)
□ Description: What, where, how
□ Steps to Reproduce: Numbered, detailed
□ Impact: Business risk explained
□ Proof of Concept: Working payload
□ Remediation: Specific fix suggestions
```

### Bounty Report Template
```
TITLE: [Vulnerability Type] in [Component] Allows [Impact]

SEVERITY: [Critical/High/Medium/Low]
CVSS: [Score if applicable]

SUMMARY:
[2-3 sentence overview of the vulnerability]

DESCRIPTION:
[Detailed explanation of the vulnerability]

STEPS TO REPRODUCE:
1. Go to [URL/endpoint]
2. [Action]
3. [Action]
4. Observe: [Result]

PROOF OF CONCEPT:
[Payload, screenshot, or video]

IMPACT:
[Explain business risk - data breach, account takeover, etc.]

REMEDIATION:
[Specific fix suggestions]

REFERENCES:
- [Relevant CVEs]
- [OWASP links]
- [Vendor documentation]
```

### Platform-Specific Guidance
```
HackerOne:
- Use H1 report template
- Include CVSS calculation
- Follow program-specific guidelines

Bugcrowd:
- Use Bugcrowd Vulnerability Rating Taxonomy
- Include priority score justification
- Follow VRT severity levels

Intigriti/YesWeHack:
- European programs - GDPR considerations
- Clear business impact explanation
```

---

## 16. Entrega do Relatório

### Formatos de Entrega
- [ ] PDF (formato principal para distribuição)
- [ ] HTML (versão interativa)
- [ ] JSON (para integração com SIEM/ticketing)
- [ ] CSV (para tracking em planilhas)

### Distribuição
- [ ] Enviar para stakeholders principais
- [ ] Armazenar em local seguro (encrypted)
- [ ] Definir data de destruição do relatório
- [ ] Registrar recipients do relatório

### Follow-up
- [ ] Agendar meeting de review
- [ ] Estabelecer timeline de remediation
- [ ] Oferecer re-test após correções
- [ ] Documentar lessons learned

---

## Output Esperado desta Fase
1. Relatório executivo completo (PDF/HTML)
2. Dados estruturados de findings (JSON/CSV)
3. Attack paths documentados com evidências
4. Recomendações priorizadas de remediation
5. Apresentação para stakeholders

## Fim do Processo PTES
Após completar esta fase, o penetration test está completo.

---

## Referências PTES
- **PTES Section 6**: Reporting
- **PTES 6.1**: Executive-Level Reporting
- **PTES 6.2**: Technical Reporting
- **PTES 6.3**: Quantifying the Risk
- **PTES 6.4**: Deliverable

## Ver Também

- `/pentest-network-scanning` - Section 14: OWASP Nettacker Integration (Network Scanning)
- `/pentest-vulnerability-analysis` - Section 7: OWASP Nettacker Vulnerability Scanning (CVE Detection)
- `/pentest-intelligence-gathering` - Section 9: OWASP Nettacker for Intelligence Gathering (Recon)
- `/pentest-pfsense` - Section 4.28: OWASP Nettacker for pfSense (Specialized Scanning)

---

## 🤖 AIRecon Integration for Reporting

> **NOTE:** AIRecon can automate report generation, consolidate findings from multiple tools, and export in multiple formats.

### AIRecon Invocation for Reporting

```bash
# Generate consolidated pentest report from all findings
airecon "generate pentest report from nettacker and worstassume findings"

# Export findings in specific format
airecon "export vulnerability findings to JSON for SIEM integration"

# Create executive summary from technical findings
airecon "create executive summary from pentest findings for management"

# Generate DefectDojo compatible report
airecon "export findings to DefectDojo format for vulnerability management"
```

### Slash Command Integration

```bash
# Export API keys found during assessment for report
/ai airecon "/api-keys --export json > report-api-keys.json"

# Export webshell detection results for post-exploitation section
/ai airecon "/webshell-detect --export json > report-webshells.json"

# Generate wordlist usage statistics for methodology section
/ai airecon "/wordlist --stats --export markdown > report-wordlist-stats.md"

…(truncated)
