Bluetooth LE Security Manager

Bluetooth LE Paring, Authentication, and Encryption.

March 12, 2024 (1mo ago)


Within Bluetooth Low Energy (LE) establising a connection betwene device requires a pairing process.

The Security Manager defines methods of pairing and key distribution.

Security properties provided by the Security Manager are classified into 4 levels:

  1. LE Secure Connections pairing
  2. Authenticated MITM protection
  3. Unauthenticated no MITM protection
  4. No security requirements

The Just Works method of pairing is the simplest and also for a encrypted connection. However the connection is unauthenticated and no MITM protection

For BR/ER/LE devices, authenticated MITM protection is obtain by utlizing these pairing methods:

  • Passkey Entry
  • Out Of Band
  • Numeric Comparision (LE-only)

LE Secure Connections đź”— is the most secure as it used P-256 curve to generate a Long Term Key (LTK).

It recommended to utilize LE Secure Connections pairing over LE Legacy pairing.

This post will detail the LE Secure Connections pairing method.

Pairing Process

Pairing is performed to establish keys between devices which are used to encrypt a link.

The LE Secure Connections pairing process occurs in 3 phases:

  1. Pairing Feature Exchange
  2. Long Term Key (LTK) Generation
  3. Transport Specific Key Distribution

Pairing Feature Exchange is the first phase. In this state devices will exchange authentication requirements and IO capabilities.

Long Term Key (LTK) Generation is the second phase. Based on device requirements and capabilties a method for LTK generation is selected:

  • Just works
  • Numeric Comparison (Only for LE Secure Connections)
  • Passkey Entry
  • Out Of Band (OOB)
enum pairing_method {
    JUST_WORKS,         /* JustWorks pairing */
    PASSKEY_INPUT,      /* Passkey Entry input */
    PASSKEY_DISPLAY,    /* Passkey Entry display */
    PASSKEY_CONFIRM,    /* Passkey confirm */
    PASSKEY_ROLE,       /* Passkey Entry depends on role */
    LE_SC_OOB,          /* LESC Out of Band */
    LEGACY_OOB,         /* Legacy Out of Band */
};	

In Zephyr RTOS, the pairing methods can be observed in this enum.

Phase 3 is optional. It may be performed to distribute transport specific keys, for example the Identity Resolving Key (IRK) value and Identity Address information.

  • Identity Resolving Key (IRK): A 128-bit key used to generate and resolved random addresses
  • Connection Signature Resolving Key (CSRK): A 128-bit key used to sign data and verify signatures on the receiving device.
  • Identity Address Information: Public device address or static random address.

Phase 3 can only be performed on a link that is encrypted using the LTK generated in Phase 2 when using LE Secure Connections

Phase 1 and Phase 2 may be performed on a link which is either encrypted or not encrypted

Security Manger Channel Over L2CAP

Security Managers on remote devices communicate via the Security Manager Protocol (SMP).

SMP is used for sending commands during pairing and transport specific key distribution

All SMP commands are sent over the Security Manager Channel, which is an L2CAP fixed channel.

#define BT_L2CAP_CID_SMP                0x0006
BT_L2CAP_CHANNEL_DEFINE(smp_fixed_chan, BT_L2CAP_CID_SMP, bt_smp_accept, NULL);

Zephyr RTOS defines this channel with a macro, with appropriate the channel identifier (CID) as defined in the Bluetooth Core Specification;

The Security Manger Channel has configuration parameters that can be set.

Find

Command Format

The general format for SMP commands

working on it

The Code field is one octet long and it identifies the type of command.

CodeDescriptionLogical Link Supported
0x01Pairing RequestLE-U, ACL-U
0x02Pairing ResponseLE-U, ACL-U
0x03Pairing ConfirmLE-U
0x04Pairing RandomLE-U
0x05Pairing FailedLE-U, ACL-U
0x06Encryption InformationLE-U
0x07Central IdentificationLE-U
0x08Identity IdentificationLE-U, ACL-U
0x09Identity Address InformationLE-U, ACL-U
0x0ASigning InformationLE-U, ACL-U
0x0BSecurity RequestLE-U
0x0CPairing Public KeyLE-U
0x0DPairing DHKey CheckLE-U
0x0EPairing Keypress NotificationLE-U
All other valuesRFU

The Data field is variable in length.

The Code field determines the format of the Data field.

If a device does not support paring then it shall respond with 0x05 Paring Failed command with the reason set to “Pairing Not Supported” when any command is received. If pairing is support then all commands shall be supports.

static int bt_smp_recv(struct bt_l2cap_chan *chan, struct net_buf *buf)

This is that routine that processes SMP commands. Where then the appropriate action is taken based on the Code field.

err = handlers[hdr->code].func(smp, buf);
    if (err) {
        smp_error(smp, err);
}
static const struct {
    uint8_t  (*func)(struct bt_smp *smp, struct net_buf *buf);
    uint8_t  expect_len;
} handlers[] = {
    { }, /* No op-code defined for 0x00 */
    { smp_pairing_req,         sizeof(struct bt_smp_pairing) },
    { smp_pairing_rsp,         sizeof(struct bt_smp_pairing) },
    { smp_pairing_confirm,     sizeof(struct bt_smp_pairing_confirm) },
    { smp_pairing_random,      sizeof(struct bt_smp_pairing_random) },
    { smp_pairing_failed,      sizeof(struct bt_smp_pairing_fail) },
    { smp_encrypt_info,        sizeof(struct bt_smp_encrypt_info) },
    { smp_central_ident,       sizeof(struct bt_smp_central_ident) },
    { smp_ident_info,          sizeof(struct bt_smp_ident_info) },
    { smp_ident_addr_info,     sizeof(struct bt_smp_ident_addr_info) },
    { smp_signing_info,        sizeof(struct bt_smp_signing_info) },
    { smp_security_request,    sizeof(struct bt_smp_security_request) },
    { smp_public_key,          sizeof(struct bt_smp_public_key) },
    { smp_dhkey_check,         sizeof(struct bt_smp_dhkey_check) },
    { smp_keypress_notif,      sizeof(struct bt_smp_keypress_notif) },
};

Within Zephyr each code has an associated handler.

SMP Timeout

To protect the Security Manager Protocol from stalling, a Security Manager Timer is used.

If the Security Manager Timer times out, the pairing procedure shall be considered to have failed.

#define SMP_TIMEOUT K_SECONDS(30)

The Bluetooth Core Specification specifies 30 seconds as the timeout.

Zephyr RTOS implements the Security Manager Timer utilizing a delayable work structure.

k_work_init_delayable(&smp->work, smp_timeout);

The idea is that the timeout routine is delayed. In this case 30 seconds. If the work thread processes the work object then the timeout handler will process a timeout.

The Security Manager Timer is reset and (re)started:

  • Upon transmission of the Security Request command
  • Upon reception of the Security Request command
  • Upon transmission of the Pairing Request command
  • Upon reception the Pairing Request command
  • Upon recpetion of a Keypress Notification
  • Upon L2CAP SMP command queued for transmission

So how does Zepyhr RTOS implement the reset with a delayable work structure?

k_work_reschedule(&smp->work, SMP_TIMEOUT);

Simply by rescheduling the work item! Now it'll be another 30 seconds before the work thread will process it.

When the Pairing process completes (whether successfully or not), the Security Manager Timer is stopped

(void)k_work_cancel_delayable(&smp->work);

This will remove the work item from the queue. Stopping the Security Manager Timer.

At this point no further SMP commands are sent over the L2CAP Security Manger Channel. A new Pairing process can only be performed when new physical link has been established.

LE Secure Connections Pairing Flow

Prior to pairing a LL connection must be established.

Pairing Featrues Exchange

  • Security Request from Peripheral
  • Pairing request by Central.

LTK Generation

Initially, each device will generate its own Elliptic Curve Diffie-Hellman (ECDH) public-private key pair (ph)

The initiating fecie will send its piblic key to the receiving deivce. The repsonding device repleis with its own puiblic key.

Each deivce validates that any public key is on the correct cure,

After the public keys have been cahgnes the deivce can start computing the Diffe-Hellman Key (DHKey)

Authentication Numeric comparison

After public ketys have been exhanges, random 128 bit nonce is selected. The value is used to migitate repolay attacks

The repsonding device computes a commitement to the tow public keys exhcnaged and its own nonce valus.

Sent to initiating deivce.

The device exhanges thier repsiecitve nonce.

The initiatinf deivce computes the commitmetns and confirms it

For numeric compariosn, the two deivce compute 6 digit confirmationv values that are dispalt ro rhew usere on thier respective devices. The user is then chcks that these values mathc and confirm.

Exchanging of KEy

durue

SMP Reference

The SMP commands detailed in this section are used to perform Pairing Feature Exchange and key generation.

There are two roles in a Pairing Feature Exchange, an initator typically a Central, and a receiver, a peripheral.

Pairing Request

The initiator starts the Pairing Feature Exchange by sending a Pairing Request command to the responding device.

IO Capability is a single octect field that describes the input/output capabilites of the device

ValueDescription
0x00DisplayOnly
0x01DispalyYesNo
0x02KeyboardOnly
0x03NoInputNoOutput
0x04KeyboardDispaly
0x05 to 0xFFReserved for future use

OOB data flag is a single octet field indicating whether OOB authentication data is available

ValueDescription
0x00OOB Authentication data not present
0x01OOB Authentication data from remote device present
0x02 to 0xFFReserved for future use

The AuthReq field is a bit filed that indicates the requested security property for the STK and LTK and GAP bonding information.

pic of the bit field

Bonding_Flags is a 2-bit field witin AuthReq that indicated the type of bonding being requestsd by the initiating device.

Bonding_Flags b1b0Bonding Type
00No Bonding
01Bonding
10Reserved for future use
11Reserved for future use

MITM is a 1-bit flag that is set to one if the devie is requesting MITM protection.

SC is a 1 but flag. If LE Secure Connections pairing support by the device it is set. If both devices support LE Secure Connections pairing, then LE Secure Connections paring is used, otherwise defaulting to LE Legacy pairing.

Keypress is a 1 bit flag that is used only in the Passkey Entry protocol.

CT2 is a 1 bit flag that indicates the support for the h7 function.

Maxium Encryption Key Size is a one octet value that defines the maxiumiu encryption key size in octets that the deivce can support

The maxium key sizes range 7 to 16 octets

Initiator Key Distribution / Generation is a one octet field which indicates which keys the initiator is requesting to distrivuite / generate or use during the Transport Specific Key Distribvution phase.

Pairing Response

This command is used bu the responding device to complete the Pairing Feature Exhange after it has received a Pairing Request command from the initiator device, if the responding device allows pairing.

It utilizies the same fields as the Pairing Request.

Pairing Confirm

This is used following a successful Pairing Feature Exchange to start STK Generation for LE legacy paring and LTK Generation for LE Secure Connections pairing.

This command is used any both device to send the confirm value to the peer device.

The initiating device starts key generation by sending the Pairing Confim command to the responding device.

The responding device sends the Pairing Confirm command after it has received a Pairng Confirm command from the initiating device. Devices essentially exchange Confirm values

Confirm Value is 16 octet, holds the confirms from Generated keys.

Pairing Random

This command is used by the initialing and responding device to send the random number used to calculate the Confirm value sent in the Paring Confirm command.

The initiating device send a Pairing Random command after it has received a Pairing Confirm command from the responding device.

The intitiainfg device shall encrypt the link using the generated key if the Confirm value calculates on the initiating device matches the Confirm value received form the responsive device.

The successful encryption or re-encryption of the link is the signal to the responding device that key generation has completed susccesfully. If the calculated Confim value does not match then the intimating device shall respond with the Pairing Failed command

Random value (16 octets)

Pairing Failed

This command is used when there has been a failure during pairing and reports that the pairing prodcueuder has been been stopped and no further communication for the current paring procedure is to occur.

Any subsequent pairing procedures will restart from the Pairing Feature Exchange phase

This command can be sent at any time during the paring process by either device in response to a message from the remote device.

Reason is a 1 octet field which specifies the reason for failure.

ValueNameDescription
0x01Passkey Entry FailedThe user input of passkey failed, for exam- ple, the user cancelled the operation
0x02OBB Not AvailableThe OOB data is not available
0x03Authentication RequirementsThe pairing procedure cannot be per- formed as authentication requirements cannot be met due to IO capabilities of one or both devices
0x04Confirm Value FailedThe confirm value does not match the cal- culated compare value
0x05Pairing Not SupportedPairing is not supported by the device
0x06Encryption Key SizeThe resultant encryption key size is not long enough for the security requirements of this device
0x07Command Not SupportThe SMP command received is not sup- ported on this device
0x08Unspecified ReasonPairing failed due to an unspecified reason
0x09Repeated AttemptsPairing or authentication procedure is dis- allowed because too little time has elapsed since last pairing request or security request
0x0AInvalid ParametersThe Invalid Parameters error code indicates that the command length is invalid or that a parameter is outside of the specified range.
0x0BDHKey Check FailedIndicates to the remote device that the DHKey Check value received doesn’t match the one calculated by the local device.
0x0CNumeric Comparison FailedIndicates that the confirm values in the numeric comparison protocol do not match.
0x0DBR/EDR pairing in progressIndicates that the pairing over the LE transport failed due to a Pairing Request sent over the BR/EDR transport in progress.
0x0ECross-transport Key Derivation/Generation not allowedIndicates that the BR/EDR Link Key generated on the BR/EDR transport cannot be used to derive and distribute keys for the LE transport or the LE LTK generated on the LE transport cannot be used to derive a key for the BR/EDR transport.
0x0EKey RejectedIndicates that the device chose not to accept a distributed key.
All other valuesReserved for future use

Pairing Public Key

This message is sued to transfer the devices local public key to the remote device. This message is used by both the initiator and responder. This PDU is only used for Secure Connections. Its format is

Pairing DHKey Check

This message is used to transmit the 128-bit DHKey Check values (Ea/Eb) generated using f6. These are confirmation values generated using the DHKey. This message is used by both initiator and responder. This PDU is only used for LE Secure Connections.

Keypress Notification

This message is used during the Passkey Entry protocol by a deice with KeyboardOnly IO capabitlis to inform the remote device when the key have been entered or erased

ValueParameter Description
0Passkey entry started
1Passkey digit entered
2Passkey digit erased
3Passkey cleared
4Passkey entry completed
5 to 255Reserved for future use

Transport Specific Key Distribution