18  Bluetooth Security Labs

In 60 Seconds

BLE security requires defense-in-depth: link-layer encryption via pairing is necessary but not sufficient. Production deployments need application-layer authorization, secure firmware updates, rate limiting against brute-force attacks, and physical security considerations covering the entire device lifecycle from manufacturing to decommissioning.

Key Concepts
  • BLE Security Lab Tools: nRF Sniffer (passive capture), btlejack (active BLE MITM/sniff), Wireshark BLE dissector, nRF Connect (GATT inspection), crackle (legacy BLE key recovery)
  • MITM Attack on Just Works: Passive attacker captures BLE 4.x Just Works pairing exchange; crackle tool recovers TK (always 0 for Just Works) and derives LTK from STK offline
  • BLE Fuzzing: Sending malformed ATT/GATT PDUs (invalid handle ranges, out-of-bounds characteristic values) to test server input validation; tools include BLEFuzz, Sweyntooth PoC
  • SWEYNTOOTH Vulnerability: Family of 2021 BLE vulnerabilities in multiple vendor SDKs enabling crash, lockup, or arbitrary code execution via malformed Link Layer packets
  • Passive Reconnaissance: BLE advertisement sniffing with ubertooth-btle or nRF Sniffer to enumerate nearby devices, their services (via extended advertising or connection), and RSSI for location estimation
  • Defense-in-Depth for BLE: Layered security approach: LE Secure Connections pairing + encrypted transport + application-layer authentication + firmware signing + OTA update monitoring
  • BLE Penetration Testing Methodology: Enumerate (advertising sniff) → Identify (service discovery) → Probe (characteristic fuzzing) → Exploit (known CVEs) → Persist (firmware modification)
  • Security Hardening Checklist: Disable Just Works for sensitive devices; enforce minimum security mode; validate all characteristic writes server-side; sign firmware images; use RPA for privacy
Minimum Viable Understanding

BLE security must be implemented in layers (defense-in-depth): link-layer encryption via authenticated pairing is necessary but not sufficient. Production deployments need application-layer authorization for sensitive commands, secure firmware updates (secure boot), rate limiting against brute-force attacks, and physical security considerations. Attacks can occur at every lifecycle stage – from manufacturing supply chain to device decommissioning – so security planning must cover the entire device lifetime.

18.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Implement BLE Security in Code: Build and test secure vs insecure BLE configurations on ESP32, comparing encrypted vs plaintext data transmission
  • Design Defense-in-Depth Architectures: Construct multi-layer security schemes for BLE IoT deployments covering link, application, and firmware layers
  • Analyze Attack Vectors: Diagnose vulnerability windows throughout the device lifecycle, from manufacturing supply chain to decommissioning
  • Evaluate Pairing Method Trade-offs: Assess the security guarantees of Just Works, Passkey Entry, Numeric Comparison, and OOB against realistic threat models
  • Configure Rate Limiting Defenses: Apply brute-force lockout logic and calculate the time-to-crack improvement achieved by rate limiting

These labs give you hands-on experience with Bluetooth security – scanning for nearby devices, analyzing pairing processes, and understanding how to defend against common attacks. Think of it as learning home security by actually testing locks and alarm systems, so you understand both how they work and how they can be strengthened.

“Security is not optional – it is essential!” declared Max the Microcontroller, putting on a virtual detective hat. “In these labs, we will build both secure and insecure BLE configurations so you can see exactly what happens when security is missing.”

Sammy the Sensor asked nervously, “What kind of attacks should I worry about?” Max listed the threats. “Eavesdropping – someone listening to your unencrypted data. Man-in-the-middle – someone pretending to be a trusted device. Replay attacks – someone recording your commands and playing them back later. And brute force – someone guessing your pairing PIN.”

“The defense is layers!” said Lila the LED. “Link-layer encryption from pairing is the first layer. But that is not enough. Add application-layer authorization so that even if someone pairs, they still need a password to unlock sensitive commands. Then add rate limiting so brute-force attempts get blocked after a few failures.”

Bella the Battery brought up a point often overlooked. “Security has a lifecycle! From manufacturing where keys are provisioned, through deployment where pairing happens, all the way to decommissioning where you must wipe all stored keys. If you sell a used smart lock without factory-resetting it, the previous owner might still have valid keys.”

18.2 Prerequisites

Before diving into this chapter, you should be familiar with:

18.3 Interactive Lab: BLE Security Demonstration

18.3.1 Lab Objective

Explore how different BLE security modes affect data transmission and device pairing. This hands-on lab demonstrates:

  • Secure pairing with PIN verification
  • Encrypted vs unencrypted data transmission
  • MAC address randomization (privacy feature)
  • Security flags in BLE advertising

18.3.2 What You’ll Build

An ESP32 BLE security demonstration that shows:

  1. Secure mode: Requires pairing with PIN, encrypts all data
  2. Insecure mode: Accepts any connection, transmits data in plaintext
  3. Security indicators: Visual feedback showing security state

18.3.3 Hardware Requirements

For Wokwi Simulator:

  • ESP32 DevKit v1
  • LED (Red = Insecure, Green = Secure)
  • Push button (toggle security modes)
  • No physical hardware needed!

For Real Hardware:

  • ESP32 DevKit v1
  • 2x LEDs (Red + Green)
  • 2x 220 Ohm resistors
  • Push button
  • Breadboard + jumper wires

18.3.4 Circuit Diagram

Circuit wiring diagram for ESP32 BLE security demo: ESP32 DevKit connected to green LED on GPIO 4 (secure mode), red LED on GPIO 2 (insecure mode), and push button on GPIO 5 for toggling modes
Figure 18.1: ESP32 BLE Security Lab Circuit Wiring

18.3.5 Lab Code: BLE Security Demo

Key Code Sections:

Security Callbacks – handle pairing PIN display and authentication:

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLE2902.h>

#define DEVICE_NAME "SecureIoTDevice"
#define SERVICE_UUID        "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"

bool secureMode = true;
uint32_t securityPIN = 123456;

class MySecurityCallbacks : public BLESecurityCallbacks {
  uint32_t onPassKeyRequest() { return securityPIN; }
  void onPassKeyNotify(uint32_t pass_key) {
    Serial.printf("Pairing PIN: %06d\n", pass_key);
  }
  bool onConfirmPIN(uint32_t pass_key) { return true; }
  bool onSecurityRequest() { return true; }
  void onAuthenticationComplete(esp_ble_auth_cmpl_t auth_cmpl) {
    Serial.println(auth_cmpl.success ? "Auth SUCCESS" : "Auth FAILED");
  }
};

Security Configuration – the critical setup difference between secure and insecure modes:

void configSecurity() {
  if (secureMode) {
    BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);
    BLEDevice::setSecurityCallbacks(new MySecurityCallbacks());

    // Require MITM-protected pairing with bonding
    esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND;
    esp_ble_io_cap_t iocap = ESP_IO_CAP_OUT; // Display PIN
    uint8_t key_size = 16; // 128-bit AES key

    esp_ble_gap_set_security_param(
        ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t));
    esp_ble_gap_set_security_param(
        ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t));
    esp_ble_gap_set_security_param(
        ESP_BLE_SM_MAX_KEY_SIZE, &key_size, sizeof(uint8_t));
  } else {
    // Just Works -- no MITM protection, vulnerable to eavesdropping
    BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT_NO_MITM);
  }
}

Data Transmission Loop – observe encrypted vs. plaintext output:

void loop() {
  if (deviceConnected) {
    static unsigned long lastUpdate = 0;
    if (millis() - lastUpdate > 5000) {
      lastUpdate = millis();
      float temp = 20.0 + (random(0, 100) / 10.0);
      String data = "Temp: " + String(temp, 1) + " C";
      pCharacteristic->setValue(data.c_str());
      pCharacteristic->notify();
      Serial.println(secureMode ? "Encrypted: " + data
                                : "PLAINTEXT: " + data);
    }
  }
  delay(100);
}

18.3.6 Lab Challenges

Try these experiments to understand BLE security:

18.3.6.1 Challenge 1: Compare Security Modes

Task: Connect to the device in both secure and insecure modes using nRF Connect app.

Steps:

  1. Upload code in secure mode (default)
  2. Open nRF Connect app on phone
  3. Scan for “SecureIoTDevice”
  4. Attempt to connect - Prompted for PIN: 123456
  5. After entering PIN, observe encrypted connection
  6. Press button to restart in insecure mode
  7. Connect again - No PIN required
  8. Compare connection process

Question: Which mode connected faster? Why?

Answer

Insecure mode is faster because it skips authentication. However, this speed comes at a security cost:

Secure mode (slow but safe):

  • Connection includes a pairing/authentication step
  • Requires a user interaction step (PIN in this demo)
  • Uses link-layer encryption after pairing (AES-CCM 128-bit)
  • MITM protection depends on the pairing method

Insecure mode (fast but dangerous):

  • Connection is typically faster (no pairing step)
  • No verification needed
  • Data sent in plaintext
  • Vulnerable to eavesdropping

Real-world trade-off: For public sensor data, plaintext might be acceptable. For control actions or sensitive data, prefer authenticated pairing and add application-layer authorization.

18.3.6.2 Challenge 2: Intercept Plaintext Data

Task: Use Wireshark or nRF Sniffer to capture BLE packets and view unencrypted data.

Requirements:

  • A BLE sniffer (e.g., nRF52840 dongle running nRF Sniffer)
  • Wireshark (with the appropriate BLE capture integration)
  • nRF Sniffer firmware/tools

Steps:

  1. Start BLE packet capture with nRF Sniffer
  2. Connect phone to ESP32 in insecure mode
  3. Observe data packets in Wireshark
  4. Find characteristic write/notify packets
  5. View temperature data in plaintext: “Temp: 24.5 C”
  6. Repeat in secure mode
  7. Observe encrypted packets (unreadable hex data)

Question: What information can an attacker learn from plaintext BLE packets?

Answer

Without encryption, an eavesdropper can see the payloads and metadata:

  • Device address/identifiers (tracking risk if privacy features aren’t used)
  • Sensor data in plaintext (e.g., temperature strings)
  • Service/Characteristic UUIDs (can reveal device type/capabilities)
  • Connection patterns (timing, frequency, active periods)
  • Commands sent to the device (replay may be possible)

With encryption (secure mode), an eavesdropper typically only sees:

  • Packet timing/length and protocol metadata
  • Addresses that may be randomized (privacy feature)
  • Nothing about actual data content

Privacy lesson: Metadata leakage is real! Even encrypted, BLE reveals when devices communicate.

18.3.6.3 Challenge 3: Implement PIN Brute-Force Protection

Task: Modify the code to lock out attackers after 3 failed pairing attempts.

Requirements:

  • Track failed pairing attempts
  • Lock device for 60 seconds after 3 failures
  • Log all pairing attempts with timestamps
Solution Code
// Add to global variables
int failedAttempts = 0;
unsigned long lockoutUntil = 0;

// Modify onAuthenticationComplete in MySecurityCallbacks
void onAuthenticationComplete(esp_ble_auth_cmpl_t auth_cmpl) {
  // Check if device is locked out
  if (millis() < lockoutUntil) {
    Serial.println("Device locked due to failed attempts");
    Serial.printf("   Unlock in: %d seconds\n", (lockoutUntil - millis()) / 1000);
    return;
  }

  if (auth_cmpl.success) {
    Serial.println("Authentication SUCCESSFUL");
    failedAttempts = 0;  // Reset counter
    digitalWrite(LED_SECURE, HIGH);
  } else {
    failedAttempts++;
    Serial.printf("Authentication FAILED (Attempt %d/3)\n", failedAttempts);

    if (failedAttempts >= 3) {
      lockoutUntil = millis() + 60000;  // Lock for 60 seconds
      Serial.println("TOO MANY FAILED ATTEMPTS - LOCKED FOR 60 SECONDS");
      digitalWrite(LED_INSECURE, HIGH);
      failedAttempts = 0;  // Reset for next cycle
    }
  }
}

Security improvement: This prevents PIN brute-force attacks by limiting attempts.

With a 6-digit PIN, an attacker has 1 million possible combinations (\(10^6 = 1,000,000\)). If allowed unlimited attempts:

\[\text{Average attempts to guess} = \frac{1,000,000}{2} = 500,000\]

Worked example: With a 3-attempt lockout and 60-second penalty, an attacker trying one PIN pattern needs: - 3 attempts × 1 second per attempt = 3 seconds - Wait 60 seconds (lockout) - Total: 63 seconds per 3 attempts - Time to exhaust all combinations: \(\frac{1,000,000}{3} \times 63 \text{ seconds} = 21,000,000 \text{ seconds} \approx 243 \text{ days}\)

Compare to unlimited attempts: \(1,000,000 \text{ seconds} = 11.6 \text{ days}\). The lockout increases attack time by 21×.

18.3.6.4 Challenge 4: Advanced - Implement Secure Boot

Task: Ensure the ESP32 firmware cannot be tampered with by enabling secure boot.

Why this matters: Even with secure BLE pairing, if an attacker can reflash the ESP32 with malicious firmware (e.g., one that leaks the PIN or disables encryption), all security is lost.

Implementation Guide

Secure Boot prevents:

  • Flashing unauthorized firmware
  • Booting malicious code
  • Firmware tampering

Implementation steps (ESP32-IDF):

# 1. Generate signing key
espsecure.py generate_signing_key secure_boot_signing_key.pem

# 2. Enable secure boot in menuconfig
idf.py menuconfig
# Navigate to: Security features - Enable secure boot in bootloader

# 3. Build and flash once (this burns eFuses - irreversible!)
idf.py build
esptool.py --port /dev/ttyUSB0 write_flash @flash_args

# 4. After first boot, secure boot is enabled
# Future firmware must be signed with your key

WARNING: Secure boot is PERMANENT. If you lose your signing key, the device may become effectively unupdatable.

Production deployment checklist:

  • Store signing key in hardware security module (HSM)
  • Implement firmware update mechanism with signed images
  • Test thoroughly before burning eFuses
  • Keep multiple backup copies of signing key (encrypted, offline)

18.3.7 Lab Takeaways

After completing this lab, you should understand:

  1. Pairing modes matter more than encryption strength
    • Even strong link encryption won’t help if pairing is unauthenticated (“Just Works”)
    • Prefer authenticated pairing (Numeric Comparison or OOB; Passkey Entry when appropriate)
  2. Security vs. Convenience trade-off
    • Secure mode: Slower connection, better security
    • Insecure mode: Faster connection, vulnerable to attacks
    • Choose based on data sensitivity and threat model
  3. Defense in depth
    • BLE security (pairing + encryption)
    • Application security (authentication/authorization)
    • Physical security (tamper-evident casing)
    • Firmware security (secure boot)
  4. Real-world deployment considerations
    • For safety- or high-value devices: use authenticated pairing and plan for revocation
    • For public sensors (weather, parking): Insecure mode may be acceptable
    • For payment systems: Add NFC/QR out-of-band pairing
  5. Attack surface extends beyond wireless
    • Attacker with physical access can reflash firmware
    • Use secure boot + tamper detection for critical devices
    • Implement rate limiting to prevent brute-force

Experiment with lockout parameters to see how rate limiting defends against brute-force attacks on BLE pairing PINs.

18.4 Defense-in-Depth Security Layers

Secure BLE deployments require protection at multiple layers:

Concentric layer diagram showing BLE defense-in-depth security: physical security, network perimeter, link layer encryption, application authentication, and data protection at the core
Figure 18.2: Defense-in-depth layers for BLE security showing how each layer blocks different attack vectors.

18.5 BLE Attack Timeline Visualization

Understanding when attacks can occur helps prioritize defenses:

Timeline showing BLE attack windows during device lifecycle: manufacturing (supply chain attacks), deployment (pairing attacks), operation (eavesdropping, MITM), and decommissioning (data recovery)
Figure 18.3: Attack timeline showing vulnerability windows throughout the BLE device lifecycle.

18.7 Knowledge Check

18.7.1 Knowledge Check: Defense-in-Depth for BLE

18.7.2 Knowledge Check: BLE Attack Surface

Common Mistake: Ignoring Bonded Key Storage Security

The Scenario: A smart lock manufacturer implements authenticated BLE pairing with Numeric Comparison (strong MITM protection) but stores bonded LTK keys in unencrypted flash memory. After deployment, a security researcher extracts the keys using a $20 USB debugger and gains permanent access to all locks.

What Went Wrong: Secure pairing means nothing if the resulting keys are not securely stored. Many developers focus on the pairing ceremony (Numeric Comparison, OOB) but neglect key storage, assuming the device’s physical security is sufficient.

Vulnerable Implementation (ESP32):

// WRONG: Keys stored in plain NVS (non-volatile storage)
esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t));
// Keys saved to flash automatically - anyone with USB can read them!

Attack Vector:

  1. Attacker removes smart lock cover (2 screws)
  2. Connects USB debugger (ST-Link, J-Link) to exposed JTAG/SWD pins
  3. Dumps flash memory contents (5 minutes)
  4. Extracts bonded keys from known NVS partition offsets
  5. Creates spoofed central device using extracted keys
  6. Locks now accept attacker’s device as trusted

Secure Implementation (use hardware-backed keystore):

// CORRECT: Store keys in secure element or encrypted flash
esp_ble_gap_config_adv_data_raw(adv_data, sizeof(adv_data));

// Enable flash encryption (prevents debugger readout)
// Set via menuconfig: Security features → Enable flash encryption on boot
// WARNING: Irreversible after first boot!

// OR: Use external secure element (ATECC608, DS28E38)
// Keys never leave secure chip, all crypto operations inside

Defense Checklist:

Real-World Cost: A Kickstarter-funded smart lock ($2.5M raised) was recalled 6 months after launch due to this exact vulnerability. Refunds and reputation damage cost the company $4M. Hardware security features cost ~$1-2 per unit.

Concept Relationships
Concept Relates To Why It Matters
Defense-in-Depth Multiple Security Layers Link encryption alone is insufficient — application authorization, secure boot, and protected key storage are all required
Attack Timeline Lifecycle Security Vulnerabilities exist from manufacturing supply chain through device decommissioning
Secure Boot Firmware Integrity Prevents malicious firmware reflash that could disable encryption or leak bonded keys
LE Secure Connections (ECDH) Key Agreement Security Replaces legacy pairing’s weak key derivation with ECDH, protecting past sessions from retroactive decryption
Key Storage Protection Bonding Security Hardware-backed keystores (flash encryption, secure element) prevent LTK extraction via JTAG/SWD debugger

18.8 See Also

18.9 Summary

This chapter provided hands-on experience with BLE security:

  • Interactive Lab: ESP32-based demonstration comparing secure and insecure BLE modes
  • Security Challenges: PIN brute-force protection, packet interception analysis, secure boot implementation
  • Defense-in-Depth: Multi-layer security architecture from physical to data protection
  • Attack Timeline: Vulnerability windows across device lifecycle (manufacturing, deployment, operation, decommissioning)
  • Visual Gallery: Reference diagrams for pairing, encryption, and protocol stack security

Common Pitfalls

BLE security testing that focuses only on pairing and encryption misses vulnerabilities at other layers: unvalidated GATT write values causing buffer overflows, unauthenticated command execution (e.g., factory reset via GATT Write without security), or insecure bootloader allowing unsigned firmware. Test the complete attack surface including: physical access, JTAG/debug interfaces, UART console, GATT command handling, and OTA update integrity.

Using the BLE device MAC address as an authentication factor is insecure — MAC addresses are transmitted in cleartext in advertising packets and can be spoofed in software. An attacker can clone a trusted device’s MAC address to impersonate it. Authentication must use cryptographic methods: LESC pairing, application-layer token exchange, or certificate-based authentication, never MAC address matching.

When a bonded device is lost, stolen, or suspected compromised, the LTK stored in the remaining device’s NVS must be immediately deleted to prevent unauthorized reconnection. IoT devices without a mechanism to remotely revoke bonding keys (via cloud command + BLE or local physical trigger) remain permanently open to the lost device reconnecting with the stolen key. Always implement a key revocation path in production firmware.

An OTA DFU implementation that accepts unsigned firmware images allows an attacker within BLE range to flash arbitrary malicious firmware. All production BLE OTA implementations must verify firmware image signatures (ECDSA or RSA) before applying updates. The public key for signature verification should be stored in a protected flash region that cannot be overwritten by OTA updates themselves.

18.10 What’s Next

Chapter What You Will Learn Why It Matters
Bluetooth Comprehensive Review Integrated Bluetooth concepts with case studies and assessments Consolidates pairing, encryption, and defense knowledge into a single review
Bluetooth Security: Pairing Methods Deep dive into Just Works, Passkey Entry, Numeric Comparison, and OOB Selecting the right pairing method is the foundation of BLE security
Bluetooth Security: Encryption and Key Management AES-CCM operation, LTK/STK/IRK hierarchy, and key distribution Understanding the key lifecycle is essential for diagnosing and fixing security gaps
IoT Security Threats and Fundamentals Threat modelling, attack taxonomies, and IoT-specific vulnerabilities Contextualizes BLE attack vectors within the broader IoT security landscape
Hardware Security for IoT Secure elements, eFuse protection, and hardware-backed key storage The secure boot and flash-encryption techniques from Challenge 4 are explained in depth here