# PAN

Uma **PAN (Personal Area Network)** é uma rede de computadores utilizada para comunicação entre dispositivos próximos a uma pessoa, geralmente dentro de um raio de poucos metros (até 10 metros). Diferente de LANs e WANs, as PANs são centradas no indivíduo e seus dispositivos pessoais, como smartphones, tablets, wearables, fones de ouvido e outros periféricos.

### **Características Principais**

```yaml
Características das PANs:
  ✅ Curto alcance (1-10 metros)
  ✅ Baixo consumo de energia
  ✅ Baixa velocidade de transmissão (normalmente)
  ✅ Conexão ponto a ponto ou multiponto
  ✅ Topologia simples (estrela, ponto a ponto)
  ✅ Baixo custo de implementação
  
Tipos de PAN:
  - WPAN: Wireless PAN (Bluetooth, Zigbee, UWB)
  - LP-PAN: Low-Power PAN (BLE, Thread)
  - H-PAN: High-Speed PAN (Wi-Fi Direct, UWB)
  - Body Area Network (BAN): Rede corporal
```

### **Comparação com Outros Tipos de Rede**

| Tipo     | Alcance    | Velocidade          | Consumo     | Uso Típico            |
| -------- | ---------- | ------------------- | ----------- | --------------------- |
| **PAN**  | 1-10 m     | 1-100 Mbps          | Muito Baixo | Dispositivos pessoais |
| **LAN**  | 100-1000 m | 100 Mbps - 100 Gbps | Médio       | Escritório, casa      |
| **WLAN** | 30-100 m   | 54 Mbps - 9.6 Gbps  | Médio       | Wi-Fi doméstico       |
| **WAN**  | > 50 km    | 1 Mbps - 100 Gbps   | Alto        | Corporativo, Internet |

### **Aplicações Típicas**

```mermaid
graph TD
    subgraph "Dispositivos PAN"
        S[Smartphone]
        T[Tablet]
        L[Laptop]
        H[Headset Bluetooth]
        W[Smartwatch]
        K[Teclado Bluetooth]
        M[Mouse Bluetooth]
        P[Impressora]
    end
    
    S --- T
    S --- L
    S --- H
    S --- W
    T --- K
    L --- M
    L --- P
```

***

## 🏗️ **Arquitetura e Componentes**

### **Topologias PAN**

```mermaid
graph TD
    subgraph "Ponto a Ponto"
        P1[Dispositivo A] --- P2[Dispositivo B]
    end
    
    subgraph "Estrela (Piconet - Bluetooth)"
        M[Master] --- S1[Slave 1]
        M --- S2[Slave 2]
        M --- S3[Slave 3]
        M --- S4[Slave 4]
        M --- S5[Slave 5]
        M --- S6[Slave 6]
        M --- S7[Slave 7]
    end
    
    subgraph "Malha (Mesh - Zigbee)"
        M1[Nó 1] --- M2[Nó 2]
        M1 --- M3[Nó 3]
        M2 --- M4[Nó 4]
        M3 --- M4
        M2 --- M5[Nó 5]
    end
    
    subgraph "Scatternet (Bluetooth)"
        SM1[Master 1] --- SS1[Slave]
        SM1 --- SM2[Master 2]
        SM2 --- SS2[Slave]
    end
```

### **Componentes de uma PAN**

| Componente              | Função                     | Exemplo              |
| ----------------------- | -------------------------- | -------------------- |
| **Master/Coordinator**  | Gerencia a rede            | Smartphone, gateway  |
| **Slave/Device**        | Dispositivo periférico     | Fone, relógio, mouse |
| **Piconet Coordinator** | Gerencia piconet Bluetooth | Smartphone           |
| **Zigbee Coordinator**  | Gerencia rede Zigbee       | Hub doméstico        |
| **Border Router**       | Conecta PAN a outras redes | Thread Border Router |

***

## 📡 **Tecnologias PAN**

### **Comparação de Tecnologias PAN**

| Tecnologia             | Banda                | Alcance  | Velocidade    | Consumo     | Topologia     |
| ---------------------- | -------------------- | -------- | ------------- | ----------- | ------------- |
| **Bluetooth Classic**  | 2.4 GHz              | 10-100 m | 1-3 Mbps      | Médio       | Piconet       |
| **Bluetooth LE (BLE)** | 2.4 GHz              | 10-100 m | 1-2 Mbps      | Muito Baixo | Estrela/Mesh  |
| **Bluetooth 5.x**      | 2.4 GHz              | 40-400 m | 2 Mbps        | Muito Baixo | Mesh          |
| **Zigbee**             | 2.4 GHz, 868/915 MHz | 10-100 m | 250 kbps      | Muito Baixo | Mesh          |
| **Z-Wave**             | 868/915 MHz          | 30-100 m | 100 kbps      | Muito Baixo | Mesh          |
| **Thread**             | 2.4 GHz              | 10-30 m  | 250 kbps      | Muito Baixo | Mesh (IPv6)   |
| **UWB**                | 3.1-10.6 GHz         | 10-30 m  | 480-675 Mbps  | Baixo       | Ponto a ponto |
| **NFC**                | 13.56 MHz            | <10 cm   | 106-848 kbps  | Muito Baixo | Ponto a ponto |
| **Wi-Fi Direct**       | 2.4/5 GHz            | 10-100 m | 250-1500 Mbps | Alto        | P2P           |

### **Bluetooth Protocol Stack**

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

class BluetoothStack:
    """Representação da pilha de protocolos Bluetooth"""
    
    def __init__(self):
        self.layers = {
            'PHY': self.phy_layer,
            'Link': self.link_layer,
            'L2CAP': self.l2cap_layer,
            'RFCOMM': self.rfcomm_layer,
            'SDP': self.sdp_layer,
            'GAP': self.gap_layer,
            'GATT': self.gatt_layer,
            'ATT': self.att_layer
        }
    
    def phy_layer(self):
        """Camada Física (PHY)"""
        return {
            'frequency': '2.4 GHz ISM band (79 channels)',
            'modulation': 'GFSK, π/4-DQPSK, 8DPSK',
            'tx_power': 'Class 1: 100mW, Class 2: 2.5mW, Class 3: 1mW',
            'range': '10-100 meters'
        }
    
    def link_layer(self):
        """Camada de Enlace"""
        return {
            'states': ['Standby', 'Inquiry', 'Page', 'Connected', 'Sniff', 'Hold', 'Park'],
            'packet_types': ['ID', 'NULL', 'POLL', 'FHS', 'DM1', 'DH1', 'HV1'],
            'error_correction': 'FEC 1/3, 2/3, ARQ'
        }
    
    def l2cap_layer(self):
        """Logical Link Control and Adaptation Protocol"""
        return {
            'cid': 'Channel IDs (0x0001-0xFFFF)',
            'mtu': 'Default 672 bytes, max 65535',
            'channels': ['Signaling', 'Connectionless', 'Data']
        }
    
    def rfcomm_layer(self):
        """Radio Frequency Communication (Serial emulação)"""
        return {
            'channels': '1-30 (DLCI)',
            'frame_types': ['SABM', 'UA', 'DM', 'UIH', 'DISC'],
            'flow_control': 'Credit based'
        }
    
    def sdp_layer(self):
        """Service Discovery Protocol"""
        return {
            'records': 'Service attributes',
            'uuids': '16/32/128-bit identifiers',
            'requests': ['SDP_ServiceSearchRequest', 'SDP_ServiceAttributeRequest']
        }
    
    def gap_layer(self):
        """Generic Access Profile"""
        return {
            'roles': ['Broadcaster', 'Observer', 'Peripheral', 'Central'],
            'modes': ['Non-discoverable', 'Limited Discoverable', 'General Discoverable'],
            'procedures': ['Device Discovery', 'Link Establishment', 'Bonding']
        }
    
    def gatt_layer(self):
        """Generic Attribute Profile"""
        return {
            'roles': ['GATT Client', 'GATT Server'],
            'procedures': ['Discover', 'Read', 'Write', 'Notify', 'Indicate'],
            'hierarchy': ['Service', 'Characteristic', 'Descriptor']
        }
    
    def att_layer(self):
        """Attribute Protocol"""
        return {
            'opcodes': ['Read Request', 'Write Request', 'Handle Value Notification'],
            'mtu': 'Default 23 bytes, can be negotiated higher',
            'security': 'Encryption, Authentication, Authorization'
        }
    
    def show_stack(self):
        """Exibir pilha Bluetooth"""
        print("\n=== Bluetooth Protocol Stack ===\n")
        
        for layer_name, layer_func in self.layers.items():
            print(f"[{layer_name.upper()}]")
            layer_info = layer_func()
            for key, value in layer_info.items():
                print(f"  {key}: {value}")
            print()

# Exemplo
bt_stack = BluetoothStack()
bt_stack.show_stack()
```

### **Bluetooth LE (BLE) GATT Services**

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

class BLE_GATT_Service:
    """Serviço GATT Bluetooth Low Energy"""
    
    def __init__(self, uuid, name):
        self.uuid = uuid
        self.name = name
        self.characteristics = []
    
    def add_characteristic(self, uuid, name, properties):
        """Adicionar característica ao serviço"""
        self.characteristics.append({
            'uuid': uuid,
            'name': name,
            'properties': properties,
            'descriptors': []
        })
        print(f"[+] Característica {name} ({uuid}) adicionada")

class BLE_GATT_Server:
    """Servidor GATT BLE"""
    
    def __init__(self, device_name):
        self.device_name = device_name
        self.services = []
        self.connections = []
    
    def add_service(self, service):
        """Adicionar serviço ao servidor"""
        self.services.append(service)
        print(f"[+] Serviço {service.name} ({service.uuid}) adicionado")
    
    def get_service_by_uuid(self, uuid):
        """Buscar serviço por UUID"""
        for service in self.services:
            if service.uuid == uuid:
                return service
        return None
    
    def handle_read(self, characteristic_uuid):
        """Manipular solicitação de leitura"""
        print(f"[*] Leitura da característica {characteristic_uuid}")
        return f"Data from {self.device_name}"
    
    def handle_write(self, characteristic_uuid, value):
        """Manipular solicitação de escrita"""
        print(f"[*] Escrita na característica {characteristic_uuid}: {value}")
        return True
    
    def advertise(self):
        """Iniciar advertising BLE"""
        print(f"\n[*] Advertising: {self.device_name}")
        print(f"    Serviços disponíveis:")
        for service in self.services:
            print(f"    - {service.name} ({service.uuid})")
            for char in service.characteristics:
                print(f"        {char['name']} ({char['uuid']}): {char['properties']}")
        print()

# Serviços GATT comuns
SERVICE_BATTERY = "0000180f-0000-1000-8000-00805f9b34fb"
SERVICE_HEART_RATE = "0000180d-0000-1000-8000-00805f9b34fb"
SERVICE_DEVICE_INFO = "0000180a-0000-1000-8000-00805f9b34fb"
SERVICE_GENERIC_ACCESS = "00001800-0000-1000-8000-00805f9b34fb"

# Características comuns
CHAR_BATTERY_LEVEL = "00002a19-0000-1000-8000-00805f9b34fb"
CHAR_HEART_RATE_MEASUREMENT = "00002a37-0000-1000-8000-00805f9b34fb"
CHAR_MANUFACTURER_NAME = "00002a29-0000-1000-8000-00805f9b34fb"
CHAR_DEVICE_NAME = "00002a00-0000-1000-8000-00805f9b34fb"

# Exemplo
server = BLE_GATT_Server("MySmartWatch")

# Serviço de Bateria
battery_service = BLE_GATT_Service(SERVICE_BATTERY, "Battery Service")
battery_service.add_characteristic(CHAR_BATTERY_LEVEL, "Battery Level", ["read", "notify"])
server.add_service(battery_service)

# Serviço de Frequência Cardíaca
hr_service = BLE_GATT_Service(SERVICE_HEART_RATE, "Heart Rate Service")
hr_service.add_characteristic(CHAR_HEART_RATE_MEASUREMENT, "Heart Rate Measurement", ["read", "notify", "indicate"])
server.add_service(hr_service)

# Serviço de Informação do Dispositivo
device_info = BLE_GATT_Service(SERVICE_DEVICE_INFO, "Device Information")
device_info.add_characteristic(CHAR_MANUFACTURER_NAME, "Manufacturer Name", ["read"])
server.add_service(device_info)

server.advertise()
```

***

## 🔌 **Protocolos de Comunicação**

### **NFC (Near Field Communication)**

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

class NFC_Protocol:
    """Protocolo Near Field Communication"""
    
    def __init__(self):
        self.tech_types = {
            'A': 'ISO/IEC 14443 Type A',
            'B': 'ISO/IEC 14443 Type B',
            'F': 'JIS X 6319-4 (FeliCa)',
            'V': 'ISO/IEC 15693 (Vicinity)'
        }
        
        self.operating_modes = {
            'Reader/Writer': 'Read/write NFC tags',
            'Card Emulation': 'Emulate NFC card',
            'Peer-to-Peer': 'Two-way communication between devices'
        }
    
    def encode_data(self, data, tech_type='A'):
        """Codificar dados para transmissão NFC"""
        print(f"[*] Codificando dados (Tech Type: {tech_type})")
        
        # Adicionar cabeçalho NFC
        header = bytes([0x00, 0x01])  # Versão do protocolo
        
        # Payload
        payload = data.encode('utf-8')
        
        # Adicionar CRC
        crc = self.calculate_crc(header + payload)
        
        return header + payload + crc
    
    def calculate_crc(self, data):
        """Calcular CRC para NFC"""
        # CRC-16-CCITT simplificado
        crc = 0xFFFF
        for byte in data:
            crc ^= (byte << 8)
            for _ in range(8):
                if crc & 0x8000:
                    crc = (crc << 1) ^ 0x1021
                else:
                    crc = crc << 1
                crc &= 0xFFFF
        return crc.to_bytes(2, 'big')
    
    def decode_data(self, raw_data):
        """Decodificar dados recebidos"""
        print("[*] Decodificando dados NFC")
        
        # Verificar CRC
        received_crc = int.from_bytes(raw_data[-2:], 'big')
        calculated_crc = self.calculate_crc(raw_data[:-2])
        
        if received_crc != calculated_crc:
            raise Exception("CRC verification failed")
        
        # Extrair payload
        payload = raw_data[2:-2].decode('utf-8')
        
        return payload
    
    def emulate_card(self, uid, data):
        """Emular cartão NFC"""
        print(f"[*] Emulando cartão NFC (UID: {uid.hex()})")
        
        # Simular comando SELECT
        select_response = bytes([0x44, 0x00])  # OK
        
        # Simular leitura de dados
        read_response = self.encode_data(data)
        
        return {
            'select': select_response,
            'read': read_response,
            'uid': uid
        }

# Exemplo
nfc = NFC_Protocol()

# Emular cartão
uid = bytes([0x04, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB])
data = "Cardholder: John Doe\nAccount: 1234-5678"
response = nfc.emulate_card(uid, data)

print(f"UID: {response['uid'].hex()}")
print(f"SELECT Response: {response['select'].hex()}")
print(f"READ Data: {response['read'][:20]}...")
```

### **Zigbee Protocol**

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

class ZigbeeNode:
    """Nó da rede Zigbee"""
    
    def __init__(self, node_id, node_type='Router'):
        self.id = node_id
        self.type = node_type  # Coordinator, Router, EndDevice
        self.children = []
        self.parent = None
        self.neighbors = []
    
    def join_network(self, coordinator):
        """Entrar na rede Zigbee"""
        print(f"[*] Nó {self.id} entrando na rede")
        
        # Enviar solicitação de associação
        if coordinator.accept_join(self):
            self.parent = coordinator
            coordinator.add_child(self)
            print(f"[+] Nó {self.id} associado ao Coordenador {coordinator.id}")
            return True
        
        print(f"[-] Falha na associação")
        return False
    
    def send_data(self, data, destination):
        """Enviar dados para outro nó"""
        print(f"[*] Enviando dados de {self.id} para {destination.id}")
        
        # Construir frame Zigbee
        frame = {
            'frame_control': 0x41,  # Data frame, normal mode
            'seq_num': self.generate_sequence(),
            'dest_addr': destination.id,
            'source_addr': self.id,
            'payload': data
        }
        
        # Encaminhar via rota
        destination.receive_data(frame)
        return True
    
    def receive_data(self, frame):
        """Receber dados de outro nó"""
        print(f"[*] Nó {self.id} recebeu dados de {frame['source_addr']}")
        print(f"    Payload: {frame['payload']}")
        return True
    
    def generate_sequence(self):
        """Gerar número de sequência"""
        import random
        return random.randint(0, 255)

class ZigbeeCoordinator(ZigbeeNode):
    """Coordenador da rede Zigbee"""
    
    def __init__(self, node_id, pan_id):
        super().__init__(node_id, 'Coordinator')
        self.pan_id = pan_id
        self.network_key = self.generate_network_key()
        self.connected_nodes = []
    
    def generate_network_key(self):
        """Gerar chave de rede"""
        import os
        return os.urandom(16)
    
    def accept_join(self, node):
        """Aceitar novo nó na rede"""
        # Verificar se há capacidade
        if len(self.connected_nodes) < 255:
            self.connected_nodes.append(node)
            return True
        return False
    
    def add_child(self, node):
        """Adicionar nó como filho"""
        self.children.append(node)
    
    def start_network(self):
        """Iniciar rede Zigbee"""
        print(f"\n[*] Iniciando rede Zigbee (PAN ID: {self.pan_id:04X})")
        print(f"    Chave de rede: {self.network_key.hex()}")
        print(f"[+] Rede Zigbee ativa\n")

# Exemplo
coordinator = ZigbeeCoordinator(1, 0x1234)
coordinator.start_network()

node1 = ZigbeeNode(2, 'Router')
node2 = ZigbeeNode(3, 'EndDevice')

node1.join_network(coordinator)
node2.join_network(coordinator)

node1.send_data("Hello from Node 2!", node2)
```

***

## 🔒 **Segurança em PAN**

### **Ameaças Comuns em PAN**

```mermaid
graph TD
    A[Ameaças em PAN] --> B[Bluejacking]
    A --> C[Bluesnarfing]
    A --> D[Bluebugging]
    A --> E[Eavesdropping]
    A --> F[Man-in-the-Middle]
    A --> G[Denial of Service]
    A --> H[Tag Cloning]
    
    B --> B1[Spam via Bluetooth]
    C --> C1[Robo de dados]
    D --> D1[Controle remoto]
    E --> E1[Sniffing de tráfego]
    F --> F1[Interceptação]
    G --> G1[Interferência]
    H --> H1[Clonagem de tags]
```

### **Configurações de Segurança Bluetooth**

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

class BluetoothSecurity:
    """Configurações de segurança Bluetooth"""
    
    def __init__(self):
        self.security_modes = {
            'Mode 1': 'No security',
            'Mode 2': 'Service-level security',
            'Mode 3': 'Link-level security',
            'Mode 4': 'Secure Simple Pairing (SSP)'
        }
        
        self.bonding_types = {
            'No Bonding': 'Temporary connection only',
            'Bonding': 'Permanent key storage',
            'Authentication': 'Authentication required'
        }
    
    def configure_ssp(self, io_capabilities):
        """Configurar Secure Simple Pairing"""
        print("[*] Configurando Secure Simple Pairing (SSP)")
        
        io_map = {
            'DisplayOnly': 'Output only',
            'DisplayYesNo': 'Output and simple input',
            'KeyboardOnly': 'Input only',
            'NoInputNoOutput': 'No I/O',
            'KeyboardDisplay': 'Full I/O'
        }
        
        print(f"    I/O Capabilities: {io_map.get(io_capabilities, 'Unknown')}")
        
        # Métodos de associação SSP
        association_models = {
            'DisplayOnly': 'Just Works',
            'DisplayYesNo': 'Numeric Comparison',
            'KeyboardOnly': 'Passkey Entry',
            'NoInputNoOutput': 'Just Works',
            'KeyboardDisplay': 'Passkey Entry / Numeric Comparison'
        }
        
        print(f"    Association Model: {association_models.get(io_capabilities, 'Unknown')}")
        return True
    
    def enable_encryption(self, enable=True):
        """Habilitar criptografia de link"""
        if enable:
            print("[+] Criptografia de link habilitada (AES-128)")
            return True
        else:
            print("[-] Criptografia de link desabilitada")
            return False
    
    def set_link_key(self, key_type):
        """Configurar tipo de chave de link"""
        key_types = {
            'Combination': 'Generated during pairing',
            'Unit': 'Unit key (deprecated)',
            'Debug': 'Debug key (insecure)'
        }
        
        print(f"[*] Tipo de chave de link: {key_type}")
        print(f"    {key_types.get(key_type, 'Unknown')}")
        return True
    
    def configure_privacy(self, enable=True):
        """Configurar privacidade (Address Randomization)"""
        if enable:
            print("[+] Randomização de endereço habilitada")
            print("    Endereços resolvíveis serão usados")
        else:
            print("[-] Randomização de endereço desabilitada")
            print("    Endereços públicos serão usados")
        return True

# Exemplo
bt_sec = BluetoothSecurity()
bt_sec.configure_ssp('KeyboardDisplay')
bt_sec.enable_encryption(True)
bt_sec.configure_privacy(True)
```

### **Bluetooth Pairing Modes**

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

class BluetoothPairing:
    """Gerenciamento de pairing Bluetooth"""
    
    def __init__(self):
        self.paired_devices = {}
        self.bonded_devices = {}
    
    def legacy_pairing(self, device_addr, pin_code):
        """Legacy Pairing (pre-Bluetooth 2.1)"""
        print(f"[*] Legacy Pairing com {device_addr}")
        print(f"    PIN Code: {pin_code}")
        
        # Vulnerabilidades conhecidas
        print("    ⚠️ Vulnerável a ataques de PIN cracking")
        
        # Simular processo
        link_key = self.derive_key(pin_code)
        self.paired_devices[device_addr] = {'key': link_key, 'type': 'legacy'}
        return link_key
    
    def ssp_pairing(self, device_addr, method, passkey=None):
        """Secure Simple Pairing (Bluetooth 2.1+)"""
        print(f"[*] SSP Pairing com {device_addr}")
        print(f"    Method: {method}")
        
        if method == 'Numeric Comparison':
            # Gerar código de confirmação
            confirm_code = self.generate_confirm_code()
            print(f"    Confirm Code: {confirm_code}")
            user_confirm = input("    Confirm? (y/n): ")
            
            if user_confirm.lower() != 'y':
                print("[-] Pairing cancelado")
                return None
        
        elif method == 'Passkey Entry':
            if passkey:
                print(f"    Passkey: {passkey}")
            else:
                passkey = input("    Enter passkey: ")
        
        elif method == 'Just Works':
            print("    No user interaction required")
        
        # Derivação de chaves usando ECDH
        link_key = self.derive_key_ecdh()
        self.paired_devices[device_addr] = {'key': link_key, 'type': 'ssp'}
        return link_key
    
    def derive_key(self, pin):
        """Derivar chave de link (simplificado)"""
        import hashlib
        return hashlib.sha256(pin.encode()).digest()[:16]
    
    def derive_key_ecdh(self):
        """Derivar chave usando ECDH (simulado)"""
        import os
        return os.urandom(16)
    
    def generate_confirm_code(self):
        """Gerar código de confirmação de 6 dígitos"""
        import random
        return f"{random.randint(0, 999999):06d}"
    
    def show_paired_devices(self):
        """Exibir dispositivos pareados"""
        print("\n=== Paired Devices ===")
        for addr, info in self.paired_devices.items():
            print(f"  {addr}: {info['type']} pairing")

# Exemplo
pairing = BluetoothPairing()
pairing.legacy_pairing("AA:BB:CC:DD:EE:FF", "1234")
pairing.ssp_pairing("11:22:33:44:55:66", "Numeric Comparison")
pairing.show_paired_devices()
```

***

## 🎯 **Pentesting em PAN**

### **Metodologia de Teste PAN**

```mermaid
sequenceDiagram
    participant T as Testador
    participant D as Dispositivo PAN
    participant G as Gateway

    T->>D: 1. Descoberta de dispositivos
    T->>D: 2. Enumeração de serviços
    T->>D: 3. Análise de segurança
    T->>D: 4. Teste de vulnerabilidades
    T->>G: 5. Escalonamento para outras redes
    T->>D: 6. Documentação
```

### **Ferramentas de Pentest PAN**

```bash
# 1. Bluetooth Scanning
hcitool scan               # Dispositivos Classic Bluetooth
hcitool inq                # Inquiry
hcitool name <MAC>         # Obter nome
hcitool info <MAC>         # Informações do dispositivo

# 2. Bluetooth LE Scanning
hcitool lescan             # Dispositivos BLE
hcitool lescan --passive   # Scan passivo
hcitool leinfo <MAC>       # Informações BLE

# 3. BlueZ Tools
bluetoothctl
bluetoothctl list
bluetoothctl scan on
bluetoothctl devices
bluetoothctl info <MAC>
bluetoothctl connect <MAC>

# 4. Gatttool (BLE GATT)
gatttool -b <MAC> --primary     # Listar serviços
gatttool -b <MAC> --characteristics
gatttool -b <MAC> --char-read -a <handle>
gatttool -b <MAC> --char-write -a <handle> -n <value>

# 5. Bettercap
bettercap -eval "set bluetooth.device hci0; bluetooth.enumerate on"
bettercap -eval "ble.recon on"

# 6. BlueBorne Scanner
# GitHub: armis/blueborne-scanner

# 7. Zigbee Tools
zigbee2mqtt
zboss
```

### **Script de Pentest Bluetooth**

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

import subprocess
import re
import sys

class BluetoothPentest:
    """Ferramenta de pentest Bluetooth"""
    
    def __init__(self, interface='hci0'):
        self.interface = interface
        self.devices = []
        self.services = {}
    
    def scan_devices(self, timeout=10):
        """Escaneamento de dispositivos Bluetooth"""
        print(f"[*] Escaneando dispositivos Bluetooth ({timeout}s)...")
        
        try:
            result = subprocess.run(
                ['hcitool', 'scan', '--timeout', str(timeout)],
                capture_output=True,
                text=True,
                timeout=timeout + 5
            )
            
            for line in result.stdout.split('\n')[1:]:
                if line.strip():
                    parts = line.split('\t')
                    if len(parts) >= 2:
                        mac = parts[0].strip()
                        name = parts[1].strip()
                        self.devices.append({
                            'mac': mac,
                            'name': name if name else 'Unknown'
                        })
                        print(f"  {mac}: {name}")
            
            return self.devices
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def get_device_info(self, mac):
        """Obter informações do dispositivo"""
        print(f"[*] Obtendo informações de {mac}")
        
        info = {}
        
        # Nome
        result = subprocess.run(
            ['hcitool', 'name', mac],
            capture_output=True,
            text=True
        )
        info['name'] = result.stdout.strip()
        
        # Info (versão, fabricante)
        result = subprocess.run(
            ['hcitool', 'info', mac],
            capture_output=True,
            text=True
        )
        info['info'] = result.stdout
        
        # Classe de dispositivo
        match = re.search(r'Class: (0x[0-9a-f]+)', result.stdout)
        if match:
            info['class'] = match.group(1)
        
        return info
    
    def enumerate_services(self, mac):
        """Enumerar serviços SDP"""
        print(f"[*] Enumerando serviços em {mac}")
        
        try:
            result = subprocess.run(
                ['sdptool', 'browse', mac],
                capture_output=True,
                text=True,
                timeout=30
            )
            
            services = []
            current_service = {}
            
            for line in result.stdout.split('\n'):
                if 'Service Name:' in line:
                    if current_service:
                        services.append(current_service)
                    current_service = {'name': line.split('Service Name:')[1].strip()}
                elif 'Service RecHandle:' in line:
                    current_service['handle'] = line.split('Service RecHandle:')[1].strip()
                elif 'Service Class ID List:' in line:
                    current_service['class_id'] = line.split('Service Class ID List:')[1].strip()
                elif 'Protocol Descriptor List:' in line:
                    current_service['protocol'] = line.split('Protocol Descriptor List:')[1].strip()
                elif 'Language Base Attr List:' in line:
                    current_service['language'] = line.split('Language Base Attr List:')[1].strip()
            
            if current_service:
                services.append(current_service)
            
            self.services[mac] = services
            return services
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def test_legacy_pairing(self, mac):
        """Testar vulnerabilidade de legacy pairing"""
        print(f"[*] Testando legacy pairing em {mac}")
        
        # Verificar versão do dispositivo
        info = self.get_device_info(mac)
        
        # Simular teste
        print("    ⚠️ Dispositivo pode ser vulnerável a ataques de PIN cracking")
        return True
    
    def test_bluejacking(self, mac, message):
        """Testar Bluejacking"""
        print(f"[*] Testando Bluejacking para {mac}")
        print(f"    Mensagem: {message}")
        
        # Enviar OBEX push
        try:
            # Simular envio
            print("    [+] Mensagem enviada")
            return True
        except:
            print("    [-] Falha no envio")
            return False
    
    def generate_report(self):
        """Gerar relatório do pentest"""
        print("\n=== RELATÓRIO DE PENTEST BLUETOOTH ===\n")
        
        print(f"Dispositivos encontrados: {len(self.devices)}")
        
        for device in self.devices:
            print(f"\nDispositivo: {device['name']} ({device['mac']})")
            
            info = self.get_device_info(device['mac'])
            print(f"  Classe: {info.get('class', 'Unknown')}")
            
            services = self.enumerate_services(device['mac'])
            print(f"  Serviços: {len(services)}")
            for service in services[:5]:  # Limitar a 5 serviços
                print(f"    - {service.get('name', 'Unknown')}")
            if len(services) > 5:
                print(f"    ... e mais {len(services) - 5} serviços")
        
        print("\n=== FIM DO RELATÓRIO ===")

# Exemplo
tester = BluetoothPentest()
tester.scan_devices(10)

if tester.devices:
    tester.generate_report()
```

### **Script de Pentest BLE**

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

import asyncio
from bleak import BleakScanner, BleakClient

class BLEPentest:
    """Ferramenta de pentest Bluetooth Low Energy"""
    
    def __init__(self):
        self.devices = []
        self.characteristics = {}
    
    async def scan_devices(self, timeout=5):
        """Escaneamento de dispositivos BLE"""
        print(f"[*] Escaneando dispositivos BLE ({timeout}s)...")
        
        def detection_callback(device, advertisement_data):
            if device.address not in [d['address'] for d in self.devices]:
                self.devices.append({
                    'address': device.address,
                    'name': device.name or 'Unknown',
                    'rssi': advertisement_data.rssi
                })
                print(f"  {device.address}: {device.name or 'Unknown'} (RSSI: {advertisement_data.rssi})")
        
        scanner = BleakScanner(detection_callback)
        await scanner.start()
        await asyncio.sleep(timeout)
        await scanner.stop()
        
        return self.devices
    
    async def connect_device(self, address):
        """Conectar a dispositivo BLE"""
        print(f"[*] Conectando a {address}")
        
        try:
            client = BleakClient(address)
            await client.connect()
            
            print(f"[+] Conectado: {client.is_connected}")
            
            # Obter serviços
            services = await client.get_services()
            print(f"[*] Serviços encontrados: {len(services.services)}")
            
            for service in services.services:
                print(f"  Service: {service.uuid}")
                for char in service.characteristics:
                    print(f"    Characteristic: {char.uuid} ({', '.join(char.properties)})")
                    
                    # Armazenar características
                    self.characteristics[char.uuid] = {
                        'handle': char.handle,
                        'properties': char.properties
                    }
            
            await client.disconnect()
            return True
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return False
    
    async def read_characteristic(self, address, char_uuid):
        """Ler característica específica"""
        print(f"[*] Lendo característica {char_uuid} de {address}")
        
        try:
            client = BleakClient(address)
            await client.connect()
            
            value = await client.read_gatt_char(char_uuid)
            print(f"[+] Valor: {value.hex()}")
            
            await client.disconnect()
            return value
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return None
    
    async def write_characteristic(self, address, char_uuid, value):
        """Escrever em característica"""
        print(f"[*] Escrevendo em característica {char_uuid}")
        
        try:
            client = BleakClient(address)
            await client.connect()
            
            await client.write_gatt_char(char_uuid, value)
            print("[+] Escrita realizada")
            
            await client.disconnect()
            return True
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return False
    
    async def run_pentest(self):
        """Executar pentest completo"""
        await self.scan_devices(5)
        
        if not self.devices:
            print("[-] Nenhum dispositivo encontrado")
            return
        
        # Testar primeiro dispositivo
        device = self.devices[0]
        print(f"\n[*] Testando dispositivo: {device['address']}")
        
        await self.connect_device(device['address'])
        
        # Verificar características de leitura
        for uuid, info in self.characteristics.items():
            if 'read' in info['properties']:
                await self.read_characteristic(device['address'], uuid)

# Exemplo de uso
# (requer biblioteca bleak: pip install bleak)
# async def main():
#     pentest = BLEPentest()
#     await pentest.run_pentest()
# 
# asyncio.run(main())
```

***

## 🔧 **Ferramentas e Diagnóstico**

### **Comandos de Diagnóstico PAN**

```bash
# 1. Bluetooth (Linux)
hciconfig -a                    # Configuração do adaptador
hcitool dev                     # Dispositivos Bluetooth
hcitool scan                    # Escaneamento básico
hcitool inq                     # Inquiry
hcitool name <MAC>              # Obter nome
hcitool info <MAC>              # Informações detalhadas
hcitool cmd <ogf> <ocf>         # Comando HCI raw

# 2. Bluetooth LE (Linux)
hcitool lescan                  # LE scan
hcitool leinfo <MAC>            # LE info
hcitool lecc <MAC>              # LE create connection
hcidump -i hci0                 # Dump HCI

# 3. Bluetoothctl
bluetoothctl
bluetoothctl list
bluetoothctl show
bluetoothctl scan on
bluetoothctl devices
bluetoothctl paired-devices
bluetoothctl info <MAC>

# 4. SDP Tool
sdptool browse <MAC>            # Enumerar serviços
sdptool records <MAC>           # Registros SDP
sdptool search <service>        # Buscar serviço

# 5. OBEX (Object Exchange)
obexftp -b <MAC> -l             # Listar arquivos
obexftp -b <MAC> -g <file>      # Baixar arquivo
obexftp -b <MAC> -p <file>      # Enviar arquivo

# 6. RFCOMM
rfcomm connect <dev> <MAC>      # Conectar RFCOMM
rfcomm watch <dev>              # Aguardar conexão

# 7. Zigbee (via dongle)
# Usar zigbee2mqtt ou zboss
zboss_cli scan
zboss_cli devices
zboss_cli permit_join 60
```

### **Script de Diagnóstico Bluetooth**

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

import subprocess
import re
import sys

class BluetoothDiagnostic:
    """Diagnóstico de Bluetooth PAN"""
    
    def __init__(self):
        self.adapter_info = {}
        self.devices = []
    
    def check_adapter(self):
        """Verificar adaptador Bluetooth"""
        print("[*] Verificando adaptador Bluetooth")
        
        try:
            result = subprocess.run(
                ['hciconfig', '-a'],
                capture_output=True,
                text=True
            )
            
            for line in result.stdout.split('\n'):
                if 'UP RUNNING' in line:
                    self.adapter_info['status'] = 'UP'
                elif 'BD Address:' in line:
                    self.adapter_info['address'] = line.split('BD Address:')[1].strip()
                elif 'Manufacturer:' in line:
                    self.adapter_info['manufacturer'] = line.split('Manufacturer:')[1].strip()
                elif 'Name:' in line:
                    self.adapter_info['name'] = line.split('Name:')[1].strip()
            
            print(f"  Status: {self.adapter_info.get('status', 'DOWN')}")
            print(f"  Endereço: {self.adapter_info.get('address', 'Unknown')}")
            print(f"  Fabricante: {self.adapter_info.get('manufacturer', 'Unknown')}")
            
            return self.adapter_info.get('status') == 'UP'
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return False
    
    def scan_devices(self, timeout=10):
        """Escaneamento de dispositivos"""
        print(f"\n[*] Escaneando dispositivos ({timeout}s)")
        
        try:
            result = subprocess.run(
                ['hcitool', 'scan', '--timeout', str(timeout)],
                capture_output=True,
                text=True,
                timeout=timeout + 5
            )
            
            for line in result.stdout.split('\n')[1:]:
                if line.strip():
                    parts = line.split('\t')
                    if len(parts) >= 2:
                        self.devices.append({
                            'address': parts[0].strip(),
                            'name': parts[1].strip()
                        })
                        print(f"  {parts[0]}: {parts[1]}")
            
            return self.devices
            
        except Exception as e:
            print(f"[-] Erro: {e}")
            return []
    
    def get_device_class(self, mac):
        """Obter classe do dispositivo"""
        try:
            result = subprocess.run(
                ['hcitool', 'info', mac],
                capture_output=True,
                text=True
            )
            
            match = re.search(r'Class: (0x[0-9a-f]+)', result.stdout)
            if match:
                class_code = match.group(1)
                return self.parse_class_code(class_code)
            
        except:
            pass
        
        return 'Unknown'
    
    def parse_class_code(self, class_code):
        """Parsear classe de dispositivo Bluetooth"""
        # Classes principais
        major_classes = {
            0x00: 'Miscellaneous',
            0x01: 'Computer',
            0x02: 'Phone',
            0x03: 'LAN/Network Access Point',
            0x04: 'Audio/Video',
            0x05: 'Peripheral',
            0x06: 'Imaging',
            0x07: 'Wearable',
            0x08: 'Toy',
            0x09: 'Health'
        }
        
        class_int = int(class_code, 16)
        major_class = (class_int >> 8) & 0x1F
        
        return major_classes.get(major_class, 'Unknown')
    
    def test_rssi(self, mac):
        """Testar intensidade do sinal"""
        print(f"[*] Medindo RSSI para {mac}")
        
        try:
            result = subprocess.run(
                ['hcitool', 'rssi', mac],
                capture_output=True,
                text=True
            )
            
            match = re.search(r'RSSI return value: (-?\d+)', result.stdout)
            if match:
                rssi = int(match.group(1))
                print(f"    RSSI: {rssi} dBm")
                
                if rssi > -50:
                    print("    Qualidade: Excelente")
                elif rssi > -70:
                    print("    Qualidade: Boa")
                elif rssi > -90:
                    print("    Qualidade: Regular")
                else:
                    print("    Qualidade: Fraca")
                
                return rssi
            
        except:
            pass
        
        return None
    
    def generate_report(self):
        """Gerar relatório de diagnóstico"""
        print("\n" + "="*60)
        print("RELATÓRIO DE DIAGNÓSTICO BLUETOOTH")
        print("="*60)
        
        print("\n[ADAPTADOR]")
        for key, value in self.adapter_info.items():
            print(f"  {key}: {value}")
        
        print(f"\n[DISPOSITIVOS] ({len(self.devices)})")
        for device in self.devices:
            device_class = self.get_device_class(device['address'])
            print(f"\n  {device['address']}: {device['name']}")
            print(f"    Classe: {device_class}")
            self.test_rssi(device['address'])
        
        print("\n" + "="*60)

# Exemplo
diag = BluetoothDiagnostic()
if diag.check_adapter():
    diag.scan_devices(5)
    diag.generate_report()
```

***

## 🛡️ **Hardening e Mitigação**

### **Checklist de Segurança para PAN**

```yaml
Hardening Bluetooth:
  - [ ] Desabilitar Bluetooth quando não em uso
  - [ ] Configurar dispositivo como "Não Detectável"
  - [ ] Usar Secure Simple Pairing (SSP)
  - [ ] Habilitar criptografia de link
  - [ ] Utilizar Address Randomization
  - [ ] Remover dispositivos pareados antigos
  - [ ] Atualizar firmware regularmente

Proteções BLE:
  - [ ] Usar Just Works apenas para dispositivos confiáveis
  - [ ] Implementar autenticação de emparelhamento
  - [ ] Validar dados recebidos via GATT
  - [ ] Limitar características críticas
  - [ ] Implementar timeouts de conexão

Proteções Zigbee:
  - [ ] Usar chave de rede forte
  - [ ] Habilitar criptografia de payload
  - [ ] Desabilitar formação de rede não autorizada
  - [ ] Atualizar chaves periodicamente
  - [ ] Isolar rede Zigbee de outras redes

Proteções NFC:
  - [ ] Usar cartões com criptografia
  - [ ] Proteger UIDs de cartões
  - [ ] Implementar autenticação de tag
  - [ ] Usar comunicação segura (NFC-SEC)
  - [ ] Bloquear clonagem de tags
```

### **Script de Hardening Bluetooth**

```bash
#!/bin/bash
# bt_hardening.sh

echo "=== Hardening Bluetooth ==="

# 1. Desabilitar Bluetooth se não necessário
systemctl stop bluetooth
systemctl disable bluetooth

# 2. Configurar Bluetooth com segurança
cat >> /etc/bluetooth/main.conf << EOF
[General]
# Desabilitar descoberta
DiscoverableTimeout = 0
# Desabilitar scanning automático
AutoConnect = false
# Habilitar apenas emparelhamentos seguros
SecureSimplePairing = true
# Habilitar randomização de endereço
Privacy = true

[Policy]
# AutoEnable (não iniciar automaticamente)
AutoEnable = false
EOF

# 3. Configurar permissões
chmod 600 /etc/bluetooth/main.conf

# 4. Remover dispositivos pareados antigos
bluetoothctl devices | grep Device | cut -d' ' -f2 | while read mac; do
    bluetoothctl remove $mac
done

# 5. Configurar iptables para Bluetooth
# Bloquear conexões Bluetooth não autorizadas
iptables -A INPUT -i bluetooth -j DROP
iptables -A OUTPUT -o bluetooth -j ACCEPT

echo "[+] Hardening Bluetooth concluído"
```

***

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

### **Resumo Técnico**

```yaml
PAN (Personal Area Network):
  ✅ Conexão de dispositivos pessoais
  ✅ Baixo consumo de energia
  ✅ Baixo custo de implementação

Desafios de segurança:
  ❌ Protocolos frequentemente inseguros por padrão
  ❌ Emparelhamento pode ser vulnerável
  ❌ Dispositivos IoT podem ter firmware desatualizado
  ❌ Ataques de proximidade

Boas Práticas:
  - Desabilitar quando não em uso
  - Usar versões recentes dos protocolos
  - Manter firmware atualizado
  - Remover dispositivos pareados antigos
```

### **Recomendações Finais**

1. **Para Usuários**
   * Desabilitar Bluetooth quando não estiver usando
   * Não aceitar emparelhamentos desconhecidos
   * Manter dispositivos atualizados
   * Remover dispositivos pareados antigos
2. **Para Administradores**
   * Implementar políticas de uso de Bluetooth
   * Monitorar dispositivos conectados
   * Atualizar firmware de dispositivos
   * Configurar tempos limite de descoberta
3. **Para Desenvolvedores**
   * Implementar Secure Simple Pairing
   * Usar criptografia forte
   * Validar entrada de dados
   * Implementar timeouts adequados


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/conceitos/redes/geoposicionamento-de-redes/pan.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.
