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
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
For Beginners: Bluetooth Security Labs
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.
Sensor Squad: Defending Our BLE Network
“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:
Task: Connect to the device in both secure and insecure modes using nRF Connect app.
Steps:
Upload code in secure mode (default)
Open nRF Connect app on phone
Scan for “SecureIoTDevice”
Attempt to connect - Prompted for PIN: 123456
After entering PIN, observe encrypted connection
Press button to restart in insecure mode
Connect again - No PIN required
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:
Start BLE packet capture with nRF Sniffer
Connect phone to ESP32 in insecure mode
Observe data packets in Wireshark
Find characteristic write/notify packets
View temperature data in plaintext: “Temp: 24.5 C”
Repeat in secure mode
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)
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 variablesint failedAttempts =0;unsignedlong lockoutUntil =0;// Modify onAuthenticationComplete in MySecurityCallbacksvoid onAuthenticationComplete(esp_ble_auth_cmpl_t auth_cmpl){// Check if device is locked outif(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.
Putting Numbers to It
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×.
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 keyespsecure.py generate_signing_key secure_boot_signing_key.pem# 2. Enable secure boot in menuconfigidf.py menuconfig# Navigate to: Security features - Enable secure boot in bootloader# 3. Build and flash once (this burns eFuses - irreversible!)idf.py buildesptool.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:
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)
Security vs. Convenience trade-off
Secure mode: Slower connection, better security
Insecure mode: Faster connection, vulnerable to attacks
Secure BLE deployments require protection at multiple layers:
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:
Figure 18.3: Attack timeline showing vulnerability windows throughout the BLE device lifecycle.
18.6 Visual Reference Gallery
Visual: Bluetooth Pairing Process
Bluetooth pairing key exchange
The pairing process establishes shared encryption keys between devices using one of four authentication methods.
Visual: Bluetooth Pairing Modes
Bluetooth pairing mode comparison
Pairing mode selection should match the security requirements of your application and the device’s I/O capabilities.
Visual: BLE State Machine
BLE connection state machine
Understanding BLE states helps identify attack surfaces and implement appropriate security controls at each stage.
Visual: Bluetooth Power Classes
Bluetooth power class and range
Power class affects not only range but also security perimeter - higher power means larger attack surface area.
Visual: Bluetooth Protocol Stack Security
BLE stack security layers
Security must be implemented at multiple stack layers - link encryption alone is insufficient for sensitive applications.
18.7 Knowledge Check
Auto-Gradable Quick 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:
Attacker removes smart lock cover (2 screws)
Connects USB debugger (ST-Link, J-Link) to exposed JTAG/SWD pins
Dumps flash memory contents (5 minutes)
Extracts bonded keys from known NVS partition offsets
Creates spoofed central device using extracted keys
// CORRECT: Store keys in secure element or encrypted flashesp_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
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
1. Testing Security Only at the BLE Protocol Layer
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.
2. Relying on Device Address as Authentication
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.
3. Not Revoking Bonding Keys After Security Incident
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.
4. Ignoring Firmware Update Authentication
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.