---
name: mitre_attack_mapping
phase: 6_reporting
tools: [python3, markdown]
dependencies: [critical_vuln_found]
mitre_tactic: N/A (Meta-skill para mapeamento)
---

# Objetivo
Mapear todas as vulnerabilidades, técnicas e táticas utilizadas durante o pentest para o framework MITRE ATT&CK Enterprise, gerando tanto uma tabela Markdown para o relatório quanto um JSON compatível com o ATT&CK Navigator para visualização interativa.

# Condições de Execução
- O pentest foi concluído (ou parcialmente concluído) com vulnerabilidades registradas.
- O Knowledge Graph ou arquivos de resultados contêm os achados.

# Comandos e Sintaxe

## 1. Gerar Mapeamento Automático via Python
```bash
cat << 'PYEOF' > {workspace}/generate_mitre.py
import json
import os
import sys

# Mapeamento abrangente: Tipo de Achado → MITRE ATT&CK
MITRE_MAP = {
    # Reconhecimento
    "subdomain_enumeration": {"tactic": "TA0043", "tactic_name": "Reconnaissance", "technique": "T1596.002", "technique_name": "Search Open Technical Databases: DNS/Passive DNS"},
    "email_harvesting": {"tactic": "TA0043", "tactic_name": "Reconnaissance", "technique": "T1589.002", "technique_name": "Gather Victim Identity: Email Addresses"},
    "tech_fingerprinting": {"tactic": "TA0043", "tactic_name": "Reconnaissance", "technique": "T1592.004", "technique_name": "Gather Victim Host Info: Software"},
    # Initial Access
    "sql_injection": {"tactic": "TA0001", "tactic_name": "Initial Access", "technique": "T1190", "technique_name": "Exploit Public-Facing Application"},
    "file_upload_rce": {"tactic": "TA0001", "tactic_name": "Initial Access", "technique": "T1190", "technique_name": "Exploit Public-Facing Application"},
    "default_credentials": {"tactic": "TA0001", "tactic_name": "Initial Access", "technique": "T1078.001", "technique_name": "Valid Accounts: Default Accounts"},
    "phishing_creds": {"tactic": "TA0001", "tactic_name": "Initial Access", "technique": "T1566", "technique_name": "Phishing"},
    # Execution
    "command_injection": {"tactic": "TA0002", "tactic_name": "Execution", "technique": "T1059", "technique_name": "Command and Scripting Interpreter"},
    "webshell": {"tactic": "TA0002", "tactic_name": "Execution", "technique": "T1059.004", "technique_name": "Unix Shell"},
    "metasploit_exploit": {"tactic": "TA0002", "tactic_name": "Execution", "technique": "T1203", "technique_name": "Exploitation for Client Execution"},
    # Persistence
    "webshell_persistence": {"tactic": "TA0003", "tactic_name": "Persistence", "technique": "T1505.003", "technique_name": "Server Software Component: Web Shell"},
    "ssh_key_persistence": {"tactic": "TA0003", "tactic_name": "Persistence", "technique": "T1098.004", "technique_name": "Account Manipulation: SSH Authorized Keys"},
    # Privilege Escalation
    "suid_exploit": {"tactic": "TA0004", "tactic_name": "Privilege Escalation", "technique": "T1548.001", "technique_name": "Abuse Elevation: Setuid and Setgid"},
    "sudo_misconfig": {"tactic": "TA0004", "tactic_name": "Privilege Escalation", "technique": "T1548.003", "technique_name": "Abuse Elevation: Sudo and Sudo Caching"},
    "kernel_exploit": {"tactic": "TA0004", "tactic_name": "Privilege Escalation", "technique": "T1068", "technique_name": "Exploitation for Privilege Escalation"},
    "token_impersonation": {"tactic": "TA0004", "tactic_name": "Privilege Escalation", "technique": "T1134.001", "technique_name": "Access Token Manipulation: Token Impersonation"},
    # Credential Access
    "brute_force": {"tactic": "TA0006", "tactic_name": "Credential Access", "technique": "T1110", "technique_name": "Brute Force"},
    "password_spray": {"tactic": "TA0006", "tactic_name": "Credential Access", "technique": "T1110.003", "technique_name": "Brute Force: Password Spraying"},
    "hash_dump": {"tactic": "TA0006", "tactic_name": "Credential Access", "technique": "T1003", "technique_name": "OS Credential Dumping"},
    "ntds_dump": {"tactic": "TA0006", "tactic_name": "Credential Access", "technique": "T1003.003", "technique_name": "OS Credential Dumping: NTDS"},
    "mimikatz": {"tactic": "TA0006", "tactic_name": "Credential Access", "technique": "T1003.001", "technique_name": "OS Credential Dumping: LSASS Memory"},
    # Lateral Movement
    "pass_the_hash": {"tactic": "TA0008", "tactic_name": "Lateral Movement", "technique": "T1550.002", "technique_name": "Use Alternate Auth: Pass the Hash"},
    "psexec": {"tactic": "TA0008", "tactic_name": "Lateral Movement", "technique": "T1569.002", "technique_name": "System Services: Service Execution"},
    "wmi_exec": {"tactic": "TA0008", "tactic_name": "Lateral Movement", "technique": "T1047", "technique_name": "Windows Management Instrumentation"},
    "ssh_lateral": {"tactic": "TA0008", "tactic_name": "Lateral Movement", "technique": "T1021.004", "technique_name": "Remote Services: SSH"},
    # Discovery
    "port_scan": {"tactic": "TA0007", "tactic_name": "Discovery", "technique": "T1046", "technique_name": "Network Service Discovery"},
    "directory_discovery": {"tactic": "TA0007", "tactic_name": "Discovery", "technique": "T1083", "technique_name": "File and Directory Discovery"},
    "smb_enumeration": {"tactic": "TA0007", "tactic_name": "Discovery", "technique": "T1135", "technique_name": "Network Share Discovery"},
}

# Carregar achados do engagement (JSON)
findings_file = "{workspace}/engagement_state.json"
findings = []
if os.path.exists(findings_file):
    with open(findings_file) as f:
        state = json.load(f)
        for vuln in state.get("discovered_vulns", []):
            findings.append(vuln)
        for cred in state.get("discovered_creds", []):
            findings.append({"type": "brute_force", "name": f"Credential: {cred.get('username', '')}"})

# Gerar tabela Markdown
print("# MITRE ATT&CK Mapping\n")
print("| Tática | ID Tática | Técnica | ID Técnica | Achado |")
print("|--------|-----------|---------|------------|--------|")

used_techniques = []
for key, mapping in MITRE_MAP.items():
    print(f"| {mapping['tactic_name']} | {mapping['tactic']} | "
          f"{mapping['technique_name']} | {mapping['technique']} | "
          f"{key.replace('_', ' ').title()} |")
    used_techniques.append({
        "techniqueID": mapping["technique"],
        "tactic": mapping["tactic_name"].lower().replace(" ", "-"),
        "color": "#ff6666" if "exploit" in key or "rce" in key or "injection" in key else "#ffcc66",
        "comment": f"MundiX finding: {key}",
        "enabled": True,
    })

# Gerar JSON para ATT&CK Navigator
navigator = {
    "name": "MundiX Pentest - {target_domain}",
    "versions": {"attack": "14", "navigator": "4.9.1", "layer": "4.5"},
    "domain": "enterprise-attack",
    "description": "Automated MITRE mapping from MundiX pentesting agent",
    "techniques": used_techniques,
    "gradient": {"colors": ["#ffffff", "#ff6666"], "minValue": 0, "maxValue": 1},
}

with open("{workspace}/mitre_navigator.json", "w") as f:
    json.dump(navigator, f, indent=2)

print(f"\nNavigator JSON salvo em: {workspace}/mitre_navigator.json")
print(f"Total de técnicas mapeadas: {len(used_techniques)}")
PYEOF

python3 {workspace}/generate_mitre.py 2>&1 | tee {workspace}/mitre_table.md
```

## 2. Gerar Resumo por Tática
```bash
cat << 'PYEOF' > {workspace}/mitre_summary.py
import json

with open("{workspace}/mitre_navigator.json") as f:
    data = json.load(f)

tactics = {}
for t in data["techniques"]:
    tactic = t.get("tactic", "unknown")
    tactics.setdefault(tactic, []).append(t["techniqueID"])

print("## Resumo por Tática MITRE ATT&CK\n")
for tactic, techniques in sorted(tactics.items()):
    print(f"- **{tactic.replace('-', ' ').title()}**: {len(techniques)} técnicas ({', '.join(set(techniques))})")
PYEOF

python3 {workspace}/mitre_summary.py 2>&1 | tee -a {workspace}/mitre_table.md
```

## 3. Validar Cobertura da Kill Chain
```bash
echo "--- Kill Chain Coverage ---" | tee {workspace}/mitre_coverage.txt
for phase in "reconnaissance" "initial-access" "execution" "persistence" "privilege-escalation" "credential-access" "lateral-movement" "discovery"; do
  count=$(grep -c "$phase" {workspace}/mitre_navigator.json 2>/dev/null || echo 0)
  echo "$phase: $count techniques" | tee -a {workspace}/mitre_coverage.txt
done
```

# Análise de Resultados

## Cobertura Completa
- Se todas as fases da kill chain estão representadas (Recon → Initial Access → Execution → Privilege Escalation → Lateral Movement), o pentest cobriu um ciclo completo de ataque.
- Isso demonstra impacto real para o cliente.

## Lacunas na Kill Chain
- Se pulou direto de Initial Access para Privilege Escalation, revise se há técnicas intermediárias não documentadas.
- Lacunas podem indicar defesas efetivas do cliente (bom para o relatório).

## Técnicas Críticas
- T1190 (Exploit Public-Facing Application): vulnerabilidade web explorada.
- T1003 (Credential Dumping): credenciais extraídas da memória.
- T1550.002 (Pass the Hash): movimento lateral sem senha em texto claro.
- Estas técnicas devem ser destacadas no relatório executivo.

# Próximos Passos
- Insira a tabela MITRE na seção de mapeamento do relatório final (`generate_pentest_report`).
- Entregue o arquivo `mitre_navigator.json` como anexo — o cliente pode importar no ATT&CK Navigator.
- Use o resumo por tática no `executive_summary`.

# Tratamento de Erros
- **engagement_state.json não encontrado:** O script usa o mapeamento estático. O agente deve alimentar achados manualmente.
- **Python3 não instalado:** `apt-get install -y python3`.
- **Técnica não mapeada:** Se um achado não tem correspondência direta, mapeie para a tática mais próxima com nota explicativa.
- **ATT&CK Navigator versão:** O JSON gerado é compatível com Navigator v4.5+.
