9 Implementing passkey pairing
In Step 5 (firmware/step5_pairing), we use the mechanisms from Chapter 8 to make a device that cannot be used without pairing by entering passkey 123456.
9.1 Changes from Step 4
| Location | Change |
|---|---|
sdkconfig.defaults |
Enable the Security Manager and persistent bond storage |
app_main() |
Configure security with ble_hs_cfg.sm_*; ble_store_config_init() |
| Service definition | *_ENC / *_AUTHEN / NOTIFY_INDICATE_* flags |
BLE_GAP_EVENT_CONNECT |
Request encryption with ble_gap_security_initiate() |
| New GAP events | ENC_CHANGE, PASSKEY_ACTION, REPEAT_PAIRING |
9.2 sdkconfig.defaults
CONFIG_IDF_TARGET="esp32c3"
# Bluetooth (NimBLE, BLE only)
CONFIG_BT_ENABLED=y
CONFIG_BT_NIMBLE_ENABLED=y
CONFIG_BT_NIMBLE_MAX_CONNECTIONS=1
# Security Manager (pairing)
CONFIG_BT_NIMBLE_SECURITY_ENABLE=y
CONFIG_BT_NIMBLE_SM_LEGACY=y
CONFIG_BT_NIMBLE_SM_SC=y
# Save bonding information to NVS (no re-pairing needed after reboot)
CONFIG_BT_NIMBLE_NVS_PERSIST=y| Setting | Meaning |
|---|---|
CONFIG_BT_NIMBLE_SECURITY_ENABLE |
Enable the Security Manager |
CONFIG_BT_NIMBLE_SM_LEGACY |
Allow LE Legacy Pairing |
CONFIG_BT_NIMBLE_SM_SC |
Enable LE Secure Connections |
CONFIG_BT_NIMBLE_NVS_PERSIST |
Store bond information in NVS (flash). If disabled, it is only kept in RAM and lost on reboot |
If Step 4’s sdkconfig is still there, adding these to sdkconfig.defaults may not take effect (Chapter 4). Delete sdkconfig before building.
9.3 The whole code
/*
* Step 5: pair with a passkey and allow use only over encrypted connections
*
* Differences from Step 4:
* - configure security (IO capability, MITM, bonding, LE Secure Connections) via sm_* in ble_hs_cfg
* - add ENC / AUTHEN flags to the characteristics (also for Notify subscriptions)
* - initiate security ourselves after connecting
* - answer passkey display requests (BLE_GAP_EVENT_PASSKEY_ACTION) with a fixed passkey
* - save bonding information to NVS (ble_store_config_init)
*/
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "nvs_flash.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "host/util/util.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
#define TAG "STEP5"
#define PAIRING_PASSKEY 123456 // pairing code (000000 - 999999)
#define CMD_PING 0x00
#define CMD_STATUS 0x01
/* c0a60001-18ff-4cd1-afce-4832ee44bcb7 (bytes are written in reverse = little-endian) */
static const ble_uuid128_t svc_uuid =
BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
0xd1, 0x4c, 0xff, 0x18, 0x01, 0x00, 0xa6, 0xc0);
static const ble_uuid128_t counter_chr_uuid =
BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
0xd1, 0x4c, 0xff, 0x18, 0x02, 0x00, 0xa6, 0xc0);
static const ble_uuid128_t cmd_chr_uuid =
BLE_UUID128_INIT(0xb7, 0xbc, 0x44, 0xee, 0x32, 0x48, 0xce, 0xaf,
0xd1, 0x4c, 0xff, 0x18, 0x03, 0x00, 0xa6, 0xc0);
static uint8_t own_addr_type;
static char device_name[20];
static uint16_t conn_handle = BLE_HS_CONN_HANDLE_NONE;
static uint16_t counter_val_handle;
static uint16_t cmd_val_handle;
static bool counter_notify_enabled;
static bool cmd_notify_enabled;
static uint32_t counter;
void ble_store_config_init(void); // not declared in a public header, so declare it ourselves
static void start_advertising(void);
/* ---------------- GATT ---------------- */
static int notify(uint16_t attr_handle, const void *data, uint16_t len)
{
if (conn_handle == BLE_HS_CONN_HANDLE_NONE) {
return BLE_HS_ENOTCONN;
}
struct os_mbuf *om = ble_hs_mbuf_from_flat(data, len);
if (om == NULL) {
return BLE_HS_ENOMEM;
}
return ble_gatts_notify_custom(conn_handle, attr_handle, om);
}
static void handle_command(const uint8_t *buf, uint16_t len)
{
uint8_t rsp[9];
uint16_t rsp_len;
uint8_t cmd = buf[0];
switch (cmd) {
case CMD_PING:
rsp[0] = CMD_PING;
memcpy(&rsp[1], "PONG", 4);
rsp_len = 5;
break;
case CMD_STATUS: {
uint32_t uptime = (uint32_t)(esp_timer_get_time() / 1000000);
rsp[0] = CMD_STATUS;
memcpy(&rsp[1], &counter, 4);
memcpy(&rsp[5], &uptime, 4);
rsp_len = 9;
break;
}
default:
rsp[0] = cmd;
rsp[1] = 0xFF;
rsp_len = 2;
break;
}
ESP_LOGI(TAG, "cmd 0x%02x (len=%d) -> rsp len=%d", cmd, len, rsp_len);
if (cmd_notify_enabled) {
notify(cmd_val_handle, rsp, rsp_len);
} else {
ESP_LOGW(TAG, "command notify not enabled, response dropped");
}
}
static int gatt_access_cb(uint16_t conn, uint16_t attr_handle,
struct ble_gatt_access_ctxt *ctxt, void *arg)
{
switch (ctxt->op) {
case BLE_GATT_ACCESS_OP_READ_CHR:
if (attr_handle == counter_val_handle) {
int rc = os_mbuf_append(ctxt->om, &counter, sizeof(counter));
return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
}
return BLE_ATT_ERR_UNLIKELY;
case BLE_GATT_ACCESS_OP_WRITE_CHR:
if (attr_handle == cmd_val_handle) {
uint8_t buf[20];
uint16_t len = OS_MBUF_PKTLEN(ctxt->om);
if (len == 0 || len > sizeof(buf)) {
return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
}
ble_hs_mbuf_to_flat(ctxt->om, buf, sizeof(buf), &len);
handle_command(buf, len);
return 0;
}
return BLE_ATT_ERR_UNLIKELY;
default:
return BLE_ATT_ERR_UNLIKELY;
}
}
/*
* *_ENC : reject unless the connection is encrypted
* *_AUTHEN : additionally reject unless the key was paired with MITM protection (passkey etc.)
* NOTIFY_INDICATE_* applies to writes to the CCCD (subscription setting). Without it, even unpaired peers can subscribe
*/
#define SECURE_READ (BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN)
#define SECURE_WRITE (BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_ENC | BLE_GATT_CHR_F_WRITE_AUTHEN)
#define SECURE_NOTIFY (BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC | \
BLE_GATT_CHR_F_NOTIFY_INDICATE_AUTHEN)
static const struct ble_gatt_svc_def gatt_svcs[] = {
{
.type = BLE_GATT_SVC_TYPE_PRIMARY,
.uuid = &svc_uuid.u,
.characteristics = (struct ble_gatt_chr_def[]) {
{
.uuid = &counter_chr_uuid.u,
.access_cb = gatt_access_cb,
.val_handle = &counter_val_handle,
.flags = SECURE_READ | SECURE_NOTIFY,
},
{
.uuid = &cmd_chr_uuid.u,
.access_cb = gatt_access_cb,
.val_handle = &cmd_val_handle,
.flags = SECURE_WRITE | SECURE_NOTIFY,
},
{ 0 },
},
},
{ 0 },
};
/* ---------------- GAP events ---------------- */
static int gap_event_cb(struct ble_gap_event *event, void *arg)
{
struct ble_gap_conn_desc desc;
switch (event->type) {
case BLE_GAP_EVENT_CONNECT:
ESP_LOGI(TAG, "connect %s status=%d",
event->connect.status == 0 ? "ok" : "failed", event->connect.status);
if (event->connect.status == 0) {
conn_handle = event->connect.conn_handle;
// the peripheral requests "please encrypt" (Security Request)
// if bonded, encrypt with the stored keys; if not bonded, pairing starts
ble_gap_security_initiate(conn_handle);
} else {
start_advertising();
}
return 0;
case BLE_GAP_EVENT_DISCONNECT:
ESP_LOGI(TAG, "disconnect reason=0x%x", event->disconnect.reason);
conn_handle = BLE_HS_CONN_HANDLE_NONE;
counter_notify_enabled = false;
cmd_notify_enabled = false;
start_advertising();
return 0;
case BLE_GAP_EVENT_ADV_COMPLETE:
start_advertising();
return 0;
case BLE_GAP_EVENT_SUBSCRIBE:
ESP_LOGI(TAG, "subscribe attr_handle=%d notify=%d",
event->subscribe.attr_handle, event->subscribe.cur_notify);
if (event->subscribe.attr_handle == counter_val_handle) {
counter_notify_enabled = event->subscribe.cur_notify;
} else if (event->subscribe.attr_handle == cmd_val_handle) {
cmd_notify_enabled = event->subscribe.cur_notify;
}
return 0;
case BLE_GAP_EVENT_MTU:
ESP_LOGI(TAG, "mtu=%d", event->mtu.value);
return 0;
case BLE_GAP_EVENT_ENC_CHANGE:
// result of encryption (status=0 means success)
if (ble_gap_conn_find(event->enc_change.conn_handle, &desc) == 0) {
ESP_LOGI(TAG, "enc change status=%d encrypted=%d authenticated=%d bonded=%d key_size=%d",
event->enc_change.status, desc.sec_state.encrypted,
desc.sec_state.authenticated, desc.sec_state.bonded,
desc.sec_state.key_size);
}
return 0;
case BLE_GAP_EVENT_PASSKEY_ACTION: {
// the Security Manager asks "what to do about the passkey"
struct ble_sm_io pkey = { 0 };
if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
// DisplayOnly: we "display" the passkey and the peer (phone) enters it
pkey.action = BLE_SM_IOACT_DISP;
pkey.passkey = PAIRING_PASSKEY;
ESP_LOGI(TAG, "==== Pairing passkey: %06d ====", PAIRING_PASSKEY);
int rc = ble_sm_inject_io(event->passkey.conn_handle, &pkey);
ESP_LOGI(TAG, "ble_sm_inject_io rc=%d", rc);
} else {
ESP_LOGW(TAG, "unsupported passkey action %d", event->passkey.params.action);
}
return 0;
}
case BLE_GAP_EVENT_REPEAT_PAIRING:
// a bonded peer requested re-pairing (e.g. the peer deleted its bond information)
// delete the old bond information and let pairing start over
if (ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc) == 0) {
ble_store_util_delete_peer(&desc.peer_id_addr);
}
return BLE_GAP_REPEAT_PAIRING_RETRY;
default:
return 0;
}
}
/* ---------------- Advertising ---------------- */
static void start_advertising(void)
{
struct ble_hs_adv_fields fields = { 0 };
struct ble_hs_adv_fields rsp_fields = { 0 };
struct ble_gap_adv_params adv_params = { 0 };
const char *name = ble_svc_gap_device_name();
fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
fields.uuids128 = &svc_uuid;
fields.num_uuids128 = 1;
fields.uuids128_is_complete = 1;
ble_gap_adv_set_fields(&fields);
rsp_fields.name = (uint8_t *)name;
rsp_fields.name_len = strlen(name);
rsp_fields.name_is_complete = 1;
ble_gap_adv_rsp_set_fields(&rsp_fields);
adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
adv_params.itvl_min = BLE_GAP_ADV_ITVL_MS(100);
adv_params.itvl_max = BLE_GAP_ADV_ITVL_MS(150);
int rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
&adv_params, gap_event_cb, NULL);
if (rc != 0) {
ESP_LOGE(TAG, "ble_gap_adv_start rc=%d", rc);
return;
}
ESP_LOGI(TAG, "advertising as \"%s\"", name);
}
/* ---------------- Host ---------------- */
static void on_sync(void)
{
uint8_t addr[6];
ble_hs_util_ensure_addr(0);
ble_hs_id_infer_auto(0, &own_addr_type);
ble_hs_id_copy_addr(own_addr_type, addr, NULL);
snprintf(device_name, sizeof(device_name), "HANDSON-C3-%02X%02X", addr[1], addr[0]);
ble_svc_gap_device_name_set(device_name);
start_advertising();
}
static void on_reset(int reason)
{
ESP_LOGE(TAG, "nimble reset reason=%d", reason);
}
static void host_task(void *param)
{
nimble_port_run();
nimble_port_freertos_deinit();
}
/* ---------------- Notify every second ---------------- */
static void notify_task(void *param)
{
while (1) {
vTaskDelay(pdMS_TO_TICKS(1000));
counter++;
if (counter_notify_enabled) {
notify(counter_val_handle, &counter, sizeof(counter));
}
}
}
void app_main(void)
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ESP_ERROR_CHECK(nimble_port_init());
ble_hs_cfg.reset_cb = on_reset;
ble_hs_cfg.sync_cb = on_sync;
ble_hs_cfg.store_status_cb = ble_store_util_status_rr; // if the bond storage is full, delete from the oldest
// security settings
ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_DISP_ONLY; // a device that can display but not take input
ble_hs_cfg.sm_bonding = 1; // store keys (bonding)
ble_hs_cfg.sm_mitm = 1; // require protection against man-in-the-middle (MITM) attacks
ble_hs_cfg.sm_sc = 1; // use LE Secure Connections
ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_svc_gap_init();
ble_svc_gatt_init();
ESP_ERROR_CHECK(ble_gatts_count_cfg(gatt_svcs));
ESP_ERROR_CHECK(ble_gatts_add_svcs(gatt_svcs));
ble_store_config_init(); // set the storage location for bond information (NVS)
nimble_port_freertos_init(host_task);
xTaskCreate(notify_task, "notify", 3072, NULL, 5, NULL);
}9.4 Security configuration
ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_DISP_ONLY;
ble_hs_cfg.sm_bonding = 1;
ble_hs_cfg.sm_mitm = 1;
ble_hs_cfg.sm_sc = 1;
ble_hs_cfg.sm_our_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;
ble_hs_cfg.sm_their_key_dist = BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID;This directly sets the items carried in the Pairing Request / Response from Chapter 8.
| Setting | Value | Meaning |
|---|---|---|
sm_io_cap |
BLE_SM_IO_CAP_DISP_ONLY |
Can display but cannot take input → Passkey Entry with the phone entering |
sm_bonding |
1 | Bond |
sm_mitm |
1 | Require MITM protection (authenticated keys) |
sm_sc |
1 | Use LE Secure Connections |
sm_our_key_dist / sm_their_key_dist |
ENC + ID | Distribute LTK and IRK to each other |
store_status_cb |
ble_store_util_status_rr |
If the bond storage (3 entries by default) is full, delete the oldest bond to make room |
void ble_store_config_init(void); // not declared in a public header, so declare it ourselves
...
ble_store_config_init();ble_store_config_init() registers the storage location for bond information (NVS if CONFIG_BT_NIMBLE_NVS_PERSIST) with NimBLE. The ESP-IDF examples also declare the function themselves like this and call it.
9.5 Access control flags
#define SECURE_READ (BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_READ_AUTHEN)
#define SECURE_WRITE (BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_ENC | BLE_GATT_CHR_F_WRITE_AUTHEN)
#define SECURE_NOTIFY (BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC | \
BLE_GATT_CHR_F_NOTIFY_INDICATE_AUTHEN)READ/WRITE/NOTIFYare properties (declarations of what can be done)*_ENC/*_AUTHENare permissions (reject unless the condition is met)
Accesses that do not meet the conditions are rejected by NimBLE before the access callback is called. You don’t need to write code that checks security inside gatt_access_cb().
9.6 Request encryption on connect
case BLE_GAP_EVENT_CONNECT:
if (event->connect.status == 0) {
conn_handle = event->connect.conn_handle;
ble_gap_security_initiate(conn_handle);
}For a Peripheral, ble_gap_security_initiate() sends a Security Request to the Central. The Central then
- if it has stored keys for this peer → starts encryption with those keys (no passkey needed)
- if not → starts pairing
Even without calling this, the Central starts pairing as soon as a protected characteristic is touched, but calling it right after connecting lets you start using the connection encrypted from the beginning.
9.7 “Displaying” the passkey
case BLE_GAP_EVENT_PASSKEY_ACTION: {
struct ble_sm_io pkey = { 0 };
if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
pkey.action = BLE_SM_IOACT_DISP;
pkey.passkey = PAIRING_PASSKEY;
ESP_LOGI(TAG, "==== Pairing passkey: %06d ====", PAIRING_PASSKEY);
ble_sm_inject_io(event->passkey.conn_handle, &pkey);
}During pairing, the Security Manager asks the app “what to do about the passkey”. params.action indicates what it wants.
action |
Meaning | What the app does |
|---|---|---|
BLE_SM_IOACT_DISP |
We are the displaying side | Decide a passkey, display it, and pass it to the SM with ble_sm_inject_io() |
BLE_SM_IOACT_INPUT |
We are the entering side | Have the user enter it and pass the value |
BLE_SM_IOACT_NUMCMP |
Numeric Comparison | Display params.numcmp and pass whether it matched |
BLE_SM_IOACT_OOB / OOB_SC |
OOB | Pass data obtained via another channel |
Only BLE_SM_IOACT_DISP comes to this DisplayOnly device. In this hands-on, the serial log is regarded as the “display”.
#include "esp_random.h"
pkey.passkey = esp_random() % 1000000; // 000000–999999
ESP_LOGI(TAG, "Pairing passkey: %06lu", (unsigned long)pkey.passkey);esp_random() returns true hardware random numbers when the radio is enabled. In a real product, show this passkey on an LCD or similar.
9.8 Checking the encryption result
case BLE_GAP_EVENT_ENC_CHANGE:
if (ble_gap_conn_find(event->enc_change.conn_handle, &desc) == 0) {
ESP_LOGI(TAG, "enc change status=%d encrypted=%d authenticated=%d bonded=%d key_size=%d", ...);
}Called when encryption starts (or fails). Retrieving the connection information with ble_gap_conn_find() gives the current connection’s security in sec_state.
| Member | Meaning |
|---|---|
encrypted |
Whether it is encrypted |
authenticated |
Whether the key has MITM protection (1 for Passkey, 0 for Just Works) |
bonded |
Whether the peer is bonded |
key_size |
Key length [bytes]. 16 is the maximum |
9.9 Re-pairing requests
case BLE_GAP_EVENT_REPEAT_PAIRING:
if (ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc) == 0) {
ble_store_util_delete_peer(&desc.peer_id_addr);
}
return BLE_GAP_REPEAT_PAIRING_RETRY;Called when an already-bonded peer tries to pair again, e.g. when the bond was deleted on the phone.
- Returning
BLE_GAP_REPEAT_PAIRING_RETRYmakes NimBLE try pairing again. Delete the old bond beforehand - Returning
BLE_GAP_REPEAT_PAIRING_IGNORErejects re-pairing (if you want to prevent keys being overwritten by impersonation)
The hands-on prioritizes ease of use and allows re-pairing.
9.10 Running it
cd firmware/step5_pairing
idf.py set-target esp32c3
idf.py build
idf.py -p PORT erase-flash flash monitor # erase-flash the first time to clear old bond information9.10.1 Pairing with nRF Connect
If you have connected to the same board in earlier steps, forget
HANDSON-C3-XXXXin the phone’s Bluetooth settings firstCONNECT in nRF Connect
A pairing dialog appears immediately (due to the Security Request from the ESP32-C3). The serial monitor shows
I (xxx) STEP5: ==== Pairing passkey: 123456 ====Enter
123456in the dialogIf
enc change status=0 encrypted=1 authenticated=1 bonded=1 key_size=16appears in the serial monitor, you have succeededConfirm that subscribing to Notify and sending commands work as in Steps 3 and 4
Disconnect once and connect again. This time you are not asked for the passkey, and
enc change … bonded=1appearsEven if you reset the ESP32-C3 and connect again, you are not asked for the passkey (because the bond information is saved in NVS)
9.10.2 Making it fail on purpose
- Cancel the dialog or enter a wrong passkey →
enc change status=…(non-zero) appears, and Read and Notify subscriptions fail with an error (Insufficient Authentication) - Erase only the ESP32-C3’s bond information with
idf.py -p PORT erase-flash flash→ the phone tries to encrypt with the old keys and fails. Forget the device on the phone too, then reconnect
- Remove
BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC/_AUTHEN, comment outble_gap_security_initiate()too, and build. After cancelling the pairing dialog, can you subscribe to Counter’s Notify? Can you Read? - Set
sm_mitm = 0and remove all*_AUTHENfrom the characteristics. How does the pairing method change? - Switch to a random passkey
- You can subscribe to Notify and the values arrive. On the other hand, Read is protected by
READ_ENC/READ_AUTHEN, so it is rejected with Insufficient Authentication. You can feel that the CCCD’s permissions are separate. - Since MITM is not required, pairing becomes possible via Just Works (no passkey entry) regardless of IO Capability (depending on the phone, only a “Pair?” confirmation appears). The link is encrypted, but
authenticated=0.
- Security is configured with
ble_hs_cfg.sm_*— exactly the items carried in the Pairing Request - Access control is done with permission flags. No need to check inside callbacks
- On connect, request encryption with
ble_gap_security_initiate() - Pass the passkey to
ble_sm_inject_io()onBLE_GAP_EVENT_PASSKEY_ACTION - Bond information is saved to flash with
ble_store_config_init()+CONFIG_BT_NIMBLE_NVS_PERSIST