# CAM

Uma **CAM (Campus Area Network)** é uma rede de computadores que interconecta múltiplos edifícios dentro de uma área geográfica limitada, como um campus universitário, complexo industrial, hospitalar ou corporativo. As CAMs combinam características de LANs (alta velocidade) e MANs (maior escala), oferecendo conectividade entre prédios geralmente através de fibra óptica ou links sem fio de alta capacidade.

### Características Principais

```yaml
Características das CAMs:
  ✅ Extensão geográfica: 1-10 km (campus universitário, hospitalar, industrial)
  ✅ Conexão entre múltiplos edifícios (5-50+ edifícios)
  ✅ Alta velocidade (1-100 Gbps entre núcleos)
  ✅ Fibra óptica como backbone principal
  ✅ Baixa latência intra-campus (1-10ms)
  ✅ Propriedade e controle total da organização
  ✅ Infraestrutura redundante (anéis, links múltiplos)
  
Diferenças para LAN:
  - Maior escala geográfica
  - Necessidade de backbone de alta capacidade
  - Maior complexidade de gerenciamento
  - Maior redundância necessária
```

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

| Tipo    | Alcance  | Velocidade Backbone | Propriedade | Edifícios | Uso Típico           |
| ------- | -------- | ------------------- | ----------- | --------- | -------------------- |
| **LAN** | Até 500m | 1-100 Gbps          | Privada     | 1-2       | Prédio único         |
| **CAM** | 1-10 km  | 10-400 Gbps         | Privada     | 3-50      | Campus universitário |
| **MAN** | 5-50 km  | 1-100 Gbps          | Mista       | 10-100    | Cidade               |
| **WAN** | >50 km   | 1-10 Gbps           | Operadora   | 100+      | Nacional/Global      |

### Aplicações Típicas

```mermaid
graph TD
    subgraph "Campus Universitário"
        A[Biblioteca Central]
        B[Centro de Aulas]
        C[Laboratórios]
        D[Residências]
        E[Administração]
        F[Data Center]
        G[Centro Esportivo]
    end
    
    F --- A
    F --- B
    F --- C
    F --- D
    F --- E
    F --- G
    
    A --- B
    B --- C
    C --- D
    D --- E
    E --- G
```

***

## 🏗️ Arquitetura e Componentes

### Arquitetura Hierárquica de CAM

```mermaid
graph TD
    subgraph "Camada Core (Backbone)"
        C1[Core Switch 1 - 400G]
        C2[Core Switch 2 - 400G]
        C3[Core Switch 3 - 400G]
    end
    
    subgraph "Camada Distribuição"
        D1[Dist. Switch - Prédio A]
        D2[Dist. Switch - Prédio B]
        D3[Dist. Switch - Prédio C]
        D4[Dist. Switch - Prédio D]
    end
    
    subgraph "Camada Acesso"
        A1[Access Switch 1]
        A2[Access Switch 2]
        A3[Access Switch 3]
        A4[Access Switch 4]
        A5[Access Switch 5]
        A6[Access Switch 6]
    end
    
    C1 --- C2
    C1 --- C3
    C2 --- C3
    
    C1 --- D1
    C1 --- D2
    C2 --- D3
    C3 --- D4
    
    D1 --- A1
    D1 --- A2
    D2 --- A3
    D3 --- A4
    D4 --- A5
    D4 --- A6
```

### Componentes de uma CAM

| Componente              | Função                    | Especificação Típica | Redundância     |
| ----------------------- | ------------------------- | -------------------- | --------------- |
| **Core Switch**         | Backbone principal        | 100-400 Gbps         | 2-4 switches    |
| **Distribution Switch** | Agregação por prédio      | 10-100 Gbps          | 2 switches      |
| **Access Switch**       | Conexão final de usuários | 1-10 Gbps            | 1-2 switches    |
| **Firewall**            | Segurança de perímetro    | 10-100 Gbps          | Ativo-Ativo     |
| **Router**              | Roteamento entre campus   | 10-100 Gbps          | 2+ roteadores   |
| **Wireless Controller** | Gerencia APs              | 500-5000 APs         | 2 controladores |
| **UPS**                 | Energia ininterrupta      | 30-120 min           | N+1             |

### Infraestrutura de Fibra Óptica

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

class FiberInfrastructure:
    """Infraestrutura de fibra óptica para CAM"""
    
    def __init__(self):
        self.links = []
        self.splitters = []
        self.odfs = []
    
    def add_fiber_link(self, link_id, source, destination, distance, fiber_type):
        """Adicionar link de fibra óptica"""
        fiber_types = {
            'SMF': {'max_distance': 80000, 'speed': '100G+', 'wavelength': 1310},
            'MMF': {'max_distance': 550, 'speed': '10G', 'wavelength': 850},
            'OM3': {'max_distance': 300, 'speed': '10G', 'wavelength': 850},
            'OM4': {'max_distance': 400, 'speed': '10G/40G', 'wavelength': 850},
            'OM5': {'max_distance': 440, 'speed': '40G/100G', 'wavelength': 850}
        }
        
        self.links.append({
            'id': link_id,
            'source': source,
            'destination': destination,
            'distance': distance,
            'type': fiber_type,
            'specs': fiber_types.get(fiber_type, {}),
            'status': 'active'
        })
        
        print(f"[+] Link {link_id}: {source} -> {destination} ({distance}m, {fiber_type})")
        return True
    
    def add_dwdm_system(self, system_id, channels=80):
        """Adicionar sistema DWDM"""
        print(f"[+] Sistema DWDM {system_id}: {channels} canais")
        
        # Capacidade DWDM: 80 canais x 100G = 8Tbps
        capacity = channels * 100
        print(f"    Capacidade total: {capacity} Gbps")
        
        return {'id': system_id, 'channels': channels, 'capacity': capacity}
    
    def calculate_loss_budget(self, distance, connector_count, splice_count):
        """Calcular budget de perda óptica"""
        # Perda típica: fibra (0.35dB/km), conector (0.5dB), splice (0.1dB)
        fiber_loss = distance * 0.35 / 1000
        connector_loss = connector_count * 0.5
        splice_loss = splice_count * 0.1
        
        total_loss = fiber_loss + connector_loss + splice_loss
        
        print(f"\n[*] Cálculo de Perda Óptica")
        print(f"    Distância: {distance}m")
        print(f"    Perda de fibra: {fiber_loss:.2f}dB")
        print(f"    Perda de conectores: {connector_loss:.2f}dB")
        print(f"    Perda de splices: {splice_loss:.2f}dB")
        print(f"    Perda total: {total_loss:.2f}dB")
        
        return total_loss
    
    def show_topology(self):
        """Exibir topologia de fibra"""
        print("\n=== Topologia de Fibra Óptica ===\n")
        
        for link in self.links:
            print(f"Link {link['id']}: {link['source']} ↔ {link['destination']}")
            print(f"  Distância: {link['distance']}m")
            print(f"  Tipo: {link['type']}")
            print(f"  Velocidade máx: {link['specs'].get('speed', 'N/A')}")

# Exemplo
fiber = FiberInfrastructure()

# Backbone principal
fiber.add_fiber_link("FIB-001", "Core1", "Core2", 1500, "SMF")
fiber.add_fiber_link("FIB-002", "Core2", "Core3", 1200, "SMF")
fiber.add_fiber_link("FIB-003", "Core3", "Core1", 1300, "SMF")

# Distribuição para prédios
fiber.add_fiber_link("FIB-010", "Core1", "Building-A", 800, "SMF")
fiber.add_fiber_link("FIB-011", "Core2", "Building-B", 950, "SMF")
fiber.add_fiber_link("FIB-012", "Core3", "Building-C", 700, "SMF")
fiber.add_fiber_link("FIB-013", "Core1", "Building-D", 1100, "SMF")

# Sistema DWDM
fiber.add_dwdm_system("DWDM-01", 80)

# Cálculo de perda
fiber.calculate_loss_budget(1500, 6, 4)

fiber.show_topology()
```

***

## 🔌 Infraestrutura de Rede

### Backbone de Fibra Óptica

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

class CampusBackbone:
    """Backbone de rede para CAM"""
    
    def __init__(self):
        self.core_switches = []
        self.aggregation_switches = []
        self.links = []
    
    def add_core_switch(self, name, location, model, ports):
        """Adicionar switch de núcleo"""
        self.core_switches.append({
            'name': name,
            'location': location,
            'model': model,
            'ports': ports,
            'uptime': 0,
            'status': 'active'
        })
        print(f"[+] Core Switch {name} adicionado em {location}")
    
    def add_aggregation_switch(self, name, building, model, uplink_speed):
        """Adicionar switch de agregação"""
        self.aggregation_switches.append({
            'name': name,
            'building': building,
            'model': model,
            'uplink_speed': uplink_speed,
            'status': 'active'
        })
        print(f"[+] Aggregation Switch {name} adicionado em {building}")
    
    def add_backbone_link(self, link_id, source, destination, speed, redundancy=True):
        """Adicionar link de backbone"""
        self.links.append({
            'id': link_id,
            'source': source,
            'destination': destination,
            'speed': speed,
            'redundancy': redundancy,
            'status': 'up'
        })
        print(f"[+] Backbone link {link_id}: {source} -> {destination} ({speed})")
    
    def configure_ecmp(self, links):
        """Configurar ECMP (Equal-Cost Multi-Path)"""
        print(f"\n[*] Configurando ECMP para {len(links)} links")
        
        for link in links:
            print(f"    {link['source']} -> {link['destination']}: {link['speed']}")
        
        print(f"[+] ECMP ativo - tráfego balanceado entre links")
        return True
    
    def configure_vxlan(self, vni, source_switch, destination_switch):
        """Configurar VXLAN para extensão de VLAN"""
        print(f"\n[*] Configurando VXLAN (VNI: {vni})")
        print(f"    Source: {source_switch}")
        print(f"    Destination: {destination_switch}")
        print(f"[+] VXLAN tunnel estabelecido")
        
        return {'vni': vni, 'source': source_switch, 'destination': destination_switch}
    
    def show_topology(self):
        """Exibir topologia do backbone"""
        print("\n=== Topologia do Backbone ===\n")
        
        print("Core Switches:")
        for sw in self.core_switches:
            print(f"  {sw['name']} - {sw['location']} ({sw['model']})")
        
        print("\nAggregation Switches:")
        for sw in self.aggregation_switches:
            print(f"  {sw['name']} - {sw['building']} ({sw['uplink_speed']})")
        
        print("\nBackbone Links:")
        for link in self.links:
            red = " (Redundante)" if link['redundancy'] else ""
            print(f"  {link['id']}: {link['source']} ↔ {link['destination']} - {link['speed']}{red}")

# Exemplo
backbone = CampusBackbone()

# Core switches
backbone.add_core_switch("CORE-1", "Data Center A", "Cisco 9508", 48)
backbone.add_core_switch("CORE-2", "Data Center B", "Cisco 9508", 48)
backbone.add_core_switch("CORE-3", "Data Center C", "Arista 7280", 48)

# Aggregation switches
backbone.add_aggregation_switch("AGG-A", "Building A", "Cisco 9300", "40G")
backbone.add_aggregation_switch("AGG-B", "Building B", "Cisco 9300", "40G")
backbone.add_aggregation_switch("AGG-C", "Building C", "Arista 7050", "100G")

# Backbone links
backbone.add_backbone_link("BKL-01", "CORE-1", "CORE-2", "400G")
backbone.add_backbone_link("BKL-02", "CORE-2", "CORE-3", "400G")
backbone.add_backbone_link("BKL-03", "CORE-3", "CORE-1", "400G")
backbone.add_backbone_link("BKL-10", "CORE-1", "AGG-A", "100G")
backbone.add_backbone_link("BKL-11", "CORE-2", "AGG-B", "100G")
backbone.add_backbone_link("BKL-12", "CORE-3", "AGG-C", "100G")

# ECMP
backbone.configure_ecmp([
    {'source': 'CORE-1', 'destination': 'AGG-A', 'speed': '100G'},
    {'source': 'CORE-2', 'destination': 'AGG-A', 'speed': '100G'}
])

# VXLAN
backbone.configure_vxlan(10000, "CORE-1", "CORE-2")

backbone.show_topology()
```

### Wireless Campus Network

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

class WirelessCampus:
    """Rede Wi-Fi para CAM"""
    
    def __init__(self):
        self.controllers = []
        self.access_points = []
        self.ssids = []
        self.coverage_zones = {}
    
    def add_controller(self, name, model, capacity_aps):
        """Adicionar controlador Wi-Fi"""
        self.controllers.append({
            'name': name,
            'model': model,
            'capacity': capacity_aps,
            'active_aps': 0
        })
        print(f"[+] Controller {name} adicionado (capacidade: {capacity_aps} APs)")
    
    def add_access_point(self, name, building, floor, controller, radio_type):
        """Adicionar Access Point"""
        radio_types = {
            'dual-band': ['2.4GHz', '5GHz'],
            'tri-band': ['2.4GHz', '5GHz', '6GHz'],
            'WiFi6': ['2.4GHz', '5GHz', '6GHz']
        }
        
        self.access_points.append({
            'name': name,
            'building': building,
            'floor': floor,
            'controller': controller,
            'radio': radio_type,
            'bands': radio_types.get(radio_type, ['2.4GHz', '5GHz']),
            'status': 'online'
        })
        
        # Atualizar contador do controller
        for ctrl in self.controllers:
            if ctrl['name'] == controller:
                ctrl['active_aps'] += 1
        
        print(f"[+] AP {name} adicionado em {building}, andar {floor}")
    
    def add_ssid(self, name, encryption, vlan, authentication):
        """Adicionar SSID"""
        encryption_types = {
            'Open': None,
            'WPA2-PSK': 'AES-CCMP',
            'WPA2-Enterprise': 'AES-CCMP + 802.1X',
            'WPA3-SAE': 'AES-GCMP',
            'WPA3-Enterprise': 'AES-GCMP + 802.1X'
        }
        
        self.ssids.append({
            'name': name,
            'encryption': encryption,
            'cipher': encryption_types.get(encryption),
            'vlan': vlan,
            'authentication': authentication,
            'enabled': True
        })
        
        print(f"[+] SSID '{name}' adicionado (VLAN {vlan})")
    
    def configure_coverage(self, zone_name, buildings, ap_count):
        """Configurar zona de cobertura"""
        self.coverage_zones[zone_name] = {
            'buildings': buildings,
            'ap_count': ap_count,
            'coverage_percentage': 95
        }
        print(f"[+] Zona '{zone_name}' configurada: {ap_count} APs em {len(buildings)} prédios")
    
    def calculate_capacity(self, total_users, concurrent_ratio=0.3):
        """Calcular capacidade da rede"""
        concurrent_users = int(total_users * concurrent_ratio)
        ap_capacity = 50  # usuários por AP
        required_aps = (concurrent_users + ap_capacity - 1) // ap_capacity
        
        print(f"\n[*] Cálculo de Capacidade Wi-Fi")
        print(f"    Total de usuários: {total_users}")
        print(f"    Usuários simultâneos: {concurrent_users}")
        print(f"    APs necessários: {required_aps}")
        
        return {'total_users': total_users, 'concurrent': concurrent_users, 'aps': required_aps}
    
    def show_config(self):
        """Exibir configuração da rede Wi-Fi"""
        print("\n=== Configuração da Rede Wi-Fi ===\n")
        
        print("Controladores:")
        for ctrl in self.controllers:
            print(f"  {ctrl['name']}: {ctrl['active_aps']}/{ctrl['capacity']} APs")
        
        print(f"\nAccess Points: {len(self.access_points)}")
        print(f"\nSSIDs: {len(self.ssids)}")
        for ssid in self.ssids:
            print(f"  - {ssid['name']} ({ssid['encryption']})")
        
        print(f"\nZonas de Cobertura:")
        for zone, config in self.coverage_zones.items():
            print(f"  {zone}: {config['ap_count']} APs, {config['coverage_percentage']}% cobertura")

# Exemplo
wifi = WirelessCampus()

# Controladores
wifi.add_controller("WLC-1", "Cisco 9800", 2000)
wifi.add_controller("WLC-2", "Cisco 9800", 2000)

# Access Points por prédio
buildings = ['Library', 'Academic', 'Engineering', 'Dormitory', 'Administration']
for building in buildings:
    for floor in range(1, 5):
        wifi.add_access_point(f"AP-{building}-F{floor}", building, floor, "WLC-1", "WiFi6")

# SSIDs
wifi.add_ssid("Campus-WiFi", "WPA2-Enterprise", 100, "802.1X")
wifi.add_ssid("Eduroam", "WPA2-Enterprise", 101, "802.1X")
wifi.add_ssid("Guest", "Open", 200, "Captive Portal")
wifi.add_ssid("IoT", "WPA3-SAE", 300, "PSK")

# Zonas
wifi.configure_coverage("Academic Zone", ["Library", "Academic", "Engineering"], 150)
wifi.configure_coverage("Residential Zone", ["Dormitory"], 50)

# Capacidade
wifi.calculate_capacity(15000, 0.25)

wifi.show_config()
```

***

## 📡 Protocolos e Serviços

### Protocolos de Roteamento para CAM

| Protocolo | Uso                    | Vantagens                  | Desvantagens          |
| --------- | ---------------------- | -------------------------- | --------------------- |
| **OSPF**  | Roteamento interno     | Convergência rápida, áreas | Configuração complexa |
| **EIGRP** | Roteamento interno     | Convergência muito rápida  | Cisco proprietário    |
| **IS-IS** | Backbone de operadoras | Escalável, estável         | Complexo              |
| **BGP**   | Entre campi            | Políticas de rota          | Lenta convergência    |

### Configuração OSPF para CAM

```cisco
! Configuração OSPF para campus

! Core Router 1
router ospf 1
 router-id 10.0.0.1
 auto-cost reference-bandwidth 100000
 network 10.0.0.0 0.0.255.255 area 0
 network 172.16.0.0 0.0.255.255 area 1
 passive-interface default
 no passive-interface GigabitEthernet0/0
 no passive-interface GigabitEthernet0/1

! Áreas OSPF
area 0 authentication message-digest
area 1 stub no-summary
area 2 nssa

! Interface para backbone
interface GigabitEthernet0/0
 description Link para Core-2
 ip address 10.0.1.1 255.255.255.252
 ip ospf cost 10
 ip ospf message-digest-key 1 md5 SecureKey

! Interface para distribuição
interface GigabitEthernet0/1
 description Link para Agg-Building-A
 ip address 172.16.1.1 255.255.255.252
 ip ospf cost 100
 ip ospf message-digest-key 1 md5 SecureKey
```

### Serviços de Campus

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

class CampusServices:
    """Serviços de rede para CAM"""
    
    def __init__(self):
        self.services = {}
        self.dhcp_scopes = []
        self.dns_zones = []
    
    def add_dhcp_scope(self, scope_name, network, range_start, range_end, lease_time):
        """Adicionar escopo DHCP"""
        self.dhcp_scopes.append({
            'name': scope_name,
            'network': network,
            'range': f"{range_start}-{range_end}",
            'lease_time': lease_time,
            'options': {
                'router': self.get_gateway(network),
                'dns': ['8.8.8.8', '8.8.4.4'],
                'domain': 'campus.local'
            }
        })
        print(f"[+] DHCP Scope '{scope_name}' adicionado: {network}")
    
    def get_gateway(self, network):
        """Obter gateway da rede"""
        parts = network.split('.')
        parts[-1] = '1'
        return '.'.join(parts)
    
    def add_dns_zone(self, zone_name, master_server, zone_type):
        """Adicionar zona DNS"""
        self.dns_zones.append({
            'name': zone_name,
            'master': master_server,
            'type': zone_type,  # forward, reverse
            'records': []
        })
        print(f"[+] DNS Zone '{zone_name}' adicionada")
    
    def add_dns_record(self, zone_name, name, record_type, value, ttl=3600):
        """Adicionar registro DNS"""
        for zone in self.dns_zones:
            if zone['name'] == zone_name:
                zone['records'].append({
                    'name': name,
                    'type': record_type,
                    'value': value,
                    'ttl': ttl
                })
                print(f"[+] DNS Record: {name} {record_type} {value}")
                return True
        return False
    
    def configure_radius(self, server_name, secret, ports):
        """Configurar RADIUS para autenticação"""
        self.services['radius'] = {
            'name': server_name,
            'secret': secret,
            'auth_port': ports.get('auth', 1812),
            'acct_port': ports.get('acct', 1813),
            'clients': []
        }
        print(f"[+] RADIUS server '{server_name}' configurado")
    
    def add_radius_client(self, client_ip, secret):
        """Adicionar cliente RADIUS (NAS)"""
        if 'radius' in self.services:
            self.services['radius']['clients'].append({
                'ip': client_ip,
                'secret': secret
            })
            print(f"[+] RADIUS client {client_ip} adicionado")
    
    def configure_tacacs(self, server_name, key):
        """Configurar TACACS+ para administração"""
        self.services['tacacs'] = {
            'name': server_name,
            'key': key,
            'clients': []
        }
        print(f"[+] TACACS+ server '{server_name}' configurado")
    
    def show_services(self):
        """Exibir serviços configurados"""
        print("\n=== Serviços de Campus ===\n")
        
        print(f"DHCP Scopes: {len(self.dhcp_scopes)}")
        for scope in self.dhcp_scopes[:5]:
            print(f"  - {scope['name']}: {scope['network']}")
        
        print(f"\nDNS Zones: {len(self.dns_zones)}")
        for zone in self.dns_zones:
            print(f"  - {zone['name']} ({zone['type']})")
        
        if 'radius' in self.services:
            print(f"\nRADIUS: {self.services['radius']['name']}")
            print(f"  Clients: {len(self.services['radius']['clients'])}")
        
        if 'tacacs' in self.services:
            print(f"\nTACACS+: {self.services['tacacs']['name']}")

# Exemplo
services = CampusServices()

# DHCP Scopes
services.add_dhcp_scope("Academic", "10.10.0.0/16", "10.10.1.1", "10.10.100.254", 86400)
services.add_dhcp_scope("Dormitory", "10.20.0.0/16", "10.20.1.1", "10.20.200.254", 43200)
services.add_dhcp_scope("Guest", "172.16.0.0/16", "172.16.1.1", "172.16.10.254", 3600)

# DNS Zones
services.add_dns_zone("campus.local", "10.10.0.10", "forward")
services.add_dns_zone("10.10.in-addr.arpa", "10.10.0.10", "reverse")

# DNS Records
services.add_dns_record("campus.local", "www", "A", "10.10.0.100")
services.add_dns_record("campus.local", "mail", "A", "10.10.0.101")
services.add_dns_record("campus.local", "portal", "A", "10.10.0.102")

# RADIUS
services.configure_radius("radius.campus.local", "SharedSecret", {'auth': 1812, 'acct': 1813})
services.add_radius_client("10.10.0.1", "ClientSecret")
services.add_radius_client("10.20.0.1", "ClientSecret")

# TACACS+
services.configure_tacacs("tacacs.campus.local", "TacacsKey")

services.show_services()
```

***

## 🔒 Segurança em CAM

### Ameaças Comuns em CAM

```mermaid
graph TD
    A[Ameaças em CAM] --> B[Acesso Físico]
    A --> C[VLAN Hopping]
    A --> D[ARP Spoofing]
    A --> E[DHCP Spoofing]
    A --> F[STP Manipulation]
    A --> G[Wireless Attacks]
    A --> H[Insider Threats]
    
    B --> B1[Acesso a salas de equipamentos]
    C --> C1[Escape entre VLANs]
    D --> D1[MITM na rede]
    E --> E1[Redirecionamento de tráfego]
    F --> F1[Root bridge takeover]
    G --> G1[Rogue APs, Evil Twin]
    H --> H1[Acesso privilegiado indevido]
```

### Configurações de Segurança para CAM

```cisco
! Configurações de segurança para campus

! 1. VLAN Segmentation
vlan 10
 name Academic
vlan 20
 name Dormitory
vlan 30
 name Administrative
vlan 40
 name Guest
vlan 99
 name Native
vlan 999
 name Blackhole

! 2. Port Security
interface range GigabitEthernet1/0/1-48
 switchport port-security
 switchport port-security maximum 2
 switchport port-security violation shutdown
 switchport port-security aging time 60
 switchport port-security aging type inactivity

! 3. DHCP Snooping
ip dhcp snooping
ip dhcp snooping vlan 10,20,30,40
ip dhcp snooping information option
no ip dhcp snooping information option allow-untrusted

interface GigabitEthernet1/0/1
 ip dhcp snooping trust

! 4. Dynamic ARP Inspection (DAI)
ip arp inspection vlan 10,20,30,40
ip arp inspection validate src-mac dst-mac ip

interface GigabitEthernet1/0/1
 ip arp inspection trust

! 5. IP Source Guard
interface range GigabitEthernet1/0/1-48
 ip verify source

! 6. BPDU Guard / Root Guard
interface range GigabitEthernet1/0/1-48
 spanning-tree bpduguard enable
 spanning-tree guard root

! 7. 802.1X Authentication
dot1x system-auth-control
aaa authentication dot1x default group radius

interface range GigabitEthernet1/0/1-48
 authentication port-control auto
 dot1x pae authenticator
 dot1x timeout tx-period 10

! 8. Private VLANs
vlan 100
 private-vlan primary
vlan 101
 private-vlan isolated
vlan 102
 private-vlan community

vlan 100
 private-vlan association 101,102

! 9. ACLs para tráfego entre VLANs
ip access-list extended INTER-VLAN
 permit ip 10.10.0.0 0.0.255.255 10.20.0.0 0.0.255.255 eq 80
 permit ip 10.10.0.0 0.0.255.255 10.20.0.0 0.0.255.255 eq 443
 deny ip any any

! 10. Storm Control
interface range GigabitEthernet1/0/1-48
 storm-control broadcast level 10.00
 storm-control multicast level 10.00
 storm-control unicast level 80.00
```

### Segmentação de Rede

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

class NetworkSegmentation:
    """Segmentação de rede para CAM"""
    
    def __init__(self):
        self.vlans = {}
        self.vrf = {}
        self.firewall_zones = {}
    
    def create_vlan(self, vlan_id, name, subnet, gateway):
        """Criar VLAN"""
        self.vlans[vlan_id] = {
            'name': name,
            'subnet': subnet,
            'gateway': gateway,
            'dhcp': False,
            'acl_in': None,
            'acl_out': None
        }
        print(f"[+] VLAN {vlan_id}: {name} ({subnet})")
    
    def create_vrf(self, vrf_name, rd):
        """Criar VRF (Virtual Routing and Forwarding)"""
        self.vrf[vrf_name] = {
            'rd': rd,
            'vlans': [],
            'interfaces': []
        }
        print(f"[+] VRF '{vrf_name}' criada (RD: {rd})")
    
    def assign_vlan_to_vrf(self, vlan_id, vrf_name):
        """Atribuir VLAN a VRF"""
        if vlan_id in self.vlans and vrf_name in self.vrf:
            self.vrf[vrf_name]['vlans'].append(vlan_id)
            print(f"[+] VLAN {vlan_id} atribuída à VRF '{vrf_name}'")
    
    def create_firewall_zone(self, zone_name, security_level):
        """Criar zona de firewall"""
        self.firewall_zones[zone_name] = {
            'level': security_level,
            'vlans': [],
            'subnets': [],
            'policies': []
        }
        print(f"[+] Zona '{zone_name}' criada (nível: {security_level})")
    
    def add_vlan_to_zone(self, vlan_id, zone_name):
        """Adicionar VLAN à zona de firewall"""
        if zone_name in self.firewall_zones:
            self.firewall_zones[zone_name]['vlans'].append(vlan_id)
            print(f"[+] VLAN {vlan_id} adicionada à zona '{zone_name}'")
    
    def add_zone_policy(self, from_zone, to_zone, traffic, action='allow'):
        """Adicionar política entre zonas"""
        if from_zone in self.firewall_zones and to_zone in self.firewall_zones:
            policy = {
                'from': from_zone,
                'to': to_zone,
                'traffic': traffic,
                'action': action
            }
            self.firewall_zones[from_zone]['policies'].append(policy)
            print(f"[+] Política: {from_zone} -> {to_zone} ({traffic}) = {action}")
    
    def show_segmentation(self):
        """Exibir segmentação de rede"""
        print("\n=== Segmentação de Rede ===\n")
        
        print("VLANs:")
        for vlan_id, vlan in self.vlans.items():
            print(f"  {vlan_id}: {vlan['name']} - {vlan['subnet']}")
        
        print("\nVRFs:")
        for vrf_name, vrf in self.vrf.items():
            print(f"  {vrf_name}: {vrf['vlans']} VLANs")
        
        print("\nZonas de Firewall:")
        for zone, config in self.firewall_zones.items():
            print(f"  {zone} (nível {config['level']}): {len(config['vlans'])} VLANs")
            for policy in config['policies']:
                print(f"    -> {policy['to']}: {policy['traffic']} = {policy['action']}")

# Exemplo
seg = NetworkSegmentation()

# VLANs
seg.create_vlan(10, "Academic", "10.10.0.0/16", "10.10.0.1")
seg.create_vlan(20, "Dormitory", "10.20.0.0/16", "10.20.0.1")
seg.create_vlan(30, "Administrative", "10.30.0.0/16", "10.30.0.1")
seg.create_vlan(40, "Guest", "172.16.0.0/16", "172.16.0.1")
seg.create_vlan(50, "DMZ", "192.168.50.0/24", "192.168.50.1")

# VRFs
seg.create_vrf("CAMPUS", "65000:1")
seg.create_vrf("GUEST", "65000:2")
seg.create_vrf("DMZ", "65000:3")

# Atribuir VLANs a VRFs
seg.assign_vlan_to_vrf(10, "CAMPUS")
seg.assign_vlan_to_vrf(20, "CAMPUS")
seg.assign_vlan_to_vrf(30, "CAMPUS")
seg.assign_vlan_to_vrf(40, "GUEST")
seg.assign_vlan_to_vrf(50, "DMZ")

# Zonas de firewall
seg.create_firewall_zone("Internal", 80)
seg.create_firewall_zone("DMZ", 50)
seg.create_firewall_zone("Guest", 30)
seg.create_firewall_zone("Internet", 0)

# Adicionar VLANs a zonas
seg.add_vlan_to_zone(10, "Internal")
seg.add_vlan_to_zone(20, "Internal")
seg.add_vlan_to_zone(30, "Internal")
seg.add_vlan_to_zone(40, "Guest")
seg.add_vlan_to_zone(50, "DMZ")

# Políticas
seg.add_zone_policy("Internal", "Internet", "http,https", "allow")
seg.add_zone_policy("Internal", "DMZ", "all", "allow")
seg.add_zone_policy("Guest", "Internet", "http,https", "allow")
seg.add_zone_policy("DMZ", "Internal", "ssh,https", "allow")
seg.add_zone_policy("Guest", "Internal", "all", "deny")

seg.show_segmentation()
```

***

## 🎯 Pentesting em CAM

### Metodologia de Teste CAM

```mermaid
sequenceDiagram
    participant T as Testador
    participant C as Campus
    participant E as Equipamentos
    participant F as Firewall

    T->>C: 1. Reconhecimento externo
    T->>C: 2. Escaneamento de perímetro
    T->>E: 3. Análise de switches/roteadores
    T->>C: 4. Teste de VLAN hopping
    T->>C: 5. Teste de wireless
    T->>F: 6. Teste de firewall
    T->>C: 7. Documentação
```

### Ferramentas de Pentest CAM

```bash
# 1. Escaneamento de rede
nmap -sS -p- -T4 10.10.0.0/16
masscan -p1-65535 10.10.0.0/16 --rate=10000

# 2. VLAN hopping
# Double tagging
frogger -h 10.10.0.1
yersinia -I 8021q

# 3. Switch attacks
# MAC flooding
macof -i eth0
yersinia -I mac

# 4. STP attacks
yersinia -I stp
bcusb -B

# 5. DHCP attacks
dhcpstarv -i eth0 -v
yersinia -I dhcp

# 6. Wireless attacks
airmon-ng start wlan0
airodump-ng wlan0mon
aireplay-ng -0 10 -a <BSSID> wlan0mon

# 7. Firewall testing
nmap -sS -sV -p- -T4 10.10.0.1
fierce -dns campus.edu
```

### Script de Pentest CAM

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

import subprocess
import re
import sys
import socket

class CAMPentest:
    """Ferramenta de pentest para CAM"""
    
    def __init__(self, campus_range):
        self.campus_range = campus_range
        self.hosts = []
        self.vlans = {}
        self.wireless_networks = []
    
    def scan_network(self):
        """Escaneamento de rede do campus"""
        print(f"[*] Escaneando rede {self.campus_range}")
        
        try:
            result = subprocess.run(
                ['nmap', '-sn', self.campus_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.hosts.append(match.group(1))
            
            print(f"[+] {len(self.hosts)} hosts encontrados")
            return self.hosts
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def detect_vlans(self):
        """Detectar VLANs na rede"""
        print("[*] Detectando VLANs")
        
        # Simular detecção de VLANs via CDP/LLDP
        vlans_detected = [10, 20, 30, 40, 50, 99]
        
        for vlan in vlans_detected:
            self.vlans[vlan] = {
                'subnet': f"10.{vlan}.0.0/16",
                'gateway': f"10.{vlan}.0.1",
                'hosts': 0
            }
            print(f"  VLAN {vlan}: 10.{vlan}.0.0/16")
        
        return self.vlans
    
    def test_vlan_hopping(self, source_vlan, target_vlan):
        """Testar VLAN hopping (double tagging)"""
        print(f"[*] Testando VLAN hopping: {source_vlan} -> {target_vlan}")
        
        # Simular double tagging attack
        print(f"    Enviando pacote com double tag: outer={source_vlan}, inner={target_vlan}")
        
        # Verificar se consegue acessar
        target_subnet = f"10.{target_vlan}.0.0/16"
        target_gateway = f"10.{target_vlan}.0.1"
        
        result = subprocess.run(
            ['ping', '-c', '1', '-W', '1', target_gateway],
            capture_output=True
        )
        
        if result.returncode == 0:
            print(f"    [!] VLAN hopping bem-sucedido! Acesso à VLAN {target_vlan}")
            return True
        
        print(f"    [-] VLAN hopping falhou")
        return False
    
    def test_arp_spoofing(self, target_ip, gateway_ip):
        """Testar ARP spoofing na rede"""
        print(f"[*] Testando ARP spoofing: {target_ip} -> {gateway_ip}")
        
        # Simular ataque ARP spoofing
        print("    Enviando pacotes ARP falsos")
        
        # Verificar MITM
        return True
    
    def test_dhcp_starvation(self):
        """Testar DHCP starvation"""
        print("[*] Testando DHCP starvation")
        
        # Simular exaustão de DHCP
        print("    Enviando 1000 requisições DHCP com MACs falsos")
        print("    [!] DHCP starvation possível")
        
        return True
    
    def scan_wireless(self, interface='wlan0mon'):
        """Escaneamento de redes Wi-Fi"""
        print(f"[*] Escaneando redes Wi-Fi ({interface})")
        
        try:
            result = subprocess.run(
                ['airodump-ng', interface],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            for line in result.stdout.split('\n'):
                if 'ESSID' in line:
                    continue
                match = re.search(r'([0-9A-F:]{17})\s+-\d+\s+\d+\s+\d+\s+(\d+)\s+(\w+)\s+(\S+)', line)
                if match:
                    self.wireless_networks.append({
                        'bssid': match.group(1),
                        'channel': match.group(2),
                        'encryption': match.group(3),
                        'essid': match.group(4)
                    })
                    print(f"    {match.group(4)} ({match.group(1)}) - {match.group(3)}")
            
            return self.wireless_networks
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def test_rogue_ap(self):
        """Testar vulnerabilidade a rogue APs"""
        print("[*] Testando rogue AP detection")
        
        # Simular rogue AP
        print("    Criando rogue AP com SSID 'Campus-WiFi'")
        print("    [+] Rogue AP detectado? Não")
        print("    [!] Sistema não detecta rogue APs")
        
        return True
    
    def test_firewall_rules(self, external_ip):
        """Testar regras de firewall"""
        print(f"[*] Testando firewall em {external_ip}")
        
        common_ports = [21, 22, 23, 25, 80, 443, 3389, 8080, 8443]
        
        for port in common_ports:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(2)
            result = sock.connect_ex((external_ip, port))
            sock.close()
            
            if result == 0:
                print(f"    Porta {port}: ABERTA")
            else:
                print(f"    Porta {port}: FILTRADA")
        
        return True
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n" + "="*60)
        print("RELATÓRIO DE PENTEST CAM")
        print("="*60)
        
        print(f"\n[REDE]")
        print(f"  Range: {self.campus_range}")
        print(f"  Hosts ativos: {len(self.hosts)}")
        
        print(f"\n[VLANS]")
        for vlan, info in self.vlans.items():
            print(f"  VLAN {vlan}: {info['subnet']}")
        
        print(f"\n[WIRELESS]")
        print(f"  Redes detectadas: {len(self.wireless_networks)}")
        for net in self.wireless_networks[:5]:
            print(f"    {net['essid']} ({net['bssid']})")
        
        print(f"\n[VULNERABILIDADES]")
        print("  ⚠️ VLAN hopping possível")
        print("  ⚠️ ARP spoofing possível")
        print("  ⚠️ DHCP starvation possível")
        print("  ⚠️ Rogue AP detection falho")
        
        print("\n" + "="*60)

# Exemplo
pentest = CAMPentest("10.10.0.0/16")
pentest.scan_network()
pentest.detect_vlans()
pentest.test_vlan_hopping(1, 10)
pentest.scan_wireless()
pentest.test_rogue_ap()
pentest.generate_report()
```

***

## 🔧 Ferramentas e Diagnóstico

### Comandos de Diagnóstico CAM

```bash
# 1. Diagnóstico de rede
mtr -n 10.10.0.1
traceroute -n 10.20.0.1
pathping -n 10.30.0.1

# 2. Análise de VLANs
show vlan brief
show vlan id 10
show interfaces trunk

# 3. Diagnóstico STP
show spanning-tree
show spanning-tree root
show spanning-tree vlan 10

# 4. Diagnóstico OSPF
show ip ospf neighbor
show ip ospf database
show ip route ospf

# 5. Diagnóstico de switches
show mac address-table
show port-security
show dhcp snooping binding
show ip arp inspection statistics

# 6. Diagnóstico wireless
show wireless summary
show ap summary
show client summary
show wlan summary

# 7. Diagnóstico de performance
show interfaces utilization
show processes cpu
show memory statistics
show logging
```

### Script de Diagnóstico CAM

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

import subprocess
import re
import sys
from datetime import datetime

class CAMDiagnostic:
    """Diagnóstico de rede CAM"""
    
    def __init__(self, core_ips):
        self.core_ips = core_ips
        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 diagnose_connectivity(self):
        """Diagnosticar conectividade com core switches"""
        print("[*] Diagnosticando conectividade")
        
        connectivity = {}
        for ip in self.core_ips:
            result = self.run_cmd(f"ping -c 5 {ip}")
            
            loss_match = re.search(r'(\d+)% packet loss', result)
            loss = int(loss_match.group(1)) if loss_match else 100
            
            rtt_match = re.search(r'avg = (\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+)/(\d+\.\d+)', result)
            if rtt_match:
                rtt_avg = float(rtt_match.group(2))
            else:
                rtt_avg = 0
            
            connectivity[ip] = {
                'loss': loss,
                'rtt_avg': rtt_avg,
                'status': 'UP' if loss < 100 else 'DOWN'
            }
            
            print(f"  {ip}: {connectivity[ip]['status']} (loss: {loss}%, rtt: {rtt_avg:.2f}ms)")
        
        self.results['connectivity'] = connectivity
    
    def diagnose_route(self, destination):
        """Diagnosticar rota para destino"""
        print(f"\n[*] Diagnosticando rota para {destination}")
        
        trace = self.run_cmd(f"traceroute -n {destination}")
        
        hops = []
        for line in trace.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})
                if hop_ip:
                    print(f"  Hop {hop_num}: {hop_ip}")
                else:
                    print(f"  Hop {hop_num}: *")
        
        self.results['route'] = hops
        return hops
    
    def diagnose_bandwidth(self, target, duration=10):
        """Diagnosticar largura de banda"""
        print(f"\n[*] Diagnosticando largura de banda para {target}")
        
        # Simular teste de throughput
        import random
        throughput = random.uniform(100, 950)
        
        self.results['bandwidth'] = {
            'target': target,
            'throughput': throughput,
            'unit': 'Mbps',
            'duration': duration
        }
        
        print(f"  Throughput: {throughput:.2f} Mbps")
        return self.results['bandwidth']
    
    def diagnose_latency(self, target, count=100):
        """Diagnosticar latência detalhada"""
        print(f"\n[*] Diagnosticando latência para {target}")
        
        ping = self.run_cmd(f"ping -c {count} {target}")
        
        latencies = []
        for line in ping.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)],
                'count': len(latencies)
            }
            
            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_capacity(self, total_users):
        """Diagnosticar capacidade da rede"""
        print(f"\n[*] Diagnosticando capacidade para {total_users} usuários")
        
        # Cálculo simplificado
        bandwidth_per_user = 10  # Mbps
        peak_ratio = 0.3
        redundancy = 1.2
        
        peak_bandwidth = total_users * bandwidth_per_user * peak_ratio
        required_bandwidth = peak_bandwidth * redundancy
        
        self.results['capacity'] = {
            'total_users': total_users,
            'bandwidth_per_user': bandwidth_per_user,
            'peak_bandwidth': peak_bandwidth,
            'required_bandwidth': required_bandwidth,
            'recommendation': 'Adequado' if required_bandwidth < 10000 else 'Necessária expansão'
        }
        
        print(f"  Banda necessária: {required_bandwidth:.0f} Mbps")
        print(f"  Recomendação: {self.results['capacity']['recommendation']}")
        
        return self.results['capacity']
    
    def generate_report(self):
        """Gerar relatório de diagnóstico"""
        print("\n" + "="*60)
        print("RELATÓRIO DE DIAGNÓSTICO CAM")
        print("="*60)
        print(f"Data: {datetime.now()}")
        
        print("\n[CONECTIVIDADE]")
        for ip, conn in self.results.get('connectivity', {}).items():
            status = "✅" if conn['status'] == 'UP' else "❌"
            print(f"  {status} {ip}: {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"  P99: {lat.get('p99', 0):.2f}ms")
        
        if 'bandwidth' in self.results:
            bw = self.results['bandwidth']
            print(f"\n[BANDA]")
            print(f"  Throughput: {bw.get('throughput', 0):.2f} {bw.get('unit', 'Mbps')}")
        
        if 'capacity' in self.results:
            cap = self.results['capacity']
            print(f"\n[CAPACIDADE]")
            print(f"  Usuários: {cap.get('total_users', 0)}")
            print(f"  Banda necessária: {cap.get('required_bandwidth', 0):.0f} Mbps")
            print(f"  Recomendação: {cap.get('recommendation', 'N/A')}")
        
        print("\n" + "="*60)

# Exemplo
diag = CAMDiagnostic(['10.10.0.1', '10.10.0.2', '10.10.0.3'])
diag.diagnose_connectivity()
diag.diagnose_latency('10.20.0.1', 50)
diag.diagnose_bandwidth('10.30.0.1')
diag.diagnose_capacity(5000)
diag.generate_report()
```

***

## 🛡️ Hardening e Mitigação

### Checklist de Segurança para CAM

```yaml
Hardening de Infraestrutura:
  - [ ] Desabilitar portas não utilizadas
  - [ ] Configurar port security
  - [ ] Habilitar DHCP snooping
  - [ ] Habilitar Dynamic ARP Inspection (DAI)
  - [ ] Configurar BPDU Guard em portas de acesso
  - [ ] Habilitar Root Guard em portas críticas
  - [ ] Configurar Storm Control
  - [ ] Implementar 802.1X para autenticação

Segurança de VLAN:
  - [ ] Usar VLANs nativas diferentes da VLAN 1
  - [ ] Desabilitar DTP (Dynamic Trunking Protocol)
  - [ ] Configurar VLANs privadas para isolamento
  - [ ] Usar VACLs para filtragem entre VLANs
  - [ ] Implementar PVLANs para isolamento de hosts

Segurança de Plano de Controle:
  - [ ] Configurar autenticação para protocolos de roteamento
  - [ ] Implementar CoPP (Control Plane Policing)
  - [ ] Desabilitar serviços não utilizados
  - [ ] Configurar SSH em vez de Telnet
  - [ ] Implementar ACLs para gerenciamento

Segurança Wireless:
  - [ ] Usar WPA3-Enterprise
  - [ ] Implementar 802.1X com RADIUS
  - [ ] Configurar detecção de rogue APs
  - [ ] Habilitar proteção contra deauth attacks
  - [ ] Segmentar redes Wi-Fi por VLAN

Monitoramento:
  - [ ] Implementar NetFlow/IPFIX
  - [ ] Configurar SNMPv3
  - [ ] Centralizar logs (SIEM)
  - [ ] Configurar alertas de segurança
  - [ ] Realizar testes periódicos
```

### Script de Hardening CAM

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

echo "=== Hardening CAM ==="

# 1. Backup da configuração atual
backup_dir="/backup/network/$(date +%Y%m%d)"
mkdir -p $backup_dir

# Backup de configurações de switches
for switch in core-1 core-2 dist-a dist-b; do
    ssh admin@$switch "show running-config" > $backup_dir/$switch.cfg
done

# 2. Configurações de segurança
cat > /tmp/switch_security.conf << EOF
! Port Security
interface range GigabitEthernet1/0/1-48
 switchport port-security
 switchport port-security maximum 2
 switchport port-security violation shutdown
 switchport port-security aging time 60

! DHCP Snooping
ip dhcp snooping
ip dhcp snooping vlan 10,20,30,40,50

! Dynamic ARP Inspection
ip arp inspection vlan 10,20,30,40,50

! BPDU Guard
interface range GigabitEthernet1/0/1-48
 spanning-tree bpduguard enable

! Root Guard
interface range GigabitEthernet1/0/1-48
 spanning-tree guard root

! Storm Control
interface range GigabitEthernet1/0/1-48
 storm-control broadcast level 10.00
 storm-control multicast level 10.00
EOF

# 3. Configurar logging centralizado
cat >> /etc/rsyslog.conf << EOF
# Logging de rede
*.* @10.10.0.100:514
EOF

systemctl restart rsyslog

# 4. Configurar SNMPv3
cat > /tmp/snmp_config.txt << EOF
snmp-server view RO-VIEW iso included
snmp-server group READONLY v3 priv read RO-VIEW
snmp-server user monitor READONLY v3 auth sha AuthPass priv aes PrivPass
snmp-server host 10.10.0.100 version 3 priv monitor
EOF

# 5. Configurar NTP
cat >> /etc/ntp.conf << EOF
server 0.br.pool.ntp.org iburst
server 1.br.pool.ntp.org iburst
restrict default kod limited nomodify notrap nopeer noquery
restrict 127.0.0.1
EOF

systemctl restart ntp

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

***

## 📊 Conclusão e Boas Práticas

### Resumo Técnico

```yaml
CAM (Campus Area Network):
  ✅ Conectividade entre múltiplos edifícios
  ✅ Backbone de alta velocidade (fibra óptica)
  ✅ Redundância em múltiplos níveis
  ✅ Controle total da organização

Desafios de segurança:
  ❌ Grande superfície de ataque
  ❌ Complexidade de gerenciamento
  ❌ Vulnerabilidade a ataques de camada 2
  ❌ Necessidade de monitoramento constante

Boas Práticas:
  - Segmentação rigorosa com VLANs
  - Implementação de 802.1X
  - Monitoramento centralizado
  - Redundância em todos os níveis
  - Políticas de segurança consistentes
```

### Recomendações Finais

1. **Para Administradores**
   * Implementar segmentação de rede com VLANs
   * Configurar port security e DHCP snooping
   * Monitorar logs e tráfego continuamente
   * Realizar backups regulares de configurações
2. **Para Pentesters**
   * Testar VLAN hopping e STP attacks
   * Verificar configurações de segurança
   * Analisar wireless security
   * Documentar vulnerabilidades encontradas
3. **Para Arquitetos**
   * Projetar com redundância (links, equipamentos, energia)
   * Planejar crescimento e escalabilidade
   * Implementar SD-Access para automação
   * Considerar zero-trust network architecture


---

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