# MAN

Uma **MAN (Metropolitan Area Network)** é uma rede de computadores que se estende por uma área metropolitana, conectando múltiplos campi, edifícios corporativos ou instituições dentro de uma cidade. As MANs combinam características de LANs (alta velocidade) e WANs (maior escala), oferecendo conectividade metropolitana geralmente através de fibra óptica, redes de cabos ou links sem fio de alta capacidade.

### **Características Principais**

```yaml
Características das MANs:
  ✅ Extensão geográfica: 5-50 km (cidade ou região metropolitana)
  ✅ Conexão entre múltiplos campi/empresas (10-100+ locais)
  ✅ Alta velocidade (1-100 Gbps entre nós)
  ✅ Fibra óptica como backbone principal
  ✅ Baixa latência intra-metropolitana (5-20ms)
  ✅ Propriedade mista (privada ou operadora)
  ✅ Infraestrutura redundante (anéis DWDM)
  
Diferenças para outras redes:
  - Maior que CAM (campus), menor que WAN
  - Geralmente utiliza infraestrutura de operadoras
  - Pode ser pública, privada ou híbrida
```

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

| Tipo    | Alcance  | Velocidade  | Propriedade | Latência | Uso Típico      |
| ------- | -------- | ----------- | ----------- | -------- | --------------- |
| **LAN** | Até 500m | 1-100 Gbps  | Privada     | <1ms     | Prédio único    |
| **CAM** | 1-10 km  | 10-400 Gbps | Privada     | 1-5ms    | Campus          |
| **MAN** | 5-50 km  | 1-100 Gbps  | Mista       | 5-20ms   | Cidade          |
| **WAN** | >50 km   | 1-10 Gbps   | Operadora   | 20-200ms | Nacional/Global |

### **Aplicações Típicas**

```mermaid
graph TD
    subgraph "Centro da Cidade"
        A[Data Center Principal]
        B[Matriz Empresa]
    end
    
    subgraph "Zona Sul"
        C[Filial Sul]
        D[Centro de Distribuição]
    end
    
    subgraph "Zona Norte"
        E[Filial Norte]
        F[Data Center Backup]
    end
    
    subgraph "Zona Leste"
        G[Centro de Pesquisa]
        H[Universidade]
    end
    
    A --- B
    A --- C
    A --- D
    A --- E
    A --- F
    A --- G
    A --- H
    
    B --- C
    B --- E
    C --- D
    E --- F
    G --- H
```

***

## 🏗️ **Arquitetura e Componentes**

### **Arquitetura de Anel Metropolitano**

```mermaid
graph TD
    subgraph "Anel Metropolitano DWDM"
        N1[Nó 1 - Centro]
        N2[Nó 2 - Zona Sul]
        N3[Nó 3 - Zona Norte]
        N4[Nó 4 - Zona Leste]
        N5[Nó 5 - Zona Oeste]
    end
    
    N1 --- N2
    N2 --- N3
    N3 --- N4
    N4 --- N5
    N5 --- N1
    
    subgraph "Edifícios Conectados"
        D1[Data Center] --- N1
        D2[Matriz] --- N1
        D3[Filial Sul] --- N2
        D4[Filial Norte] --- N3
        D5[Universidade] --- N4
        D6[Hospital] --- N5
    end
```

### **Componentes de uma MAN**

| Componente       | Função                                | Especificação                | Redundância |
| ---------------- | ------------------------------------- | ---------------------------- | ----------- |
| **ROADM**        | Reconfiguração óptica                 | 96 canais DWDM               | Anel        |
| **Core Router**  | Roteamento metropolitano              | 100-400 Gbps                 | 2+ nós      |
| **Metro Switch** | Agregação por região                  | 10-100 Gbps                  | N+1         |
| **DWDM Mux**     | Multiplexação por comprimento de onda | 40-96 canais                 | 1+1         |
| **OTN Switch**   | Transporte óptico                     | 100-800 Gbps                 | Anel        |
| **PTN**          | Transporte de pacotes                 | 10-100 Gbps                  | 1+1         |
| **Colocation**   | Espaço para clientes                  | Racks, energia, refrigeração | N+1         |

### **Infraestrutura DWDM**

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

class DWDMNetwork:
    """Rede DWDM Metropolitana"""
    
    def __init__(self):
        self.nodes = []
        self.links = []
        self.wavelengths = {}
        self.channels = []
    
    def add_node(self, node_id, location, node_type):
        """Adicionar nó ROADM"""
        node_types = {
            'ROADM': 'Reconfigurable OADM',
            'OADM': 'Optical Add-Drop Multiplexer',
            'ILA': 'In-Line Amplifier',
            'REGEN': 'Regenerator'
        }
        
        self.nodes.append({
            'id': node_id,
            'location': location,
            'type': node_type,
            'description': node_types.get(node_type, 'Unknown')
        })
        print(f"[+] Nó {node_id} adicionado em {location} ({node_type})")
    
    def add_link(self, link_id, source, destination, distance, fibers=2):
        """Adicionar link de fibra entre nós"""
        self.links.append({
            'id': link_id,
            'source': source,
            'destination': destination,
            'distance': distance,
            'fibers': fibers,
            'status': 'active'
        })
        print(f"[+] Link {link_id}: {source} -> {destination} ({distance}km, {fibers} fibras)")
    
    def configure_wavelengths(self, start_freq=191.35, end_freq=196.10, spacing=0.05):
        """Configurar comprimentos de onda DWDM"""
        # Grid DWDM ITU-T (50GHz spacing)
        freq = start_freq
        channel = 1
        
        while freq <= end_freq:
            wavelength = 299792.458 / freq  # λ = c/f (nm)
            self.wavelengths[channel] = {
                'frequency': freq,
                'wavelength': wavelength,
                'channel': channel
            }
            channel += 1
            freq += spacing
        
        print(f"[+] {len(self.wavelengths)} canais DWDM configurados ({start_freq}-{end_freq} THz)")
        return self.wavelengths
    
    def add_service(self, service_id, bandwidth, protection='1+1'):
        """Adicionar serviço sobre DWDM"""
        protection_types = {
            '1+1': 'Proteção dedicada',
            '1:1': 'Proteção compartilhada',
            'Ring': 'Proteção em anel'
        }
        
        # Alocar canais
        channels_needed = (bandwidth + 99) // 100  # 100G por canal
        allocated = []
        
        for i in range(channels_needed):
            if len(self.wavelengths) > i:
                allocated.append(self.wavelengths[i+1])
        
        self.services.append({
            'id': service_id,
            'bandwidth': bandwidth,
            'protection': protection,
            'protection_desc': protection_types.get(protection, 'None'),
            'allocated_channels': allocated,
            'status': 'active'
        })
        
        print(f"[+] Serviço {service_id}: {bandwidth}Gbps ({protection})")
        return True
    
    def show_topology(self):
        """Exibir topologia DWDM"""
        print("\n=== Topologia DWDM Metropolitana ===\n")
        
        print("Nós ROADM:")
        for node in self.nodes:
            print(f"  {node['id']}: {node['location']} ({node['description']})")
        
        print("\nLinks Ópticos:")
        for link in self.links:
            print(f"  {link['id']}: {link['source']} ↔ {link['destination']} ({link['distance']}km)")
        
        print(f"\nCanais DWDM: {len(self.wavelengths)}")
        print(f"  Banda C: 191.35-196.10 THz")
        print(f"  Spacing: 50 GHz (0.4 nm)")
        
        if hasattr(self, 'services'):
            print(f"\nServiços Ativos: {len(self.services)}")

# Exemplo
dwdm = DWDMNetwork()

# Nós ROADM
dwdm.add_node("ROADM-01", "Centro", "ROADM")
dwdm.add_node("ROADM-02", "Zona Sul", "ROADM")
dwdm.add_node("ROADM-03", "Zona Norte", "ROADM")
dwdm.add_node("ROADM-04", "Zona Leste", "OADM")
dwdm.add_node("ROADM-05", "Zona Oeste", "ROADM")

# Links em anel
dwdm.add_link("DWDM-01", "ROADM-01", "ROADM-02", 12.5)
dwdm.add_link("DWDM-02", "ROADM-02", "ROADM-03", 15.2)
dwdm.add_link("DWDM-03", "ROADM-03", "ROADM-04", 18.7)
dwdm.add_link("DWDM-04", "ROADM-04", "ROADM-05", 14.3)
dwdm.add_link("DWDM-05", "ROADM-05", "ROADM-01", 16.8)

# Configurar canais
dwdm.configure_wavelengths()

dwdm.show_topology()
```

***

## 📡 **Tecnologias MAN**

### **Comparação de Tecnologias MAN**

| Tecnologia         | Velocidade      | Alcance   | Meio     | Vantagens                   | Desvantagens  |
| ------------------ | --------------- | --------- | -------- | --------------------------- | ------------- |
| **DWDM**           | 100G-800G por λ | 80-120km  | Fibra    | Alta capacidade, escalável  | Alto custo    |
| **OTN**            | 100G-800G       | 100-200km | Fibra    | FEC, OAM, proteção          | Complexidade  |
| **Metro Ethernet** | 10G-100G        | 40-80km   | Fibra    | Baixo custo, familiar       | Menor alcance |
| **MPLS**           | 10G-100G        | Nacional  | Qualquer | QoS, VPNs                   | Complexo      |
| **PON**            | 1G-10G          | 20km      | Fibra    | Baixo custo                 | Compartilhado |
| **WiMAX**          | 100M-1G         | 10-50km   | RF       | Sem fio, rápida implantação | Interferência |
| **Microwave**      | 1G-10G          | 10-30km   | RF       | Ponto a ponto               | Licenciamento |
| **Dark Fiber**     | Qualquer        | Limitado  | Fibra    | Controle total              | Alto custo    |

### **Metro Ethernet (E-Line, E-LAN)**

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

class MetroEthernet:
    """Rede Metro Ethernet"""
    
    def __init__(self):
        self.services = []
        self.vlans = {}
        self.connections = []
    
    def add_evc(self, evc_id, name, bandwidth, type='E-Line'):
        """Adicionar Ethernet Virtual Circuit (EVC)"""
        evc_types = {
            'E-Line': 'Point-to-Point (Ethernet Private Line)',
            'E-LAN': 'Multipoint-to-Multipoint (Ethernet LAN)',
            'E-Tree': 'Point-to-Multipoint (Ethernet Tree)'
        }
        
        self.services.append({
            'id': evc_id,
            'name': name,
            'type': type,
            'description': evc_types.get(type, 'Unknown'),
            'bandwidth': bandwidth,
            'status': 'active',
            'endpoints': []
        })
        print(f"[+] EVC {evc_id}: {name} ({type}) - {bandwidth}Mbps")
    
    def add_endpoint(self, evc_id, location, vlan, interface):
        """Adicionar endpoint à EVC"""
        for service in self.services:
            if service['id'] == evc_id:
                service['endpoints'].append({
                    'location': location,
                    'vlan': vlan,
                    'interface': interface
                })
                print(f"[+] Endpoint adicionado: {location} (VLAN {vlan})")
                return True
        return False
    
    def add_connection(self, connection_id, a_end, z_end, bandwidth):
        """Adicionar conexão Metro Ethernet"""
        self.connections.append({
            'id': connection_id,
            'a_end': a_end,
            'z_end': z_end,
            'bandwidth': bandwidth,
            'status': 'up'
        })
        print(f"[+] Conexão {connection_id}: {a_end} <-> {z_end} ({bandwidth}Mbps)")
    
    def configure_qos(self, evc_id, cos, rate_limit):
        """Configurar QoS para EVC"""
        for service in self.services:
            if service['id'] == evc_id:
                service['qos'] = {
                    'cos': cos,
                    'rate_limit': rate_limit,
                    'burst': rate_limit * 1.5
                }
                print(f"[+] QoS configurado: CoS={cos}, Rate={rate_limit}Mbps")
                return True
        return False
    
    def show_services(self):
        """Exibir serviços Metro Ethernet"""
        print("\n=== Serviços Metro Ethernet ===\n")
        
        print("EVCs:")
        for svc in self.services:
            print(f"  {svc['id']}: {svc['name']} ({svc['type']}) - {svc['bandwidth']}Mbps")
            for ep in svc['endpoints']:
                print(f"    -> {ep['location']} (VLAN {ep['vlan']})")
            if 'qos' in svc:
                print(f"    QoS: CoS={svc['qos']['cos']}, Rate={svc['qos']['rate_limit']}Mbps")
        
        print(f"\nConexões Ativas: {len(self.connections)}")
        for conn in self.connections:
            print(f"  {conn['id']}: {conn['a_end']} ↔ {conn['z_end']}")

# Exemplo
metro = MetroEthernet()

# E-Line (Ponto a ponto)
metro.add_evc("EVC-001", "Data Center to Matriz", 10000, "E-Line")
metro.add_endpoint("EVC-001", "Data Center", 100, "Gi0/1")
metro.add_endpoint("EVC-001", "Matriz", 100, "Gi0/2")
metro.configure_qos("EVC-001", 5, 10000)

# E-LAN (Multiponto)
metro.add_evc("EVC-002", "Campus Interligado", 1000, "E-LAN")
metro.add_endpoint("EVC-002", "Universidade Sul", 200, "Gi0/1")
metro.add_endpoint("EVC-002", "Universidade Norte", 200, "Gi0/2")
metro.add_endpoint("EVC-002", "Centro Pesquisa", 200, "Gi0/3")

# E-Tree (Ponto-Multiponto)
metro.add_evc("EVC-003", "Headquarters to Branches", 500, "E-Tree")
metro.add_endpoint("EVC-003", "Headquarters", 300, "Gi0/1")
metro.add_endpoint("EVC-003", "Branch Sul", 300, "Gi0/2")
metro.add_endpoint("EVC-003", "Branch Norte", 300, "Gi0/3")
metro.add_endpoint("EVC-003", "Branch Leste", 300, "Gi0/4")

# Conexões diretas
metro.add_connection("METRO-01", "Centro", "Zona Sul", 10000)
metro.add_connection("METRO-02", "Centro", "Zona Norte", 10000)
metro.add_connection("METRO-03", "Zona Sul", "Zona Leste", 5000)

metro.show_services()
```

### **MPLS Metro (L2VPN, L3VPN)**

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

class MPLS_Metro:
    """Rede MPLS Metropolitana"""
    
    def __init__(self):
        self.les = []      # Label Edge Routers
        self.lsrs = []     # Label Switch Routers
        self.lsps = []     # Label Switched Paths
        self.vpns = []     # VPNs
    
    def add_pe_router(self, name, location, capacity):
        """Adicionar Router PE (Provider Edge)"""
        self.les.append({
            'name': name,
            'location': location,
            'type': 'PE',
            'capacity': capacity,
            'interfaces': []
        })
        print(f"[+] PE Router {name} em {location} ({capacity})")
    
    def add_p_router(self, name, location, capacity):
        """Adicionar Router P (Provider)"""
        self.lsrs.append({
            'name': name,
            'location': location,
            'type': 'P',
            'capacity': capacity,
            'label_space': 1000000
        })
        print(f"[+] P Router {name} em {location} ({capacity})")
    
    def add_lsp(self, lsp_id, source, destination, bandwidth, setup_priority=5):
        """Adicionar LSP (Label Switched Path)"""
        self.lsps.append({
            'id': lsp_id,
            'source': source,
            'destination': destination,
            'bandwidth': bandwidth,
            'setup_priority': setup_priority,
            'holding_priority': setup_priority,
            'path': [],
            'status': 'up'
        })
        print(f"[+] LSP {lsp_id}: {source} -> {destination} ({bandwidth}Mbps)")
    
    def add_l3vpn(self, vpn_name, rd, rt):
        """Adicionar VPN de Camada 3 (RFC 4364)"""
        self.vpns.append({
            'name': vpn_name,
            'type': 'L3VPN',
            'rd': rd,  # Route Distinguisher
            'rt': rt,  # Route Target
            'sites': [],
            'routes': {}
        })
        print(f"[+] L3VPN '{vpn_name}' criada (RD: {rd}, RT: {rt})")
    
    def add_l2vpn(self, vpn_name, vpn_id):
        """Adicionar VPN de Camada 2 (Martini/Kompella)"""
        self.vpns.append({
            'name': vpn_name,
            'type': 'L2VPN',
            'vpn_id': vpn_id,
            'sites': [],
            'vc_id': vpn_id * 100
        })
        print(f"[+] L2VPN '{vpn_name}' criada (VPN ID: {vpn_id})")
    
    def add_site_to_vpn(self, vpn_name, site_name, ce_ip, pe_router, vlan=None):
        """Adicionar site à VPN"""
        for vpn in self.vpns:
            if vpn['name'] == vpn_name:
                vpn['sites'].append({
                    'name': site_name,
                    'ce_ip': ce_ip,
                    'pe': pe_router,
                    'vlan': vlan
                })
                print(f"[+] Site '{site_name}' adicionado à VPN '{vpn_name}'")
                return True
        return False
    
    def show_topology(self):
        """Exibir topologia MPLS"""
        print("\n=== Topologia MPLS Metropolitana ===\n")
        
        print("PE Routers:")
        for pe in self.les:
            print(f"  {pe['name']}: {pe['location']} ({pe['capacity']})")
        
        print("\nP Routers:")
        for p in self.lsrs:
            print(f"  {p['name']}: {p['location']} ({p['capacity']})")
        
        print(f"\nLSPs: {len(self.lsps)}")
        for lsp in self.lsps:
            print(f"  {lsp['id']}: {lsp['source']} -> {lsp['destination']} ({lsp['bandwidth']}Mbps)")
        
        print(f"\nVPNs: {len(self.vpns)}")
        for vpn in self.vpns:
            print(f"  {vpn['name']} ({vpn['type']}): {len(vpn['sites'])} sites")

# Exemplo
mpls = MPLS_Metro()

# PE Routers (borda)
mpls.add_pe_router("PE-1", "Centro", "400G")
mpls.add_pe_router("PE-2", "Zona Sul", "400G")
mpls.add_pe_router("PE-3", "Zona Norte", "400G")
mpls.add_pe_router("PE-4", "Zona Leste", "200G")
mpls.add_pe_router("PE-5", "Zona Oeste", "200G")

# P Routers (core)
mpls.add_p_router("P-1", "Centro", "800G")
mpls.add_p_router("P-2", "Zona Sul", "800G")
mpls.add_p_router("P-3", "Zona Norte", "800G")

# LSPs
mpls.add_lsp("LSP-01", "PE-1", "PE-2", 40000)
mpls.add_lsp("LSP-02", "PE-1", "PE-3", 40000)
mpls.add_lsp("LSP-03", "PE-2", "PE-3", 40000)
mpls.add_lsp("LSP-04", "PE-1", "PE-4", 10000)
mpls.add_lsp("LSP-05", "PE-1", "PE-5", 10000)

# L3VPN para clientes corporativos
mpls.add_l3vpn("Enterprise-1", "65000:100", "65000:100")
mpls.add_site_to_vpn("Enterprise-1", "Matriz", "10.0.0.1", "PE-1")
mpls.add_site_to_vpn("Enterprise-1", "Filial Sul", "10.0.1.1", "PE-2")
mpls.add_site_to_vpn("Enterprise-1", "Filial Norte", "10.0.2.1", "PE-3")

# L2VPN para provedor de serviços
mpls.add_l2vpn("ServiceProvider", 1000)
mpls.add_site_to_vpn("ServiceProvider", "POP-1", "N/A", "PE-1", 100)
mpls.add_site_to_vpn("ServiceProvider", "POP-2", "N/A", "PE-2", 100)
mpls.add_site_to_vpn("ServiceProvider", "POP-3", "N/A", "PE-3", 100)

mpls.show_topology()
```

***

## 🔒 **Segurança em MAN**

### **Ameaças Comuns em MAN**

```mermaid
graph TD
    A[Ameaças em MAN] --> B[Eavesdropping Óptico]
    A --> C[Fibra Tapping]
    A --> D[Label Spoofing]
    A --> E[VLAN Hopping]
    A --> F[DoS/DDoS]
    A --> G[Physical Access]
    A --> H[BGP Hijacking]
    
    B --> B1[Interceptação de luz]
    C --> C1[Clonagem de sinal]
    D --> D1[Injeção de labels]
    E --> E1[Escape entre VLANs]
    F --> F1[Inundação de tráfego]
    G --> G1[Acesso a PoPs]
    H --> H1[Redirecionamento de rotas]
```

### **Configurações de Segurança para MAN**

```cisco
! Configurações de segurança para rede metropolitana

! 1. Autenticação de roteamento (OSPF/BGP)
router ospf 1
 area 0 authentication message-digest
!
router bgp 65000
 neighbor 10.0.0.1 remote-as 65001
 neighbor 10.0.0.1 password 7 SecureBGPKey
 neighbor 10.0.0.1 ttl-security hops 1

! 2. MPLS Label Security
mpls label protocol ldp
mpls ldp password required
mpls ldp neighbor 10.0.0.1 password SecureLDPKey

! 3. VRF-Aware Security
vrf definition CUSTOMER-A
 rd 65000:100
 route-target export 65000:100
 route-target import 65000:100
!
 ip access-list extended CUSTOMER-ACL
  permit ip 10.0.0.0 0.255.255.255 any

! 4. Control Plane Policing
class-map match-all BGP-CLASS
 match protocol bgp
!
policy-map CONTROL-PLANE-POLICY
 class BGP-CLASS
  police 1000000 conform-action transmit exceed-action drop
!
control-plane
 service-policy input CONTROL-PLANE-POLICY

! 5. MACsec (802.1AE) para links metro
interface GigabitEthernet0/0/0
 macsec encrypt
 macsec replay-protection window-size 64
 macsec policy MUST_SECURE
 mka key-server priority 10
 mka policy MUST_SECURE

! 6. Link Layer Discovery Protocol (LLDP) Security
no lldp receive
no lldp transmit

! 7. ACL para gerenciamento
ip access-list extended MANAGEMENT-ACL
 permit tcp 10.0.0.0 0.0.255.255 any eq 22
 permit tcp 10.0.0.0 0.0.255.255 any eq 161
 deny ip any any log
```

### **Proteção de Fibra Óptica**

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

class FiberSecurity:
    """Proteções de segurança para fibra óptica"""
    
    def __init__(self):
        self.protections = {}
        self.monitoring_points = []
    
    def add_protection(self, link_id, protection_type):
        """Adicionar proteção a link de fibra"""
        protection_types = {
            'AES-256': 'Criptografia de camada física',
            'OTDR': 'Monitoramento de reflexão',
            'Polarization': 'Monitoramento de polarização',
            'Loss': 'Monitoramento de perda óptica'
        }
        
        self.protections[link_id] = {
            'type': protection_type,
            'description': protection_types.get(protection_type, 'Unknown'),
            'status': 'active'
        }
        print(f"[+] Proteção '{protection_type}' adicionada ao link {link_id}")
    
    def add_monitoring_point(self, node, fiber, direction):
        """Adicionar ponto de monitoramento"""
        self.monitoring_points.append({
            'node': node,
            'fiber': fiber,
            'direction': direction,
            'status': 'monitoring'
        })
        print(f"[+] Ponto de monitoramento em {node} (fibras {fiber})")
    
    def detect_tapping(self):
        """Detectar tentativas de tapping na fibra"""
        print("\n[*] Verificando sinais de tapping óptico")
        
        # Simular detecção
        taps = []
        
        # Verificar variações de potência
        power_variation = 0.5  # dB
        if power_variation > 0.3:
            taps.append({
                'location': 'Link DWDM-01',
                'type': 'Power variation',
                'severity': 'HIGH'
            })
        
        # Verificar reflexões anômalas (OTDR)
        reflections = True
        if reflections:
            taps.append({
                'location': 'Link DWDM-02',
                'type': 'Anomalous reflection',
                'severity': 'CRITICAL'
            })
        
        if taps:
            print("[!] Possível tapping detectado!")
            for tap in taps:
                print(f"    {tap['location']}: {tap['type']} (Severidade: {tap['severity']})")
        else:
            print("[+] Nenhuma anomalia detectada")
        
        return taps
    
    def analyze_encryption(self, link_id):
        """Analisar criptografia do link"""
        print(f"\n[*] Analisando criptografia do link {link_id}")
        
        # Verificar tipo de criptografia
        crypto = {
            'layer': 'Physical Layer (OTN)',
            'algorithm': 'AES-256-GCM',
            'key_exchange': 'Diffie-Hellman Group 14',
            'key_rotation': '3600 seconds'
        }
        
        print(f"  Camada: {crypto['layer']}")
        print(f"  Algoritmo: {crypto['algorithm']}")
        print(f"  Troca de chaves: {crypto['key_exchange']}")
        print(f"  Rotação: {crypto['key_rotation']}")
        
        return crypto
    
    def generate_report(self):
        """Gerar relatório de segurança de fibra"""
        print("\n=== Relatório de Segurança de Fibra ===\n")
        
        print("Proteções Ativas:")
        for link, prot in self.protections.items():
            print(f"  {link}: {prot['type']} ({prot['status']})")
        
        print(f"\nPontos de Monitoramento: {len(self.monitoring_points)}")
        
        # Simular análise de tapping
        self.detect_tapping()
        
        print("\n" + "="*40)

# Exemplo
fiber_sec = FiberSecurity()

# Adicionar proteções
fiber_sec.add_protection("DWDM-01", "AES-256")
fiber_sec.add_protection("DWDM-02", "OTDR")
fiber_sec.add_protection("DWDM-03", "Loss")

# Adicionar pontos de monitoramento
fiber_sec.add_monitoring_point("ROADM-01", "DWDM-01/02", "bidirectional")
fiber_sec.add_monitoring_point("ROADM-02", "DWDM-02/03", "bidirectional")
fiber_sec.add_monitoring_point("ROADM-03", "DWDM-01/03", "bidirectional")

# Analisar criptografia
fiber_sec.analyze_encryption("DWDM-01")

# Gerar relatório
fiber_sec.generate_report()
```

***

## 🎯 **Pentesting em MAN**

### **Metodologia de Teste MAN**

```mermaid
sequenceDiagram
    participant T as Testador
    participant M as Rede MAN
    participant P as Provedor
    participant C as Cliente

    T->>M: 1. Reconhecimento de topologia
    T->>P: 2. Análise de rotas BGP/MPLS
    T->>M: 3. Teste de isolamento de VPNs
    T->>M: 4. Teste de QoS
    T->>P: 5. Análise de configurações
    T->>C: 6. Teste de extremidade a extremidade
    T->>M: 7. Documentação
```

### **Ferramentas de Pentest MAN**

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

# 2. Análise de MPLS
# Verificar LDP neighbors
mpls-ping 10.0.0.2
traceroute -T -p 80 10.0.0.2

# 3. Análise de VPN
ike-scan -M 10.0.0.1
ike-scan --pskcrack -P psk.txt 10.0.0.1

# 4. Teste de throughput
iperf3 -c 10.0.0.2 -p 5201 -t 30
nuttcp -t -i1 10.0.0.2

# 5. Análise de latência
mtr -n 10.0.0.2
tcptraceroute -n 10.0.0.2 80

# 6. Teste de QoS
hping3 -S -p 80 --dscp 46 10.0.0.2
hping3 -S -p 80 --fast 10.0.0.2
```

### **Script de Pentest MAN**

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

import socket
import subprocess
import re
import sys
from datetime import datetime

class MANPentest:
    """Ferramenta de pentest para redes MAN"""
    
    def __init__(self, network_range):
        self.network_range = network_range
        self.results = {}
        self.devices = []
    
    def discover_devices(self):
        """Descobrir dispositivos na rede MAN"""
        print(f"[*] Descobrindo dispositivos em {self.network_range}")
        
        try:
            result = subprocess.run(
                ['nmap', '-sn', self.network_range],
                capture_output=True,
                text=True,
                timeout=120
            )
            
            for line in result.stdout.split('\n'):
                match = re.search(r'Nmap scan report for ([\d\.]+)', line)
                if match:
                    self.devices.append(match.group(1))
            
            print(f"[+] {len(self.devices)} dispositivos encontrados")
            return self.devices
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def analyze_bgp(self, bgp_peer):
        """Analisar peer BGP"""
        print(f"[*] Analisando BGP peer {bgp_peer}")
        
        try:
            # Simular coleta de informações BGP
            bgp_info = {
                'asn': 65000,
                'prefixes': 1250,
                'neighbors': 4,
                'uptime': '45d 12h'
            }
            
            print(f"  ASN: {bgp_info['asn']}")
            print(f"  Prefixos: {bgp_info['prefixes']}")
            print(f"  Vizinhos: {bgp_info['neighbors']}")
            
            self.results['bgp'] = bgp_info
            return bgp_info
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return {}
    
    def test_mpls_vpn_isolation(self, vpn_a_ce, vpn_b_ce):
        """Testar isolamento entre VPNs MPLS"""
        print(f"[*] Testando isolamento entre VPNs")
        print(f"    VPN A CE: {vpn_a_ce}")
        print(f"    VPN B CE: {vpn_b_ce}")
        
        # Tentar acessar VPN B a partir de VPN A
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            result = sock.connect_ex((vpn_b_ce, 80))
            sock.close()
            
            if result == 0:
                print("    [!] Isolamento falhou! VPN A acessou VPN B")
                return False
            else:
                print("    [+] Isolamento funcionando")
                return True
                
        except Exception as e:
            print(f"    [+] Isolamento ok (erro: {e})")
            return True
    
    def test_qos(self, target_ip):
        """Testar qualidade de serviço"""
        print(f"[*] Testando QoS para {target_ip}")
        
        # Medir latência e jitter
        latencies = []
        
        for i in range(100):
            start = datetime.now()
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((target_ip, 80))
            elapsed = (datetime.now() - start).total_seconds() * 1000
            if result == 0:
                latencies.append(elapsed)
            sock.close()
        
        if latencies:
            avg_latency = sum(latencies) / len(latencies)
            min_latency = min(latencies)
            max_latency = max(latencies)
            jitter = max_latency - min_latency
            
            self.results['qos'] = {
                'avg_latency': avg_latency,
                'min_latency': min_latency,
                'max_latency': max_latency,
                'jitter': jitter,
                'packet_loss': 100 - (len(latencies) / 100 * 100)
            }
            
            print(f"  Latência média: {avg_latency:.2f}ms")
            print(f"  Jitter: {jitter:.2f}ms")
            print(f"  Perda: {self.results['qos']['packet_loss']:.1f}%")
        
        return self.results.get('qos', {})
    
    def test_vlan_hopping(self, native_vlan=1):
        """Testar VLAN hopping (double tagging)"""
        print(f"[*] Testando VLAN hopping (VLAN nativa: {native_vlan})")
        
        # Simular double tagging attack
        print("    Enviando pacote com double tag")
        print("    [!] VLAN hopping possível se switch não filtra tags duplas")
        
        return True
    
    def analyze_security_config(self):
        """Analisar configurações de segurança"""
        print("[*] Analisando configurações de segurança")
        
        security_checks = {
            'BGP MD5': 'Configurado',
            'MPLS LDP Auth': 'Não configurado',
            'SSH Access': 'Habilitado',
            'SNMPv3': 'Configurado',
            'NTP': 'Configurado',
            'ACLs': 'Parcialmente configurado'
        }
        
        issues = []
        for check, status in security_checks.items():
            if status == 'Não configurado' or status == 'Parcialmente configurado':
                issues.append(check)
            print(f"  {check}: {status}")
        
        self.results['security_issues'] = issues
        return issues
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n" + "="*60)
        print("RELATÓRIO DE PENTEST MAN")
        print("="*60)
        print(f"Data: {datetime.now()}")
        print(f"Range: {self.network_range}")
        
        print(f"\n[DISPOSITIVOS]")
        print(f"  Ativos: {len(self.devices)}")
        for device in self.devices[:10]:
            print(f"    {device}")
        if len(self.devices) > 10:
            print(f"    ... e mais {len(self.devices) - 10} dispositivos")
        
        if 'bgp' in self.results:
            bgp = self.results['bgp']
            print(f"\n[BGP]")
            print(f"  ASN: {bgp.get('asn', 'N/A')}")
            print(f"  Prefixos: {bgp.get('prefixes', 'N/A')}")
        
        if 'qos' in self.results:
            qos = self.results['qos']
            print(f"\n[QoS]")
            print(f"  Latência média: {qos.get('avg_latency', 0):.2f}ms")
            print(f"  Jitter: {qos.get('jitter', 0):.2f}ms")
            print(f"  Perda: {qos.get('packet_loss', 0):.1f}%")
        
        if 'security_issues' in self.results:
            print(f"\n[VULNERABILIDADES]")
            for issue in self.results['security_issues']:
                print(f"  ⚠️ {issue}")
        
        print("\n" + "="*60)

# Exemplo
pentest = MANPentest("10.0.0.0/8")
pentest.discover_devices()
pentest.analyze_bgp("10.0.0.1")
pentest.test_mpls_vpn_isolation("10.0.1.1", "10.0.2.1")
pentest.test_qos("10.0.0.1")
pentest.analyze_security_config()
pentest.generate_report()
```

***

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

### **Comandos de Diagnóstico MAN**

```bash
# 1. Diagnóstico de rota
traceroute -n 10.0.0.1
mtr -n 10.0.0.1
tcptraceroute -n 10.0.0.1 80

# 2. Diagnóstico MPLS
show mpls ldp neighbor
show mpls forwarding-table
show mpls lsp
mpls-ping 10.0.0.2
mpls-traceroute 10.0.0.2

# 3. Diagnóstico BGP
show bgp summary
show bgp neighbors
show bgp routes
show route protocol bgp

# 4. Diagnóstico de VPN
show vrf
show vrf detail
show route vrf CUSTOMER-A
ping vrf CUSTOMER-A 10.0.1.1

# 5. Diagnóstico de interface
show interfaces optical
show interfaces utilization
show interfaces optics
show ethernet cfm maintenance-points

# 6. Diagnóstico OTN
show otn cross-connections
show otn alarm
show otn performance

# 7. Diagnóstico DWDM
show dwdm optical-power
show dwdm osnr
show dwdm wavelength
```

### **Script de Diagnóstico MAN**

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

import subprocess
import re
import sys
from datetime import datetime

class MANDiagnostic:
    """Diagnóstico de rede metropolitana"""
    
    def __init__(self, core_routers):
        self.core_routers = core_routers
        self.results = {}
    
    def diagnose_connectivity(self):
        """Diagnosticar conectividade entre core routers"""
        print("[*] Diagnosticando conectividade entre core routers")
        
        connectivity = {}
        for router in self.core_routers:
            for target in self.core_routers:
                if router != target:
                    result = subprocess.run(
                        ['ping', '-c', '5', target],
                        capture_output=True,
                        text=True
                    )
                    
                    match = re.search(r'(\d+)% packet loss', result.stdout)
                    loss = int(match.group(1)) if match else 100
                    
                    key = f"{router}->{target}"
                    connectivity[key] = {
                        'loss': loss,
                        'status': 'UP' if loss < 100 else 'DOWN'
                    }
        
        self.results['connectivity'] = connectivity
        return connectivity
    
    def diagnose_latency(self, target, count=100):
        """Diagnosticar latência detalhada"""
        print(f"\n[*] Diagnosticando latência para {target}")
        
        result = subprocess.run(
            ['ping', '-c', str(count), target],
            capture_output=True,
            text=True
        )
        
        latencies = []
        for line in result.stdout.split('\n'):
            match = re.search(r'time=(\d+\.?\d*)', line)
            if match:
                latencies.append(float(match.group(1)))
        
        if latencies:
            self.results['latency'] = {
                'min': min(latencies),
                'max': max(latencies),
                'avg': sum(latencies) / len(latencies),
                'p95': sorted(latencies)[int(len(latencies) * 0.95)],
                'p99': sorted(latencies)[int(len(latencies) * 0.99)]
            }
            
            print(f"  Mínima: {self.results['latency']['min']:.2f}ms")
            print(f"  Máxima: {self.results['latency']['max']:.2f}ms")
            print(f"  Média: {self.results['latency']['avg']:.2f}ms")
            print(f"  P95: {self.results['latency']['p95']:.2f}ms")
            print(f"  P99: {self.results['latency']['p99']:.2f}ms")
        
        return self.results.get('latency', {})
    
    def diagnose_jitter(self, target, count=100):
        """Diagnosticar jitter da conexão"""
        print(f"\n[*] Diagnosticando jitter para {target}")
        
        result = subprocess.run(
            ['ping', '-c', str(count), '-i', '0.01', target],
            capture_output=True,
            text=True
        )
        
        delays = []
        for line in result.stdout.split('\n'):
            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),
                'p95': sorted(jitters)[int(len(jitters) * 0.95)]
            }
            
            print(f"  Jitter médio: {self.results['jitter']['avg']:.2f}ms")
            print(f"  Jitter máx: {self.results['jitter']['max']:.2f}ms")
            print(f"  Jitter P95: {self.results['jitter']['p95']:.2f}ms")
        
        return self.results.get('jitter', {})
    
    def diagnose_route(self, destination):
        """Diagnosticar rota para destino"""
        print(f"\n[*] Diagnosticando rota para {destination}")
        
        result = subprocess.run(
            ['traceroute', '-n', destination],
            capture_output=True,
            text=True
        )
        
        hops = []
        for line in result.stdout.split('\n'):
            match = re.search(r'(\d+)\s+([\d\.]+|\*)', line)
            if match:
                hop_num = int(match.group(1))
                hop_ip = match.group(2) if match.group(2) != '*' else None
                hops.append({'hop': hop_num, 'ip': hop_ip})
        
        self.results['route'] = hops
        print(f"  Saltos totais: {len(hops)}")
        
        return hops
    
    def diagnose_throughput(self, target, duration=10):
        """Diagnosticar throughput (simulado)"""
        print(f"\n[*] Diagnosticando throughput para {target}")
        
        # Simular teste de throughput
        import random
        throughput = random.uniform(100, 950)
        
        self.results['throughput'] = {
            'target': target,
            'throughput': throughput,
            'unit': 'Mbps',
            'duration': duration
        }
        
        print(f"  Throughput: {throughput:.2f} Mbps")
        return self.results['throughput']
    
    def generate_report(self):
        """Gerar relatório de diagnóstico"""
        print("\n" + "="*60)
        print("RELATÓRIO DE DIAGNÓSTICO MAN")
        print("="*60)
        print(f"Data: {datetime.now()}")
        
        print("\n[CONECTIVIDADE]")
        for link, conn in self.results.get('connectivity', {}).items():
            status = "✅" if conn['status'] == 'UP' else "❌"
            print(f"  {status} {link}: {conn['status']} (loss: {conn['loss']}%)")
        
        if 'latency' in self.results:
            lat = self.results['latency']
            print(f"\n[LATÊNCIA]")
            print(f"  Média: {lat.get('avg', 0):.2f}ms")
            print(f"  P95: {lat.get('p95', 0):.2f}ms")
            print(f"  P99: {lat.get('p99', 0):.2f}ms")
        
        if 'jitter' in self.results:
            jit = self.results['jitter']
            print(f"\n[JITTER]")
            print(f"  Médio: {jit.get('avg', 0):.2f}ms")
            print(f"  P95: {jit.get('p95', 0):.2f}ms")
        
        if 'throughput' in self.results:
            thr = self.results['throughput']
            print(f"\n[THROUGHPUT]")
            print(f"  {thr.get('throughput', 0):.2f} {thr.get('unit', 'Mbps')}")
        
        if 'route' in self.results:
            print(f"\n[ROTA]")
            print(f"  Saltos: {len(self.results['route'])}")
        
        print("\n" + "="*60)

# Exemplo
diag = MANDiagnostic(['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4'])
diag.diagnose_connectivity()
diag.diagnose_latency('10.0.0.1', 50)
diag.diagnose_jitter('10.0.0.2', 50)
diag.diagnose_route('8.8.8.8')
diag.diagnose_throughput('10.0.0.1')
diag.generate_report()
```

***

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

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

```yaml
Hardening de Infraestrutura Óptica:
  - [ ] Implementar criptografia de camada física (AES-256)
  - [ ] Configurar monitoramento de tapping (OTDR)
  - [ ] Habilitar alarmes de perda de sinal
  - [ ] Restringir acesso físico a PoPs
  - [ ] Implementar OTN com FEC

Segurança MPLS:
  - [ ] Autenticação LDP (MD5)
  - [ ] Filtros de labels
  - [ ] VRF-Aware Security
  - [ ] uRPF (Unicast Reverse Path Forwarding)
  - [ ] Limit de labels por VPN

Segurança de Roteamento:
  - [ ] Autenticação BGP (MD5/TCP-AO)
  - [ ] Prefix filtering
  - [ ] AS_PATH filtering
  - [ ] Max prefix limit
  - [ ] Route dampening

Segurança de Acesso:
  - [ ] SSH em vez de Telnet
  - [ ] AAA (RADIUS/TACACS+)
  - [ ] ACLs de gerenciamento
  - [ ] Portas de gerenciamento isoladas
  - [ ] Logging centralizado

Monitoramento:
  - [ ] NetFlow/IPFIX em todos os nós
  - [ ] SNMPv3 com autenticação
  - [ ] Coleta de logs (Syslog/SIEM)
  - [ ] Monitoramento de performance óptica
  - [ ] Alertas para anomalias
```

### **Script de Hardening MAN**

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

echo "=== Hardening MAN ==="

# 1. Backup de configurações
backup_dir="/backup/man/$(date +%Y%m%d)"
mkdir -p $backup_dir

for router in pe-1 pe-2 p-1 p-2; do
    ssh admin@$router "show configuration" > $backup_dir/$router.conf
done

# 2. Configurações de segurança MPLS
cat > /tmp/mpls_security.conf << EOF
! Autenticação LDP
mpls ldp password required
mpls ldp neighbor 10.0.0.1 password SecureLDPKey

! Filtros de labels
mpls label range 100 9999
no mpls label advertise

! Proteção de VRF
vrf CUSTOMER-A
 ip vrf receive CUSTOMER-A
 ip vrf sgt CUSTOMER-A
EOF

# 3. Configurações de segurança BGP
cat > /tmp/bgp_security.conf << EOF
! Autenticação BGP
router bgp 65000
 neighbor 10.0.0.1 password SecureBGPKey
 neighbor 10.0.0.1 ttl-security hops 1
 
! Prefix filtering
 neighbor 10.0.0.1 prefix-list CUSTOMER-IN in
 neighbor 10.0.0.1 prefix-list CUSTOMER-OUT out

! Max prefix
 neighbor 10.0.0.1 maximum-prefix 1000
EOF

# 4. Configurar ACLs
cat >> /etc/iproute2/rt_tables << EOF
100 management
EOF

iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

# 5. Configurar SNMPv3
cat > /tmp/snmpv3.conf << EOF
snmp-server view ALL iso included
snmp-server group ADMIN v3 priv read ALL write ALL
snmp-server user admin ADMIN v3 auth sha AuthPass priv aes PrivPass
snmp-server host 10.0.0.100 version 3 priv admin
EOF

# 6. Configurar logging
cat >> /etc/rsyslog.conf << EOF
*.* @10.0.0.100:514
auth.* /var/log/auth.log
daemon.* /var/log/daemon.log
EOF

systemctl restart rsyslog

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

***

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

### **Resumo Técnico**

```yaml
MAN (Metropolitan Area Network):
  ✅ Conectividade metropolitana de alta velocidade
  ✅ Tecnologias maduras (DWDM, OTN, MPLS)
  ✅ Redundância em anel ou malha
  ✅ Suporte a múltiplos clientes (VPNs)

Desafios de segurança:
  ❌ Grande superfície de ataque
  ❌ Vulnerabilidade física de fibra
  ❌ Complexidade de configuração
  ❌ Dependência de operadoras (em alguns casos)

Boas Práticas:
  - Criptografia de camada física
  - Isolamento de VPNs (VRF)
  - Autenticação de roteamento
  - Monitoramento contínuo
  - Redundância em todos os níveis
```

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

1. **Para Administradores**
   * Implementar criptografia em links ópticos
   * Configurar autenticação MPLS/BGP
   * Monitorar performance e segurança
   * Realizar testes de penetração regulares
2. **Para Pentesters**
   * Testar isolamento entre VPNs
   * Verificar autenticação de roteamento
   * Analisar segurança de fibra óptica
   * Documentar configurações inseguras
3. **Para Arquitetos**
   * Projetar com redundância (anel/malha)
   * Considerar SDN para automação
   * Implementar zero-trust na borda
   * Planejar crescimento de capacidade


---

# 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/man.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.
