Chapters

BLE Attack Labs: Security Review

bluetooth-ble
bt
security
defense

This lab belongs to BLE Encryption: Secure Pairing

Start With the Decision

This section: Start With the Decision — A Bluetooth Low Energy (BLE) lock can pair, or set up link keys, and still fail under attack.

A Bluetooth Low Energy (BLE) lock can pair, or set up link keys, and still fail under attack. Test the lock PIN or pairing passkey used by this design, its stored keys, and the recovery path after a lost phone, failed link, or key change.

Route Overview

This section: Route Overview — This is part 1 of 2.

This is part 1 of 2. Continue with BLE Attack Labs: PIN Brute-Force Timing.

Part Objectives

This section: Part Objectives

  • Test lab security review pattern against named attack, failure, and recovery cases.
  • Validate putting numbers to it with a concrete scenario and pass criteria.
In 60 Seconds

Begin with one protected action. A phone asks a lock to open. The lock must know which phone is asking. It must also know whether that user may open this door. A hidden radio exchange does not answer both questions.

Write the allowed case first. Name the user. Name the device. Name the action. Set the time and place limits. Then write the cases that must fail. Include a lost phone and an old key.

A lab should make each check visible. Try an unknown phone. Try a changed command. Try the same command twice. Try many wrong guesses. Break the link during the action. Save what the device did.

Add guards in layers. Protect the local exchange. Check permission inside the product. Limit repeated guesses. Accept new device software only from a trusted source. Protect stored secrets. Provide a safe way to remove access.

Repeat the same tests after each change. A fix passes only the named case. It does not prove that every path is safe. Record the device version, setup, action, and result. Keep failed cases in the final report.

This quick view uses one lock. Real products cross phones, online services, and support work. Practitioner tests make those paths repeatable. Under the Hood examines data permissions, key life, write checks, and the gaps that a successful pairing can hide. 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 and Passive Capture of Just Works: In LE Legacy Pairing with Just Works, the temporary key is zero, so a captured pairing exchange can expose the session and long-term keys. LE Secure Connections Just Works resists passive key recovery but remains vulnerable to an active man-in-the-middle during pairing.
  • BLE Fuzzing: Sending malformed ATT/GATT PDUs (invalid handle ranges, out-of-bounds characteristic values) to test server input validation; public research tools and vendor test harnesses are useful references
  • BLE Stack Vulnerabilities: Published BLE implementation bugs have caused crashes, lockups, and code execution in vendor SDKs, so firmware patching and input validation remain part of the security plan
  • 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
  • Bluejacking: Low-severity nuisance attack that sends unsolicited messages or data to a discoverable device; mitigate by disabling discoverability outside of an intentional pairing window rather than treating it as a serious threat on its own

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.

Learning Objectives

This section: 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
Chapter Roadmap
  • In 60 Seconds
  • Key Concepts
  • Quick Check: Bluetooth Security Boundary
  • Minimum Viable Understanding
  • For Beginners: Labs and Defense-in-Depth
  • Lab Security Review Pattern
  • Prerequisites
  • Interactive Lab: BLE Security Demonstration
  • Checkpoint: Lab Boundary
  • Checkpoint: Capture Evidence
  • Putting Numbers to It
  • Checkpoint: Rate-Limit Math
  • Knowledge Check: Lab Concepts

Use this lab as a security review in four passes:

  1. First build the secure/insecure ESP32 comparison so pairing, encryption, and the visible device state are testable.
  2. Then capture the radio evidence: which payloads become plaintext, which packets stay opaque, and which metadata still leaks.
  3. Next add online-abuse controls such as the 3-failure, 60-second lockout and check the math instead of trusting the label.
  4. Finally widen the defense boundary to firmware signing, bonded-key storage, ATT permissions, application authorization, and recovery.

The checkpoints below mark each pass so the lab record shows what changed before another layer is added.

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.

Use each lab as a security review checklist, not just a code exercise:

  • Compare secure and insecure BLE modes so the pairing, encryption, and user-verification differences are visible.
  • Capture only your own lab device traffic, then confirm what an eavesdropper can and cannot read.
  • Add application-layer authorization for sensitive commands, even after a device is paired.
  • Rate-limit repeated authentication failures so PINs and short secrets cannot be guessed quickly.
  • Protect firmware, stored keys, debug ports, and decommissioning flows because wireless security fails if the device can be reflashed or cloned.

Prerequisites

This section: Prerequisites

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

Interactive Lab: BLE Security Demonstration

This section: Interactive Lab: BLE Security Demonstration

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

What You’ll Build

An ESP32 BLE security demonstration that shows:

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

Hardware Requirements

For Wokwi GPIO practice only:

  • ESP32 DevKit v1
  • LED (Red = Insecure, Green = Secure)
  • Push button (toggle security modes)
  • No physical hardware is needed to rehearse the LED and button logic. BLE pairing, encryption, and packet capture require your own ESP32 and radio tools.

For Real Hardware:

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

Circuit Diagram

Before applying power, inspect Figure 1 to trace every current path and input reference. The diagram makes the secure/insecure indicators visually distinct while keeping both LEDs and the mode button on one common ESP32 ground.

ESP32 BLE security lab wiring diagram: GPIO 4 drives a green LED for secure mode, GPIO 2 drives a red LED for insecure mode, GPIO 5 reads the toggle button, and the LEDs and button share ESP32 ground.
Figure 1: ESP32 BLE security lab circuit showing GPIO 4 wired through a 220 ohm resistor to the green secure-mode LED, GPIO 2 wired through a 220 ohm resistor to the red insecure-mode LED, GPIO 5 wired to the mode-toggle push button, and all returns tied to ESP32 ground.

Read Figure 1 from GPIO 4 through its 220-ohm resistor and green LED to ground, then repeat the check from GPIO 2 through the red branch. Finally follow GPIO 5 to the push button and verify its return and configured pull state. That order connects the physical build to the software modes below: a reversed LED, missing resistor, or floating input can produce misleading “security” observations even when the BLE code is correct.

Lab Code: BLE Security Demo

Open the simulator directly: Wokwi ESP32 starter project.

Use the starter project as a safe place to build the demo. Keep the implementation focused on these checkpoints:

  • Security callbacks: return a demo passkey, display it in the serial console, confirm pairing requests, and log whether authentication succeeds or fails.
  • Secure mode configuration: require LE Secure Connections with MITM protection and bonding, use a 128-bit key size, and set the device I/O capability to match the passkey workflow.
  • Insecure mode configuration: deliberately allow a no-MITM or unauthenticated path only for comparison. Label this mode clearly so it is never mistaken for production code.
  • Notification loop: publish the same sample temperature value in both modes, then compare what a sniffer can read from encrypted and plaintext connections.
  • State indicators: use the LEDs and serial log to show whether the device is waiting for pairing, paired securely, or running in the insecure test mode.

This section:

Radio Remi, Wireless and radio domain expertCheckpoint: Lab Boundary

You now know:

  • The lab device has two intentionally different modes: secure mode asks for PIN 123456, while insecure mode accepts a connection without that pairing step.
  • The ESP32 setup is not just a demo circuit; the red/green LEDs, serial log, and phone connection flow are evidence that the mode changed.
  • The same sample temperature notification appears in both paths, which gives the packet-capture challenge a fair before/after comparison.

This section: — With the lab boundary explicit, the next question is what an observer can see from outside the device.

With the lab boundary explicit, the next question is what an observer can see from outside the device.

Lab Challenges

Try these experiments to understand BLE security:

Challenge 1: Compare Security Modes

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

Run it: The connection you are about to compare is a walk through the BLE link-layer states, so trace it first in the state-machine workbench below. Step the peripheral from Standby into Advertising, then bring a central through Scanning and Initiating until the Connection state forms — the same path nRF Connect drives when it scans for and connects to the device. Note that both secure and insecure modes traverse these link states; the difference is the pairing and encryption step layered on top once the connection exists, which is what makes the secure connection slower.

Step 1: Compare pairing paths on your own hardware
  • In the BLE state workbench above, press Step twice and read CONNECT_IND: the controller reaches a link before pairing starts. This browser workbench was run here; its readout said “Exchange data in scheduled connection events on data channels.”
  • Flash the secure-mode firmware onto your own ESP32, then open nRF Connect on the phone and scan for SecureIoTDevice. Wokwi’s GPIO demonstration cannot establish a real BLE radio link.
  • Tap Connect and enter demo PIN 123456 if the firmware actually requests it. Save the app’s pairing and security status; the prompt is expected from the described demo, not an observation made here.
  • Disconnect, press the mode button, verify the insecure LED or serial state, and reconnect. Record whether the phone now omits authentication and how long each connection takes.
  • Compare the two phone records: both use the same advertising-to-connection path, while only the secure path should add authenticated pairing and encryption. The phone and ESP32 pairing were not run here.

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.

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
Step 2: Compare plaintext and encrypted captures on your own hardware
  • Start nRF Sniffer on your dongle, select its capture interface in Wireshark, and save the trace before connecting. This requires a real BLE sniffer and was not run here.
  • Put the ESP32 into insecure mode, connect from the phone, and filter for the demo characteristic’s ATT writes or notifications.
  • Record the packet number and bytes for the sample Temp: 24.5 C if that string is actually sent; it is an expected demo value, not a captured result in this lane.
  • Repeat with secure pairing and compare the same characteristic after encryption begins. Save packet numbers showing that the payload is no longer decoded as ordinary ATT data.
  • Record visible address behavior, packet lengths, and timing in both traces. Those metadata fields explain why encryption protects content without making a device invisible.

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)
  • No encrypted connection payload content; ordinary advertising data may still be readable

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

This section:

Radio Remi, Wireless and radio domain expertCheckpoint: Capture Evidence

You now know:

  • Insecure mode can expose the sample payload, such as Temp: 24.5 C, plus UUIDs, timing, connection patterns, and device identifiers.
  • Secure mode protects the payload with link encryption, but packet timing, packet length, and address behavior can still support tracking analysis.
  • The lab needs both traces in the record: one that proves plaintext risk and one that proves the mitigation changed what Wireshark can decode.

This section: — After capture, the attack becomes active: can repeated pairing attempts turn a short PIN into a practical online guessing path?

After capture, the attack becomes active: can repeated pairing attempts turn a short PIN into a practical online guessing path?

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

Step 3: Calculate the lockout budget, then test it on your own hardware

  • In a local Python terminal, calculate cycle = 3 * 1 + 60 for three one-second guesses and a sixty-second lockout.
  • The run here printed 3 guesses + 60 s lockout = 63 s; slowdown = 21x and 21,000,000 s = 243.1 days for one million guesses at three per cycle.
  • Add failedAttempts and lockoutUntil to the ESP32 authentication callback, following the solution outline below; log each failure with time and peer identity where available.
  • On your own ESP32, enter three wrong passkeys, try a fourth before 60 seconds elapse, then try again after expiry. The expected result is rejection during lockout and a fresh attempt afterward; this radio test was not run here.
  • Keep the arithmetic and radio logs separate. The calculation describes an idealized online rate, while real pairing behavior and recovery depend on the implemented firmware.
Solution Outline

Implement the lockout as a small state machine:

  • Add failedAttempts and lockoutUntil as persistent state.
  • At the start of the authentication callback, reject new pairing attempts while millis() < lockoutUntil.
  • On successful authentication, reset failedAttempts, clear any warning indicator, and log the accepted peer.
  • On failed authentication, increment failedAttempts and log the timestamp, peer address if available, and failure count.
  • When the failure count reaches 3, set lockoutUntil = millis() + 60000, turn on the warning indicator, and reset the counter for the next lockout window.

Security improvement: This does not make a weak PIN strong, but it changes brute-force guessing from a rapid online attack into a slow, noisy process that operators can detect.

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

Average attempts to guess=1,000,0002=500,000\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: 1,000,0003×63 seconds=21,000,000 seconds≈243 days\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 seconds=11.6 days1,000,000 \text{ seconds} = 11.6 \text{ days}. The lockout increases attack time by 21×.

This section:

Radio Remi, Wireless and radio domain expertCheckpoint: Rate-Limit Math

You now know:

  • A 6-digit PIN has 1,000,000 combinations, so the average guess lands after about 500,000 attempts.
  • With 3 tries followed by a 60-second penalty, each cycle costs 63 seconds and full exhaustion is about 21,000,000 seconds, or 243 days.
  • That is a 21x slowdown compared with 1,000,000 seconds, but it is still only an online friction control; sensitive products should avoid weak pairing choices in the first place.

This section: — Once the online attack is slowed, protect the firmware and stored secrets that could bypass pairing entirely.

Once the online attack is slowed, protect the firmware and stored secrets that could bypass pairing entirely.

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.

Step 4: Review the signed firmware path on your own hardware

  • In the ESP-IDF security menu for your exact board, record the secure-boot mode, signing-key location, firmware version, and planned update route before enabling irreversible settings.
  • Build and verify a signed image on a sacrificial development board, then save the boot log that accepts the signed image.
  • Test a deliberately unsigned or modified image on that board and record the bootloader rejection; do not infer this from BLE pairing success.
  • Confirm that the authorized update path still works after signing and that a protected backup key can restore the release process.
  • No eFuse, bootloader, or production board was accessed in this lane; the acceptance evidence must come from your own ESP32 and ESP-IDF logs.
Implementation Guide

Secure Boot prevents:

  • Flashing unauthorized firmware
  • Booting malicious code
  • Firmware tampering

Implementation steps (ESP32-IDF):

  • Generate a secure-boot signing key and store it outside the source repository.
  • Enable secure boot in idf.py menuconfig under the security features menu.
  • Build and flash a fully tested image only after confirming the device can still be recovered during development.
  • On first production boot, the relevant eFuses are burned and future firmware must be signed with the trusted key.

Warning: Secure boot is permanent on production devices. If you lose the 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)

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

Continue to the Next Part

This section: Continue to the Next Part — Carry this evidence into BLE Attack Labs: PIN Brute-Force Timing, which begins with Interactive: PIN Brute-Force Time Calculator.

Carry this evidence into BLE Attack Labs: PIN Brute-Force Timing, which begins with Interactive: PIN Brute-Force Time Calculator.