Chapters

12 BLE Pairing and MITM Defense

bluetooth-ble
bt
security
pairing

12.1 Start With the Story

A Matching Number Must Prove the Right Peer

Picture a nurse pairing a tablet with a medicine cabinet. Both screens show the same six digits. The nurse must know that the cabinet, not a nearby attacker’s device, helped create that number.

Bluetooth Low Energy, or BLE, is a short-range radio system. Pairing is the setup talk that creates shared secret material between two devices. The security reviewer should follow who speaks, what each device can display or enter, and what the person is asked to confirm.

Test the clean setup, a wrong number, a cancelled step, a repeated attempt, and a device with no useful screen. Record which method was chosen and whether it matches the real controls. A private radio link is not enough if it protects a link to the wrong peer.

This simple story leaves out the mathematics. Practitioner checks product flow and stored keys. Under the Hood explains commitments, key agreement, derived keys, and active relays.

Two screens show matching digits. The user action looks small, but the security story underneath includes commitments, ECDH, key derivation, authentication flags, and the difference between observing a number and proving the peer.

Read this deep dive as the machinery behind the decision. Follow the pairing phases slowly enough that each key, confirmation value, and capability assumption can be checked against the device flow.

This child chapter holds the deeper L2 material split out of Pairing Methods & MITM Protection. Use it when the learner already understands the pairing-method choice and needs to review why the protocol evidence works.

12.2 Protocol Evidence Checklist

Three protocol details decide whether a pairing review is complete:

  • Numeric Comparison vs active MITM: ECDH stops passive listeners, but only the displayed transcript check exposes an active relay that runs separate ECDH exchanges.
  • Passkey bit commitment: Passkey Entry protects the six-digit secret by committing to one passkey bit at a time instead of revealing the passkey as a reusable PIN.
  • f5 key derivation: LE Secure Connections derives usable keys from the ECDH DHKey; the raw ECDH result is not itself the link key.

12.3 Deep Dive: IO Capabilities, Legacy Pairing, and Numeric Comparison Evidence

The pairing method is not only a product preference. During the Pairing Request and Pairing Response, both devices declare their I/O capabilities: display, keyboard, Yes/No confirmation, and out-of-band support. The combination selects the association model, so the security review must prove the configured capability flags match the real hardware.

MethodRequired device capabilityMITM protectionReview evidence
Just WorksAt least one side cannot display, enter, or confirm a valueNoAccept only for low-risk public telemetry, or add application authorization before sensitive writes.
Passkey EntryOne side displays a fresh passkey and the other side enters itYesConfirm the passkey is random per attempt, short-lived, and never a fixed factory PIN.
Numeric ComparisonBoth sides display and confirm the same six-digit value under LE Secure ConnectionsYesVerify the firmware rejects fallback to Just Works for high-risk setup flows.
OOBA separate channel such as NFC, QR, wired provisioning, or setup tokenYes, if the side channel is bound to the deviceProve the user physically receives data from the device being commissioned, not from a nearby relay.

Legacy Pairing and LE Secure Connections also need separate evidence:

Security questionLE Legacy PairingLE Secure Connections
Key agreementShort Term Key derived from a weak Temporary KeyECDH on the P-256 curve
Passive eavesdropperA captured exchange can often be attacked offline, especially with Just WorksPublic keys alone do not reveal the shared secret
Numeric ComparisonNot availableAvailable

LE Secure Connections closes the passive-sniffer problem, but it does not automatically close the active man-in-the-middle problem. An active relay can run one ECDH exchange with the phone and a different ECDH exchange with the peripheral unless the user has a transcript check. Numeric Comparison gives that check: each device derives a six-digit verification value from the exchanged public keys and nonces, and the user confirms the values match. If the relay changed the transcript, the displays do not match and no trusted bond should be created.

A practical policy is therefore: require LE Secure Connections for sensitive products, require Numeric Comparison or OOB when first pairing grants control over locks, medication, vehicles, payment data, or industrial setpoints, and make the app explain a failed pairing as a security mismatch instead of silently retrying with Just Works.

12.4 Why Numeric Comparison Beats Active MITM

ECDH gives both devices a shared secret that a passive sniffer cannot compute from the public keys. That is necessary, but it is not enough. An active relay can stand between the phone and peripheral, run one ECDH exchange with the phone, run a second ECDH exchange with the peripheral, and forward application-looking traffic between two encrypted links.

Numeric Comparison adds a transcript check after the public-key and nonce exchange. Inspect Figure 12.1 to follow the commitment, nonce exchange, verification, and human confirmation in their security-critical order. If a relay substituted its own public keys, the two transcripts differ.

Sequence diagram with two lanes, Device A (initiator) and Device B (responder). Phase 1: both devices choose a random nonce (Na, Nb); Device B computes a confirmation value from both public keys and its own nonce. Phase 2: Device B sends the confirmation value to Device A, Device A sends nonce Na to Device B, Device B sends nonce Nb to Device A; Device A verifies the confirmation and aborts if it does not match. Phase 3: both devices compute a six-digit value (Va, Vb) from the shared public keys and nonces; the user compares the two displayed values, and pairing proceeds only if they match. A side panel explains why this defeats an active relay: the confirmation is committed before nonces are revealed, the six-digit value is bound to both devices’ keys and nonces, a relay running two separate ECDH exchanges cannot produce one confirmation valid on both links, and only the user’s comparison completes the check.
Figure 12.1: Numeric Comparison Authentication Stage 1: Device A and Device B each choose a random nonce, Device B computes a confirmation value from both public keys and its own nonce and sends it first, the two nonces are exchanged next, Device A verifies the confirmation and aborts on mismatch, both devices then compute a six-digit value from the shared public keys and nonces, and the user compares the two displayed values before pairing proceeds.

Read Figure 12.1 from the devices’ fresh nonces and Device B’s confirmation commitment to the nonce exchange and Device A’s verification. Both sides then calculate six-digit values from the same public keys and nonces, and the user must compare them before pairing proceeds. The review question is therefore precise: can both endpoints display and confirm a value bound to the same transcript? If not, the design cannot claim Numeric Comparison MITM protection even when LE Secure Connections still encrypts the link.

12.5 Passkey Entry Bit Commitments

Passkey Entry does not safely authenticate by sending the six-digit passkey across the radio. In LE Secure Connections, the protocol proves knowledge of the passkey through repeated commitment rounds. Each round binds one bit of the passkey to fresh random material and the devices’ public keys before the bit is effectively checked.

That bit-by-bit structure matters because it prevents a relay from waiting to see the whole passkey and then reusing it in the other direction. A wrong guess fails a round; repeated failures are visible as pairing failures and should trigger lockout or delay. The product review should therefore ask for three pieces of evidence: the passkey is fresh per attempt, the UI only displays it during intentional pairing, and failed attempts are rate-limited.

A fixed factory PIN breaks this model. If the same passkey is reused across units or pairing attempts, the attacker is no longer guessing a short-lived value inside the commitment ceremony; they are reusing a secret that can be photographed, learned from documentation, or extracted from firmware.

12.6 f5 Key Derivation After ECDH

LE Secure Connections does not use the raw ECDH DHKey directly as the long-term link key. After the devices compute the shared DHKey, the f5 derivation step mixes it with both device nonces and addresses. The result is key material such as MacKey and LTK for later confirmation and encryption work.

This separation protects the protocol design. DHKey is an intermediate secret; f5 turns it into context-bound keys for this pairing transcript. A review should therefore avoid vague claims like “ECDH creates the Bluetooth key.” A better review record says: devices exchanged P-256 public keys, computed the same DHKey, ran f5 with the pairing nonces and addresses, then used the derived key material for confirmation and encrypted reconnection.

12.7 Deep Review Checklist

  • Does the product reject Legacy Pairing for sensitive flows?
  • Does the selected method prove active MITM resistance, not just passive eavesdropper resistance?
  • If Numeric Comparison is claimed, can both sides display and confirm the same value?
  • If Passkey Entry is claimed, is the passkey fresh, short-lived, and rate-limited?
  • Does implementation evidence show the f5-derived keys and bonding records are protected after pairing?

12.8 Worked Example: Comparing Just Works and Numeric Comparison

Scenario: A smart door lock is being paired in an apartment building with many nearby BLE devices. Compare the security behavior of Just Works versus Numeric Comparison pairing.

Just Works pairing:

In Just Works mode, there is zero user-authenticated verification. If an attacker wins the setup timing race, the protocol does not give the user a number, passkey, or OOB proof to compare.

Attack steps:

  1. Legitimate lock advertises: “Smart Lock 123 ready to pair”
  2. User opens app to pair
  3. Attacker (within range) sends pairing request first
  4. Lock accepts (no verification step)
  5. Attacker now has bonded keys (LTK)

Why this is dangerous: The defense depends on setup timing, app UX, and physical controls rather than a cryptographic user-verification step.

Numeric Comparison pairing:

Both devices display a 6-digit code. User verifies they match.

Attack scenario:

  1. Lock displays code: 481923
  2. User’s phone displays: 481923
  3. Attacker MITM position displays: 775204 (different code)
  4. User compares: 481923 ≠ 775204 → rejects pairing

Probability attacker’s random code matches:

  • Total possible 6-digit codes: 10^6 = 1,000,000
  • Probability of match: 1 / 1,000,000 = 0.0001% = ~0

With repeated attempts:

  • Attacker tries 10 times (user may suspect after repeated failures)
  • Success probability: 10 / 1,000,000 = 0.001% (essentially zero)

Conclusion: Just Works provides no protocol-level MITM detection. Numeric Comparison adds a user-visible check that makes an undetected MITM require guessing the same 6-digit value during setup.

12.9 Putting Numbers to It

The 6-digit numeric comparison code provides strong MITM protection because:

Total possible codes=106=1,000,000\text{Total possible codes} = 10^6 = 1,000,000

For an attacker attempting a man-in-the-middle attack:

P(successful MITM)=11,000,000=0.0001%=1 in a millionP(\text{successful MITM}) = \frac{1}{1,000,000} = 0.0001\% = 1 \text{ in a million}

Worked example: If an attacker tries 10 pairing attempts before the user becomes suspicious:

  • Success probability: 101,000,000=0.001%\frac{10}{1,000,000} = 0.001\% (essentially zero)
  • Compare to Just Works: no user-verification challenge to guess or compare

This 10610^6 keyspace makes Numeric Comparison infeasible to crack through trial-and-error during the brief pairing window.

12.10 Decision Framework: Selecting BLE Pairing Method Based on Device Capabilities

Use this order when selecting a pairing method:

  1. If an OOB channel exists, use it for security-sensitive setup. NFC, QR, wired provisioning, or a short-lived setup token can prove physical presence.
  2. If both devices can display and confirm, use Numeric Comparison under LE Secure Connections.
  3. If one device displays and the other can enter digits, use Passkey Entry with a fresh random passkey for each pairing attempt.
  4. If neither device can verify the user, Just Works is the protocol fallback. Use it only for low-risk public data, or add another control before release.

Typical outcomes:

  • A phone paired with a watch that has a display and Yes/No control should use Numeric Comparison.
  • A phone paired with an NFC-enabled lock should use OOB setup.
  • A phone paired with a basic beacon may fall back to Just Works, but the beacon should not expose sensitive commands.
  • A safety-critical displayless device should add a physical setup button, OOB tag, account claim, or commissioning station.

12.11 Common Mistake: Using a Fixed PIN for Passkey Entry Pairing

The error: A developer implements Passkey Entry pairing but hardcodes a static PIN instead of generating a fresh 6-digit passkey for each pairing attempt.

What actually happens:

  • The same passkey works for every unit or every pairing attempt.
  • Attackers try common default values first.
  • Reverse engineering the firmware or setup app can reveal the passkey.
  • A known passkey removes the practical value of Passkey Entry as a verification step.

The fix (correct implementation):

  • Generate a fresh 6-digit passkey from a hardware-backed random source for each pairing attempt.
  • Display the passkey only while the user has intentionally started pairing.
  • Expire the passkey after a short setup window or after successful pairing.
  • Discard the passkey after use; do not reuse it for later sessions.
  • Lock out or slow down repeated failures so online guessing is noisy and slow.

Security improvement:

  • Random 6-digit PIN = 1,000,000 possibilities
  • Attacker success rate for one random guess: 1 / 1,000,000 = 0.0001%
  • If pairing fails 3 times, lock out for 5 minutes (prevents brute force)

Additional mistake: Displaying PIN before pairing starts:

Some devices show the PIN continuously on an always-on display (even when not pairing). This allows an attacker to photograph the PIN from a distance, then initiate pairing later.

Correct UX flow:

  1. User presses “Pair” button on lock
  2. Lock generates random PIN
  3. Lock displays PIN for 60 seconds only
  4. After 60 seconds or successful pairing, PIN is discarded
  5. Next pairing gets a new random PIN

Lesson: Do not ship static passkeys for security. Generate random passkeys, display them only during intentional pairing, and implement lockout after failed attempts.

Common Pitfalls

Just Works pairing provides zero MITM protection: an attacker within BLE range can participate in the setup exchange and bond as the trusted central device if no other setup control is present. Evaluate the sensitivity of the data or physical access being controlled. If the device unlocks a door, controls medication delivery, or stores personal data, use Numeric Comparison, OOB pairing, or another setup proof instead of relying on Just Works alone.

A common development shortcut is to hardcode a fixed passkey for convenience during testing, then ship the same firmware to production. An attacker who reverse-engineers the firmware or observes the setup flow may learn the passkey. The correct approach is to use the platform hardware random source to generate a fresh 6-digit passkey for each pairing attempt, display it only during the pairing window, and discard it afterwards. Do not use a general-purpose pseudo-random function for security decisions.

BLE pairing method selection is automatic: both devices exchange IO capability flags and the protocol selects the strongest mutually supported method. Many developers assume Numeric Comparison will be used but forget that their peripheral declares NoInputNoOutput (a common default in SDK examples), forcing Just Works regardless of the central’s capabilities. Always explicitly set the IO capability flags in the security parameters to match the actual hardware. Verify the selected pairing method at runtime by logging the ESP_GAP_BLE_AUTH_CMPL_EVT callback parameters — never assume.

After successful pairing, the Long-Term Key (LTK) is stored in non-volatile storage (NVS flash on ESP32) so reconnections skip re-pairing. If an attacker gains physical access to the device and can read the flash (e.g., via JTAG debug port or direct chip read), they extract the LTK and can permanently impersonate the bonded central device. Mitigations: disable JTAG in production firmware, encrypt NVS with a device-unique key derived from hardware eFuses, and implement a factory-reset button that wipes bond storage. For high-security applications, consider not bonding at all and requiring re-pairing on every session.

12.12 BLE Pairing Practice Checks

This child chapter contains the practice material split out of Pairing Methods & MITM Protection. Use it after the main chapter, or after BLE Pairing Deep Dive: MITM and Key Derivation if you want the protocol mechanics first.

12.12.1 Interactive: MITM Attack Probability Calculator

Compare an illustrative MITM risk model across pairing methods and attacker attempts. Treat the values as a teaching model, not a measured product failure rate.

12.12.2 Pairing Failure Patterns

Make Setup Prove the Right Owner

Picture a new door lock waiting for its owner’s phone. A stranger stands nearby with another phone. If the lock accepts the first request it hears, setup can finish cleanly for the wrong person.

Bluetooth Low Energy (BLE) is a short-range way for devices to connect while using little power. Pairing is the setup step in which two devices form shared trust. The key question is not only whether pairing succeeds. It is how the lock knows that this phone belongs to the intended owner.

Start with the device’s real controls. A screen can show a number. A button can confirm a match. A printed code, tap, or account claim can prove physical access. Choose a method that matches both the controls and the harm of a wrong owner.

Test a nearby rival, a repeated setup, a lost phone, old trust records, and a reset. Make failure clear to the user and safe for the device.

This simple check does not cover every radio attack. Use Practitioner for method choice and recovery. Use Under the Hood for keys, messages, and attack limits.

Understanding pairing vulnerabilities in theory is important, but the design pattern is what matters for learners: the same mistake repeats across access-control, health, and industrial devices when setup accepts the first nearby device without strong verification.

12.12.3 Case Pattern: Displayless Lock Setup

A displayless lock often cannot run Numeric Comparison because the lock cannot show a confirmation code. If setup uses Just Works by itself, the first nearby central that completes pairing can become the trusted controller.

Attack timeline:

  • The lock advertises a setup service and accepts pairing during a short commissioning window.
  • An attacker nearby completes pairing before the owner’s phone.
  • The lock stores the attacker’s bond keys for later reconnection.
  • The legitimate user may only see a vague setup failure unless the app explains the problem.

Design fix: Add a physical setup action, NFC/QR OOB data, cloud-backed ownership claim, or a short-lived setup token so pairing requires proof of physical presence or account ownership.

12.12.4 Pairing Method Selection Decision Framework

When designing a BLE IoT product, use this framework to select the appropriate pairing method based on device capabilities and threat model:

  • No display, no input, public telemetry: Just Works can be acceptable if no sensitive commands are exposed.
  • No display, has NFC or QR label: use OOB for private or safety-critical setup.
  • Display plus Yes/No input: use Numeric Comparison when both peers can show and confirm the same value.
  • Display plus keyboard/keypad: use Numeric Comparison when possible; use Passkey Entry when one device displays and the other enters the passkey.
  • Safety-critical device with no local UI: add a setup control, OOB channel, or account claim before shipping.

Cost of getting it wrong:

  • Firmware updates, customer support, and replacement setup flows become expensive after release.
  • Trust damage is hard to recover when pairing controls doors, medication, vehicles, or payment workflows.
  • Security-by-design requirements increasingly expect products to justify why weak pairing is safe for their use case.

Rule of thumb: If the BLE device controls physical access, medication, vehicles, or payment data, Just Works should not be the sole setup control.

12.12.5 Concept Relationships

  • Just Works and MITM protection: no user-authenticated verification means a nearby attacker can participate in setup unnoticed.
  • Numeric Comparison and user verification: the 6-digit comparison value turns MITM detection into a visible user decision.
  • OOB pairing and physical presence: NFC, QR, or setup tokens move authentication data outside the BLE radio channel.
  • Bonding and stored-key risk: saved LTK/IRK/CSRK values make reconnection convenient but require protected storage and revocation.
  • LE Secure Connections and ECDH: P-256 key agreement protects against passive recovery of the link keys, while the pairing method determines MITM resistance.

12.12.6 See Also

12.12.7 Label the Diagram

12.12.8 Code Challenge

12.12.9 BLE Pairing Security Workbench

12.12.10 Start With the Story

Practice becomes useful when a learner can change the device capabilities and watch the security outcome change. A display, a button, an NFC side channel, or no I/O should lead to different pairing evidence.

Use this page as a decision rehearsal. Try the cases, name the pairing method, explain the MITM boundary, and write down what the device would still need before deployment.

12.12.11 Interactive Quiz: Match Pairing Concepts

12.12.12 Interactive Quiz: Sequence the Steps

12.12.13 What’s Next

12.13 Summary

This chapter covered the fundamentals of BLE pairing security:

  • Four Pairing Methods: Just Works (insecure), Passkey Entry (moderate), Numeric Comparison (strong), OOB (strongest)
  • Just Works Vulnerability: Provides no MITM protection - attackers can hijack pairing
  • Three-Phase Pairing Process: Feature exchange, STK generation, key distribution
  • Bonding Trade-offs: Convenience vs. security risk if devices are compromised
  • LE Secure Connections: BLE 4.2+ uses ECDH for improved key agreement
  • Product consequences: weak setup flows are expensive to repair after release, so match pairing method to threat model before shipping

12.14 What’s Next