# WAN

Uma **WAN (Wide Area Network)** é uma rede de telecomunicações que se estende por uma grande área geográfica, conectando múltiplas LANs (Local Area Networks) entre si. Diferente das LANs, as WANs geralmente utilizam infraestrutura de operadoras de telecomunicações, como linhas alugadas, fibra óptica, satélites ou redes celulares.

### **Características Principais**

```yaml
Características das WANs:
  ✅ Cobertura geográfica extensa (cidades, países, continentes)
  ✅ Conexão de múltiplas LANs e sites remotos
  ✅ Utilização de infraestrutura de operadoras
  ✅ Suporte a altas velocidades (1 Mbps a 100 Gbps+)
  ✅ Alta latência comparada a LANs (10-200ms)
  ✅ Maior custo de implementação e operação
  
Diferenças para LAN:
  ❌ Velocidade geralmente menor que LAN
  ❌ Latência significativamente maior
  ❌ Maior taxa de erro de bits (BER)
  ❌ Dependência de provedores de serviço
  ❌ Complexidade de troubleshooting
```

### **Comparação com Outros Tipos de Rede**

| Tipo         | Alcance   | Velocidade          | Propriedade | Latência | Custo |
| ------------ | --------- | ------------------- | ----------- | -------- | ----- |
| **LAN**      | Até 2 km  | 100 Mbps - 100 Gbps | Privada     | <1ms     | Baixo |
| **MAN**      | 2 - 50 km | 1 - 100 Gbps        | Mista       | 1-5ms    | Médio |
| **WAN**      | > 50 km   | 1 Mbps - 100 Gbps   | Operadora   | 10-200ms | Alto  |
| **SD-WAN**   | Global    | 1 Mbps - 10 Gbps    | Híbrida     | Variável | Médio |
| **Internet** | Global    | Variável            | Pública     | 20-500ms | Baixo |

### **Componentes de uma WAN**

```mermaid
graph TD
    subgraph "Site A (Matriz)"
        A1[LAN Matriz]
        A2[Router Edge]
        A3[CE Router]
    end
    
    subgraph "Provedor de Serviço"
        P1[PE Router]
        P2[P Router]
        P3[PE Router]
    end
    
    subgraph "Site B (Filial)"
        B1[LAN Filial]
        B2[Router Edge]
        B3[CE Router]
    end
    
    A1 --- A2
    A2 --- A3
    A3 --- P1
    P1 --- P2
    P2 --- P3
    P3 --- B3
    B3 --- B2
    B2 --- B1
```

***

## 🏗️ **Arquitetura e Topologias**

### **Topologias WAN Comuns**

```mermaid
graph TD
    subgraph "Ponto a Ponto"
        P1[Site A] --- P2[Site B]
    end
    
    subgraph "Hub-and-Spoke"
        H1[Hub] --- H2[Spoke 1]
        H1 --- H3[Spoke 2]
        H1 --- H4[Spoke 3]
    end
    
    subgraph "Full Mesh"
        M1[Site A] --- M2[Site B]
        M1 --- M3[Site C]
        M2 --- M3
    end
    
    subgraph "Parital Mesh"
        PM1[Site A] --- PM2[Site B]
        PM1 --- PM3[Site C]
        PM2 --- PM4[Site D]
    end
```

### **Comparação de Topologias WAN**

| Topologia         | Vantagens                         | Desvantagens          | Uso Típico                   |
| ----------------- | --------------------------------- | --------------------- | ---------------------------- |
| **Ponto a Ponto** | Simples, baixo custo              | Não escalável         | Conexão entre 2 sites        |
| **Hub-and-Spoke** | Centralizado, fácil gerenciamento | Ponto único de falha  | Filiais conectadas à matriz  |
| **Full Mesh**     | Alta redundância, baixa latência  | Alto custo, complexa  | Redes críticas, data centers |
| **Partial Mesh**  | Balanceamento custo/benefício     | Configuração complexa | Empresas médias/grandes      |
| **Dual-Homed**    | Redundância de conectividade      | Custo adicional       | Sites críticos               |

***

## 📡 **Tecnologias WAN**

### **Tecnologias de Camada Física**

| Tecnologia       | Velocidade          | Alcance  | Meio    | Uso            |
| ---------------- | ------------------- | -------- | ------- | -------------- |
| **T1/E1**        | 1.544/2.048 Mbps    | Até 1 km | Cobre   | Legado, backup |
| **T3/E3**        | 45/34 Mbps          | Até 1 km | Cobre   | Legado         |
| **SONET/SDH**    | 155 Mbps - 100 Gbps | 100+ km  | Fibra   | Operadoras     |
| **Ethernet WAN** | 1 Gbps - 100 Gbps   | 40-80 km | Fibra   | Corporativo    |
| **DWDM**         | 100 Gbps - Tbps     | 1000+ km | Fibra   | Operadoras     |
| **Satélite**     | 50-500 Mbps         | Global   | RF      | Áreas remotas  |
| **5G/LTE**       | 100 Mbps - 10 Gbps  | 10-50 km | RF      | Backup, IoT    |
| **MPLS**         | 10 Mbps - 10 Gbps   | Nacional | Variado | Corporativo    |

### **Circuitos WAN Tradicionais**

```python
#!/usr/bin/env python3
# wan_circuits.py

class WANCircuit:
    """Representação de circuitos WAN"""
    
    def __init__(self, circuit_id, bandwidth, latency):
        self.circuit_id = circuit_id
        self.bandwidth = bandwidth
        self.latency = latency
        self.availability = 99.999
        self.status = "UP"
    
    def calculate_sla(self):
        """Calcular SLA"""
        downtime_per_year = (1 - self.availability/100) * 365 * 24 * 60
        return f"{downtime_per_year:.2f} minutos/ano"

class T1Circuit(WANCircuit):
    """Circuito T1 (1.544 Mbps)"""
    def __init__(self, circuit_id):
        super().__init__(circuit_id, 1.544, 10)
        self.framing = "ESF"
        self.line_coding = "B8ZS"

class T3Circuit(WANCircuit):
    """Circuito T3 (45 Mbps)"""
    def __init__(self, circuit_id):
        super().__init__(circuit_id, 45, 8)
        self.framing = "C-BIT"
        self.scrambling = True

class OC3Circuit(WANCircuit):
    """Circuito OC-3 (155 Mbps)"""
    def __init__(self, circuit_id):
        super().__init__(circuit_id, 155, 5)
        self.sts_3c = True
        self.path_verification = True

class EthernetWAN(WANCircuit):
    """Ethernet WAN (1 Gbps - 100 Gbps)"""
    def __init__(self, circuit_id, bandwidth):
        super().__init__(circuit_id, bandwidth, 2)
        self.auto_negotiation = True
        self.flow_control = True

# Exemplo
t1 = T1Circuit("CKT-001")
print(f"T1: {t1.bandwidth} Mbps, Latência: {t1.latency}ms")
print(f"SLA: {t1.calculate_sla()}")

ethernet = EthernetWAN("CKT-002", 10000)
print(f"Ethernet WAN: {ethernet.bandwidth/1000} Gbps")
```

***

## 🔌 **Protocolos WAN**

### **Protocolos de Camada 2 WAN**

| Protocolo       | Descrição                     | Características              | Uso                          |
| --------------- | ----------------------------- | ---------------------------- | ---------------------------- |
| **HDLC**        | High-Level Data Link Control  | Cisco proprietário           | Serial point-to-point        |
| **PPP**         | Point-to-Point Protocol       | Autenticação, multilink      | Dial-up, serial              |
| **Frame Relay** | Frame switching               | VC, CIR, PVC                 | Legado, substituído por MPLS |
| **ATM**         | Asynchronous Transfer Mode    | Células 53 bytes, QoS        | Legado, operadoras           |
| **Ethernet**    | IEEE 802.3                    | Alta velocidade, baixo custo | Metro Ethernet               |
| **MPLS**        | Multiprotocol Label Switching | Labels, VPN, TE              | Corporativo, operadoras      |

### **PPP (Point-to-Point Protocol)**

```python
#!/usr/bin/env python3
# ppp_config.py

class PPPConfiguration:
    """Configuração do protocolo PPP"""
    
    def __init__(self):
        self.lcp_options = {
            'MRU': 1500,           # Maximum Receive Unit
            'ACCM': 0,             # Async Control Character Map
            'Auth': 'PAP',         # Authentication protocol
            'MagicNumber': True,   # Magic number for loopback detection
            'PFC': False,          # Protocol Field Compression
            'ACFC': False          # Address/Control Field Compression
        }
        
        self.ipcp_options = {
            'IP': 'negotiate',
            'DNS': 'negotiate',
            'WINS': 'negotiate'
        }
    
    def configure_authentication(self, protocol, username, password):
        """Configurar autenticação PPP"""
        self.lcp_options['Auth'] = protocol
        self.auth_username = username
        self.auth_password = password
        print(f"[+] Autenticação PPP configurada: {protocol}")
    
    def configure_multilink(self, max_links=2):
        """Configurar Multilink PPP"""
        self.multilink = True
        self.max_links = max_links
        print(f"[+] Multilink PPP configurado (max {max_links} links)")
    
    def show_config(self):
        """Exibir configuração PPP"""
        print("\n=== PPP Configuration ===")
        print(f"LCP Options: {self.lcp_options}")
        print(f"IPCP Options: {self.ipcp_options}")
        if hasattr(self, 'multilink'):
            print(f"Multilink: Enabled (Max {self.max_links} links)")
        if hasattr(self, 'auth_username'):
            print(f"Auth: {self.auth_username}")

# Exemplo
ppp = PPPConfiguration()
ppp.configure_authentication('CHAP', 'router', 'SecurePass123')
ppp.configure_multilink(2)
ppp.show_config()
```

### **MPLS (Multiprotocol Label Switching)**

```python
#!/usr/bin/env python3
# mpls_vpn.py

class MPLS_LSR:
    """Label Switch Router MPLS"""
    
    def __init__(self, name):
        self.name = name
        self.lfib = {}  # Label Forwarding Information Base
        self.fec_map = {}  # FEC to label mapping
    
    def add_label(self, incoming_label, outgoing_label, next_hop):
        """Adicionar entrada na LFIB"""
        self.lfib[incoming_label] = {
            'out_label': outgoing_label,
            'next_hop': next_hop
        }
        print(f"[+] Label {incoming_label} -> {outgoing_label} via {next_hop}")
    
    def add_route(self, prefix, label, next_hop):
        """Adicionar rota com label"""
        self.fec_map[prefix] = {
            'label': label,
            'next_hop': next_hop
        }
        print(f"[+] FEC {prefix} -> Label {label} via {next_hop}")

class MPLS_VPN:
    """VPN sobre MPLS (RFC 4364)"""
    
    def __init__(self, vrf_name, rd, rt):
        self.vrf_name = vrf_name
        self.rd = rd  # Route Distinguisher
        self.rt = rt  # Route Target
        self.routes = {}
        self.interfaces = []
    
    def add_interface(self, interface, ip_address):
        """Adicionar interface à VRF"""
        self.interfaces.append({
            'interface': interface,
            'ip': ip_address,
            'vrf': self.vrf_name
        })
        print(f"[+] Interface {interface} adicionada à VRF {self.vrf_name}")
    
    def add_route(self, prefix, next_hop, label):
        """Adicionar rota VPN"""
        self.routes[prefix] = {
            'next_hop': next_hop,
            'label': label,
            'vpn_label': self.generate_vpn_label()
        }
        print(f"[+] Rota VPN {prefix} via {next_hop} (Label: {label})")
    
    def generate_vpn_label(self):
        """Gerar label VPN (16-1048575)"""
        import random
        return random.randint(16, 1048575)
    
    def show_vrf(self):
        """Exibir informações da VRF"""
        print(f"\n=== VRF: {self.vrf_name} ===")
        print(f"RD: {self.rd}")
        print(f"RT: {self.rt}")
        print(f"Interfaces: {[i['interface'] for i in self.interfaces]}")
        print(f"Routes: {len(self.routes)}")

# Exemplo
pe1 = MPLS_LSR("PE1")
pe2 = MPLS_LSR("PE2")

# Configurar labels
pe1.add_label(100, 200, "192.168.1.2")
pe2.add_label(200, 100, "192.168.1.1")

# Configurar VPN
vpn_customer = MPLS_VPN("VRF_Customer_A", "65000:1", "65000:1")
vpn_customer.add_interface("GigabitEthernet0/1", "10.1.1.1/24")
vpn_customer.add_route("192.168.100.0/24", "10.1.1.2", 100)
vpn_customer.show_vrf()
```

### **SD-WAN (Software-Defined WAN)**

```python
#!/usr/bin/env python3
# sdwan.py

class SDWANController:
    """Controlador SD-WAN"""
    
    def __init__(self, name):
        self.name = name
        self.edges = {}
        self.policies = []
        self.overlay_network = {}
    
    def add_edge(self, edge_id, site, public_ip, private_ip):
        """Adicionar edge device (router/firewall)"""
        self.edges[edge_id] = {
            'site': site,
            'public_ip': public_ip,
            'private_ip': private_ip,
            'status': 'online',
            'links': []
        }
        print(f"[+] Edge {edge_id} adicionado em {site}")
    
    def add_transport(self, edge_id, transport_type, bandwidth, priority):
        """Adicionar transporte (MPLS, Broadband, LTE)"""
        if edge_id in self.edges:
            self.edges[edge_id]['links'].append({
                'type': transport_type,
                'bandwidth': bandwidth,
                'priority': priority,
                'status': 'up'
            })
            print(f"[+] Transporte {transport_type} adicionado em {edge_id}")
    
    def add_policy(self, name, match, action):
        """Adicionar política de tráfego"""
        self.policies.append({
            'name': name,
            'match': match,
            'action': action
        })
        print(f"[+] Política '{name}' adicionada")
    
    def create_tunnel(self, edge1, edge2, encryption='IPsec'):
        """Criar túnel entre edges"""
        tunnel_id = f"{edge1}-{edge2}"
        self.overlay_network[tunnel_id] = {
            'source': edge1,
            'destination': edge2,
            'encryption': encryption,
            'status': 'established'
        }
        print(f"[+] Túnel {encryption} criado entre {edge1} e {edge2}")
    
    def show_topology(self):
        """Exibir topologia SD-WAN"""
        print(f"\n=== SD-WAN Topology: {self.name} ===\n")
        
        for edge_id, edge in self.edges.items():
            print(f"Edge: {edge_id} ({edge['site']})")
            print(f"  Public IP: {edge['public_ip']}")
            print(f"  Private IP: {edge['private_ip']}")
            print(f"  Links:")
            for link in edge['links']:
                print(f"    - {link['type']}: {link['bandwidth']} Mbps (Priority {link['priority']})")
            print()

# Exemplo
controller = SDWANController("Main-SDWAN-Controller")

# Adicionar edges
controller.add_edge("BR-01", "São Paulo", "200.100.50.10", "10.0.0.1")
controller.add_edge("BR-02", "Rio de Janeiro", "200.100.50.20", "10.0.1.1")
controller.add_edge("BR-03", "Belo Horizonte", "200.100.50.30", "10.0.2.1")

# Adicionar transportes
controller.add_transport("BR-01", "MPLS", 100, 1)
controller.add_transport("BR-01", "Broadband", 500, 2)
controller.add_transport("BR-01", "LTE", 50, 3)

# Adicionar políticas
controller.add_policy("Voice", {"protocol": "UDP", "port": 5060}, {"path": "MPLS"})
controller.add_policy("Critical", {"dscp": "EF"}, {"priority": "high"})

# Criar túneis
controller.create_tunnel("BR-01", "BR-02", "IPsec")
controller.create_tunnel("BR-01", "BR-03", "IPsec")

controller.show_topology()
```

***

## 🔒 **Segurança em WAN**

### **Ameaças Comuns em WAN**

```mermaid
graph TD
    A[Ameaças em WAN] --> B[Eavesdropping]
    A --> C[Man-in-the-Middle]
    A --> D[DDoS]
    A --> E[BGP Hijacking]
    A --> F[MPLS Label Spoofing]
    A --> G[VPN Vulnerabilities]
    
    B --> B1[Sniffing de tráfego]
    C --> C1[Interceptação de dados]
    D --> D1[Negação de serviço]
    E --> E1[Redirecionamento de tráfego]
    F --> F1[Escalonamento entre VPNs]
    G --> G1[Falhas de criptografia]
```

### **Configurações de Segurança WAN**

```cisco
! Configurações de segurança para WAN (Cisco IOS)

! 1. Autenticação de roteamento (BGP)
router bgp 65000
 neighbor 192.168.1.2 remote-as 65001
 neighbor 192.168.1.2 password 7 SecureBGPKey
 neighbor 192.168.1.2 ttl-security hops 1

! 2. Autenticação de roteamento (OSPF)
router ospf 1
 area 0 authentication message-digest
 interface Serial0/0/0
  ip ospf message-digest-key 1 md5 SecureOSPFKey

! 3. GRE/IPsec VPN
crypto isakmp policy 10
 encr aes 256
 authentication pre-share
 group 14
crypto isakmp key VPNKey address 0.0.0.0
crypto ipsec transform-set AES256 esp-aes 256 esp-sha-hmac
!
interface Tunnel0
 ip address 10.255.255.1 255.255.255.252
 tunnel source Serial0/0/0
 tunnel destination 200.100.50.20
 tunnel protection ipsec profile VPN-Profile

! 4. ACL para filtragem WAN
ip access-list extended WAN-IN
 permit tcp host 200.100.50.20 host 200.100.50.10 eq bgp
 permit esp host 200.100.50.20 host 200.100.50.10
 permit udp host 200.100.50.20 host 200.100.50.10 eq isakmp
 deny ip any any log

! 5. Control Plane Policing
class-map match-any BGP-TRAFFIC
 match protocol bgp
!
policy-map CONTROL-PLANE-POLICY
 class BGP-TRAFFIC
  police 1000000 conform-action transmit exceed-action drop
!
control-plane
 service-policy input CONTROL-PLANE-POLICY
```

### **VPN Site-to-Site com IPsec**

```python
#!/usr/bin/env python3
# ipsec_vpn.py

import hashlib
import hmac
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

class IPSecVPN:
    """Implementação simplificada de VPN IPsec"""
    
    def __init__(self, pre_shared_key):
        self.psk = pre_shared_key
        self.sa_in = None
        self.sa_out = None
        self.spi_in = None
        self.spi_out = None
    
    def ike_phase1(self, peer_ip):
        """Fase 1 do IKE - Autenticação e troca de chaves"""
        print(f"[*] IKE Phase 1 iniciada com {peer_ip}")
        
        # Simular Diffie-Hellman
        dh_private = os.urandom(32)
        dh_public = self.dh_generate_public(dh_private)
        
        # Autenticação com PSK
        auth_data = hmac.new(self.psk.encode(), dh_public, hashlib.sha256).digest()
        
        print(f"[+] IKE Phase 1 concluída")
        return self.derive_keys(dh_private, dh_public)
    
    def dh_generate_public(self, private_key):
        """Gerar chave pública Diffie-Hellman (simulado)"""
        # Em produção, usar biblioteca DH real
        return hashlib.sha256(private_key).digest()
    
    def derive_keys(self, private_key, peer_public):
        """Derivar chaves de criptografia"""
        shared_secret = hashlib.sha256(private_key + peer_public).digest()
        
        keys = {
            'encryption': shared_secret[:32],
            'authentication': shared_secret[32:64],
            'spi': int.from_bytes(shared_secret[:4], 'big')
        }
        
        return keys
    
    def ike_phase2(self, keys):
        """Fase 2 do IKE - Estabelecimento de SA"""
        print("[*] IKE Phase 2 - Estabelecendo SA")
        
        self.spi_out = keys['spi']
        self.spi_in = keys['spi'] + 1
        
        self.sa_out = {
            'encryption': keys['encryption'],
            'auth': keys['authentication'],
            'spi': self.spi_out
        }
        
        self.sa_in = {
            'encryption': keys['encryption'],
            'auth': keys['authentication'],
            'spi': self.spi_in
        }
        
        print(f"[+] SA estabelecidas (SPI Out: {self.spi_out}, SPI In: {self.spi_in})")
        return True
    
    def encrypt_packet(self, data):
        """Criptografar pacote para transmissão"""
        if not self.sa_out:
            raise Exception("VPN não estabelecida")
        
        # AES-GCM para criptografia e autenticação
        iv = os.urandom(12)
        cipher = Cipher(algorithms.AES(self.sa_out['encryption']), modes.GCM(iv))
        encryptor = cipher.encryptor()
        
        ciphertext = encryptor.update(data) + encryptor.finalize()
        
        # Adicionar ESP header
        esp_packet = self.spi_out.to_bytes(4, 'big') + iv + ciphertext + encryptor.tag
        
        return esp_packet
    
    def decrypt_packet(self, esp_packet):
        """Descriptografar pacote recebido"""
        if not self.sa_in:
            raise Exception("VPN não estabelecida")
        
        spi = int.from_bytes(esp_packet[:4], 'big')
        
        if spi != self.sa_in['spi']:
            raise Exception(f"SPI inválido: {spi}")
        
        iv = esp_packet[4:16]
        ciphertext = esp_packet[16:-16]
        tag = esp_packet[-16:]
        
        cipher = Cipher(algorithms.AES(self.sa_in['encryption']), modes.GCM(iv, tag))
        decryptor = cipher.decryptor()
        
        plaintext = decryptor.update(ciphertext) + decryptor.finalize()
        return plaintext
    
    def establish(self, peer_ip):
        """Estabelecer VPN completa"""
        keys = self.ike_phase1(peer_ip)
        return self.ike_phase2(keys)

# Exemplo
vpn = IPSecVPN("SecurePreSharedKey")
vpn.establish("200.100.50.20")

# Simular envio de pacote
packet = b"Hello, this is secure traffic!"
encrypted = vpn.encrypt_packet(packet)
decrypted = vpn.decrypt_packet(encrypted)
print(f"Original: {packet}")
print(f"Decrypted: {decrypted}")
```

***

## 🎯 **Pentesting em WAN**

### **Metodologia de Teste WAN**

```mermaid
sequenceDiagram
    participant T as Testador
    participant W as WAN
    participant P as Provedor
    participant D as Destino

    T->>W: 1. Descoberta de topologia
    T->>W: 2. Mapeamento de circuitos
    T->>W: 3. Análise de rotas BGP
    T->>W: 4. Teste de VPN
    T->>W: 5. Teste de resiliência
    T->>D: 6. Análise de latência/packet loss
    T->>P: 7. Verificação de configurações
    T->>W: 8. Documentação
```

### **Ferramentas de Pentest WAN**

```bash
# 1. Análise de rotas BGP
whois -h whois.radb.net 200.100.50.0/24
bgpq3 -4 AS65000
nmap --script bgp-* -p 179 200.100.50.1

# 2. Análise de latência e rotas
mtr -n 200.100.50.20
traceroute -n 200.100.50.20
tcptraceroute -n 200.100.50.20 80

# 3. Teste de throughput
iperf3 -c 200.100.50.20 -p 5201 -t 30
nuttcp -t -i1 200.100.50.20

# 4. Análise de QoS
hping3 -S -p 80 --faster 200.100.50.20
nmap -sS -p 80 --max-rtt-timeout 100ms 200.100.50.0/24

# 5. Teste de VPN
ike-scan -M 200.100.50.20
ike-scan --pskcrack -P psk.txt 200.100.50.20

# 6. Análise de circuitos MPLS
# (requer acesso interno)
mpls-ping 192.168.1.2
traceroute -T -p 80 200.100.50.20
```

### **Script de Pentest WAN**

```python
#!/usr/bin/env python3
# wan_pentest.py

import socket
import subprocess
import time
import sys

class WANPentest:
    """Teste de segurança em WAN"""
    
    def __init__(self, target_ip):
        self.target = target_ip
        self.results = {}
    
    def trace_route(self):
        """Mapear rota para o destino"""
        print(f"[*] Mapeando rota para {self.target}")
        
        try:
            result = subprocess.run(
                ['traceroute', '-n', self.target],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            hops = []
            for line in result.stdout.split('\n'):
                if line and not line.startswith('traceroute'):
                    parts = line.split()
                    if len(parts) > 1:
                        hops.append({
                            'hop': parts[0],
                            'ip': parts[1] if parts[1] != '*' else None
                        })
            
            self.results['route'] = hops
            print(f"[+] {len(hops)} hops encontrados")
            return hops
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def measure_latency(self, count=10):
        """Medir latência para o destino"""
        print(f"[*] Medindo latência para {self.target}")
        
        latencies = []
        packet_loss = 0
        
        for i in range(count):
            start = time.time()
            response = subprocess.run(
                ['ping', '-c', '1', '-W', '2', self.target],
                capture_output=True,
                text=True
            )
            elapsed = (time.time() - start) * 1000
            
            if response.returncode == 0:
                latencies.append(elapsed)
                print(f"  Ping {i+1}: {elapsed:.2f}ms")
            else:
                packet_loss += 1
                print(f"  Ping {i+1}: Timeout")
        
        if latencies:
            avg_latency = sum(latencies) / len(latencies)
            min_latency = min(latencies)
            max_latency = max(latencies)
        else:
            avg_latency = min_latency = max_latency = 0
        
        self.results['latency'] = {
            'min': min_latency,
            'max': max_latency,
            'avg': avg_latency,
            'loss': (packet_loss / count) * 100
        }
        
        print(f"\n[+] Latência média: {avg_latency:.2f}ms")
        print(f"[+] Packet loss: {self.results['latency']['loss']:.1f}%")
        
        return self.results['latency']
    
    def test_bandwidth(self, duration=10):
        """Testar largura de banda (simulado)"""
        print(f"[*] Testando largura de banda para {self.target}")
        
        # Em produção, usar iperf3
        # Simulação de throughput
        import random
        throughput = random.uniform(10, 100)
        
        self.results['bandwidth'] = {
            'throughput': throughput,
            'unit': 'Mbps'
        }
        
        print(f"[+] Throughput estimado: {throughput:.2f} Mbps")
        return self.results['bandwidth']
    
    def analyze_bgp(self, asn):
        """Analisar informações BGP"""
        print(f"[*] Analisando BGP para AS{asn}")
        
        try:
            result = subprocess.run(
                ['whois', f'-h', 'whois.radb.net', f'AS{asn}'],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            prefixes = []
            for line in result.stdout.split('\n'):
                if 'route:' in line or 'route6:' in line:
                    prefix = line.split(':')[1].strip()
                    prefixes.append(prefix)
            
            self.results['bgp'] = {
                'asn': asn,
                'prefixes': prefixes[:10]  # Limitar a 10 prefixos
            }
            
            print(f"[+] {len(prefixes)} prefixos encontrados")
            return self.results['bgp']
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return {}
    
    def test_vpn(self, port=500):
        """Testar serviços VPN"""
        print(f"[*] Verificando VPN na porta {port}")
        
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.settimeout(5)
            
            # IKE packet (ISAKMP)
            ike_packet = bytes.fromhex(
                "0000001c00000000000000000101120000000000000000"
            )
            
            sock.sendto(ike_packet, (self.target, port))
            data, addr = sock.recvfrom(1024)
            
            self.results['vpn'] = {
                'port': port,
                'responded': True,
                'vendor': self.identify_vendor(data)
            }
            
            print(f"[+] VPN detectada: {self.results['vpn']['vendor']}")
            sock.close()
            return True
            
        except socket.timeout:
            print("[-] Nenhuma resposta VPN detectada")
            return False
        except Exception as e:
            print(f"[-] Erro: {e}")
            return False
    
    def identify_vendor(self, data):
        """Identificar vendor de VPN baseado na resposta"""
        # Simplificado - em produção, analisar payload
        return "Unknown (Cisco/StrongSwan possible)"
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n=== RELATÓRIO DE PENTEST WAN ===\n")
        
        print(f"Alvo: {self.target}")
        
        if 'route' in self.results:
            print(f"\n[ROTA]")
            print(f"  Saltos: {len(self.results['route'])}")
            for hop in self.results['route'][:5]:
                if hop['ip']:
                    print(f"    Hop {hop['hop']}: {hop['ip']}")
            if len(self.results['route']) > 5:
                print(f"    ... e mais {len(self.results['route']) - 5} saltos")
        
        if 'latency' in self.results:
            l = self.results['latency']
            print(f"\n[LATÊNCIA]")
            print(f"  Mínima: {l['min']:.2f}ms")
            print(f"  Máxima: {l['max']:.2f}ms")
            print(f"  Média: {l['avg']:.2f}ms")
            print(f"  Perda: {l['loss']:.1f}%")
        
        if 'bandwidth' in self.results:
            b = self.results['bandwidth']
            print(f"\n[BANDA]")
            print(f"  Throughput: {b['throughput']:.2f} {b['unit']}")
        
        if 'vpn' in self.results:
            v = self.results['vpn']
            print(f"\n[VPN]")
            print(f"  Detectada na porta {v['port']}")
            print(f"  Vendor: {v['vendor']}")
        
        print("\n=== FIM DO RELATÓRIO ===")

# Exemplo
tester = WANPentest("200.100.50.20")
tester.trace_route()
tester.measure_latency(10)
tester.test_bandwidth()
tester.test_vpn()
tester.generate_report()
```

***

## 🔧 **Ferramentas e Diagnóstico**

### **Comandos de Diagnóstico WAN**

```bash
# Diagnóstico de conectividade
ping -c 10 -s 1400 200.100.50.20
mtr --report -c 100 200.100.50.20
pathping -n -h 30 200.100.50.20

# Análise de rota
traceroute -n -T -p 80 200.100.50.20
tcptraceroute -n 200.100.50.20 80

# Análise de QoS
hping3 -S -p 80 --faster 200.100.50.20
nmap -sS -p 80 --max-rtt-timeout 100ms 200.100.50.20

# Análise de MTU
ping -M do -s 1472 200.100.50.20
tracepath -n 200.100.50.20

# Análise de BGP
# (requer acesso a route servers)
telnet route-views.routeviews.org
show ip bgp 200.100.50.0/24
show ip bgp neighbors

# Análise de MPLS
mpls-ping 192.168.1.2
mpls-traceroute 192.168.1.2
```

### **Script de Diagnóstico Avançado**

```python
#!/usr/bin/env python3
# wan_diagnostic.py

import subprocess
import re
import sys
from datetime import datetime

class WANDiagnostic:
    """Diagnóstico avançado de WAN"""
    
    def __init__(self, destination):
        self.dest = destination
        self.start_time = datetime.now()
        self.results = {}
    
    def run_cmd(self, cmd, timeout=30):
        """Executar comando e retornar resultado"""
        try:
            result = subprocess.run(
                cmd.split(),
                capture_output=True,
                text=True,
                timeout=timeout
            )
            return result.stdout
        except Exception as e:
            return f"Erro: {e}"
    
    def analyze_route(self):
        """Analisar rota completa"""
        print("[*] Analisando rota...")
        
        trace = self.run_cmd(f"traceroute -n {self.dest}")
        
        hops = []
        for line in trace.split('\n'):
            match = re.search(r'(\d+)\s+(\d+\.\d+\.\d+\.\d+|\*)', line)
            if match:
                hops.append({
                    'hop': int(match.group(1)),
                    'ip': match.group(2) if match.group(2) != '*' else None
                })
        
        self.results['hops'] = len(hops)
        self.results['route'] = hops
        return hops
    
    def analyze_latency(self, count=20):
        """Analisar latência em detalhe"""
        print(f"[*] Analisando latência ({count} pacotes)...")
        
        ping = self.run_cmd(f"ping -c {count} {self.dest}")
        
        latencies = []
        loss = 0
        
        for line in ping.split('\n'):
            if 'time=' in line:
                match = re.search(r'time=(\d+\.?\d*)', line)
                if match:
                    latencies.append(float(match.group(1)))
            elif '100% packet loss' in line:
                loss = 100
        
        if latencies:
            self.results['latency'] = {
                'min': min(latencies),
                'max': max(latencies),
                'avg': sum(latencies) / len(latencies),
                'stddev': self.std_dev(latencies),
                'loss': loss
            }
        else:
            self.results['latency'] = {'loss': 100}
        
        return self.results['latency']
    
    def std_dev(self, values):
        """Calcular desvio padrão"""
        if not values:
            return 0
        mean = sum(values) / len(values)
        variance = sum((x - mean) ** 2 for x in values) / len(values)
        return variance ** 0.5
    
    def analyze_jitter(self):
        """Analisar jitter da conexão"""
        print("[*] Analisando jitter...")
        
        # Enviar 100 pings rápidos
        ping = self.run_cmd(f"ping -c 100 -i 0.01 {self.dest}")
        
        delays = []
        for line in ping.split('\n'):
            if 'time=' in line:
                match = re.search(r'time=(\d+\.?\d*)', line)
                if match:
                    delays.append(float(match.group(1)))
        
        if len(delays) > 1:
            jitters = [abs(delays[i+1] - delays[i]) for i in range(len(delays)-1)]
            self.results['jitter'] = {
                'avg': sum(jitters) / len(jitters),
                'max': max(jitters),
                'min': min(jitters)
            }
        
        return self.results.get('jitter', {})
    
    def analyze_mtu(self):
        """Encontrar MTU máximo"""
        print("[*] Encontrando MTU...")
        
        for size in range(1500, 1400, -10):
            result = self.run_cmd(f"ping -M do -c 1 -s {size} {self.dest}")
            if 'Frag needed' not in result and '100% packet loss' not in result:
                self.results['mtu'] = size + 28  # +28 para headers IP/ICMP
                print(f"[+] MTU máximo: {self.results['mtu']}")
                return self.results['mtu']
        
        self.results['mtu'] = 1400
        return 1400
    
    def analyze_qos(self):
        """Analisar QoS baseado em DSCP"""
        print("[*] Analisando QoS...")
        
        dscp_values = [0, 8, 10, 16, 18, 26, 34, 46]
        results = {}
        
        for dscp in dscp_values:
            # Pacotes com DSCP específico
            cmd = f"hping3 -S -p 80 --dscp {dscp} -c 10 {self.dest} 2>/dev/null | grep 'rtt'"
            result = self.run_cmd(cmd, timeout=5)
            
            match = re.search(r'avg = (\d+\.?\d*)', result)
            if match:
                results[dscp] = float(match.group(1))
        
        self.results['qos'] = results
        return results
    
    def generate_report(self):
        """Gerar relatório completo"""
        print("\n" + "="*60)
        print("RELATÓRIO DE DIAGNÓSTICO WAN")
        print("="*60)
        print(f"Destino: {self.dest}")
        print(f"Início: {self.start_time}")
        print(f"Término: {datetime.now()}")
        
        print("\n[1] ROTA")
        print(f"  Saltos totais: {self.results.get('hops', 'N/A')}")
        if 'route' in self.results:
            for hop in self.results['route'][:10]:
                if hop['ip']:
                    print(f"    {hop['hop']}: {hop['ip']}")
            if len(self.results['route']) > 10:
                print(f"    ... e mais {len(self.results['route']) - 10} saltos")
        
        print("\n[2] LATÊNCIA")
        lat = self.results.get('latency', {})
        print(f"  Mínima: {lat.get('min', 'N/A'):.2f}ms" if 'min' in lat else "  Mínima: N/A")
        print(f"  Máxima: {lat.get('max', 'N/A'):.2f}ms" if 'max' in lat else "  Máxima: N/A")
        print(f"  Média: {lat.get('avg', 'N/A'):.2f}ms" if 'avg' in lat else "  Média: N/A")
        print(f"  Desvio: {lat.get('stddev', 'N/A'):.2f}ms" if 'stddev' in lat else "  Desvio: N/A")
        print(f"  Perda: {lat.get('loss', 'N/A')}%")
        
        print("\n[3] JITTER")
        jit = self.results.get('jitter', {})
        print(f"  Médio: {jit.get('avg', 'N/A'):.2f}ms" if 'avg' in jit else "  Médio: N/A")
        print(f"  Máximo: {jit.get('max', 'N/A'):.2f}ms" if 'max' in jit else "  Máximo: N/A")
        
        print("\n[4] MTU")
        print(f"  Máximo: {self.results.get('mtu', 'N/A')} bytes")
        
        print("\n[5] QoS (DSCP)")
        qos = self.results.get('qos', {})
        if qos:
            for dscp, latency in sorted(qos.items()):
                print(f"  DSCP {dscp}: {latency:.2f}ms")
        else:
            print("  Não foi possível analisar QoS")
        
        print("\n" + "="*60)

# Exemplo
diag = WANDiagnostic("200.100.50.20")
diag.analyze_route()
diag.analyze_latency(20)
diag.analyze_jitter()
diag.analyze_mtu()
diag.analyze_qos()
diag.generate_report()
```

***

## 🛡️ **Hardening e Mitigação**

### **Checklist de Segurança para WAN**

```yaml
Hardening de Roteadores:
  - [ ] Desabilitar serviços desnecessários (CDP, HTTP server)
  - [ ] Configurar autenticação para protocolos de roteamento
  - [ ] Implementar ACLs para controle de tráfego
  - [ ] Configurar SSH em vez de Telnet
  - [ ] Habilitar logging e monitoramento
  - [ ] Configurar NTP para sincronização
  - [ ] Implementar Control Plane Policing

Segurança de VPN:
  - [ ] Usar IPsec com IKEv2 e AES-256
  - [ ] Implementar certificados digitais
  - [ ] Configurar Perfect Forward Secrecy (PFS)
  - [ ] Habilitar Dead Peer Detection (DPD)
  - [ ] Limitar tentativas de autenticação

Proteção de Circuitos:
  - [ ] Criptografar tráfego sensível
  - [ ] Implementar redundância de links
  - [ ] Monitorar circuitos para anomalias
  - [ ] Configurar QoS para tráfego crítico

Monitoramento:
  - [ ] Implementar NetFlow/IPFIX
  - [ ] Configurar SNMPv3 com autenticação
  - [ ] Monitorar latência e packet loss
  - [ ] Alertas para mudanças de rota BGP
```

### **Script de Hardening**

```bash
#!/bin/bash
# wan_hardening.sh

echo "=== Hardening de Configuração WAN ==="

# 1. Backup da configuração atual
cp /etc/network/interfaces /etc/network/interfaces.bak
cp /etc/ipsec.conf /etc/ipsec.conf.bak

# 2. Configurar sysctl para segurança
cat >> /etc/sysctl.conf << EOF
# Proteções WAN
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
EOF

sysctl -p

# 3. Configurar iptables para WAN
iptables -F
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Permitir tráfego estabelecido
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Permitir SSH (management)
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT

# Permitir IPsec
iptables -A INPUT -p udp --dport 500 -j ACCEPT
iptables -A INPUT -p udp --dport 4500 -j ACCEPT
iptables -A INPUT -p esp -j ACCEPT

# Permitir BGP (se necessário)
iptables -A INPUT -p tcp --dport 179 -s 200.100.50.0/24 -j ACCEPT

# Logging de pacotes descartados
iptables -A INPUT -j LOG --log-prefix "WAN-DROP: "

# 4. Configurar fail2ban para SSH
cat >> /etc/fail2ban/jail.local << EOF
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
EOF

systemctl restart fail2ban

echo "[+] Hardening WAN concluído"
```

***

## 📊 **Conclusão e Boas Práticas**

### **Resumo Técnico**

```yaml
WAN (Wide Area Network):
  ✅ Conectividade geograficamente distribuída
  ✅ Suporte a múltiplas tecnologias (MPLS, VPN, SD-WAN)
  ✅ Redundância e resiliência possíveis

Desafios de segurança:
  ❌ Maior superfície de ataque
  ❌ Dependência de provedores
  ❌ Latência e perda de pacotes
  ❌ Complexidade de troubleshooting

Boas Práticas:
  - Implementar VPNs para tráfego sensível
  - Redundância de circuitos e equipamentos
  - Monitoramento proativo
  - Políticas de segurança consistentes
```

### **Recomendações Finais**

{% stepper %}
{% step %}

### Para Administradores

* Implementar redundância de circuitos WAN
* Monitorar latência e packet loss continuamente
* Utilizar SD-WAN para otimização
* Manter documentação de circuitos atualizada
  {% endstep %}

{% step %}

### Para Pentesters

* Mapear topologia completa da WAN
* Testar resiliência de circuitos
* Verificar configurações de VPN
* Analisar rotas BGP
  {% endstep %}

{% step %}

### Para Arquitetos

* Projetar WAN com redundância
* Considerar SD-WAN para flexibilidade
* Implementar QoS para tráfego crítico
* Planejar crescimento e escalabilidade
  {% endstep %}
  {% endstepper %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/redes/geoposicionamento-de-redes/wan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
