9  パスキーペアリングを実装する

Step 5(firmware/step5_pairing)では、第 8 章の仕組みを使って、パスキー 123456 を入力してペアリングしないと使えない デバイスにします。

9.1 Step 4 からの変更点

場所 変更
sdkconfig.defaults Security Manager とボンド情報の保存を有効にする
app_main() ble_hs_cfg.sm_* でセキュリティを設定、ble_store_config_init()
サービス定義 *_ENC / *_AUTHEN / NOTIFY_INDICATE_* フラグ
BLE_GAP_EVENT_CONNECT ble_gap_security_initiate() で暗号化を要求
新しい GAP イベント 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 (ペアリング)
CONFIG_BT_NIMBLE_SECURITY_ENABLE=y
CONFIG_BT_NIMBLE_SM_LEGACY=y
CONFIG_BT_NIMBLE_SM_SC=y
# ボンディング情報を NVS に保存(再起動しても再ペアリング不要)
CONFIG_BT_NIMBLE_NVS_PERSIST=y
設定 意味
CONFIG_BT_NIMBLE_SECURITY_ENABLE Security Manager を有効にする
CONFIG_BT_NIMBLE_SM_LEGACY LE Legacy Pairing を許す
CONFIG_BT_NIMBLE_SM_SC LE Secure Connections を使えるようにする
CONFIG_BT_NIMBLE_NVS_PERSIST ボンド情報を NVS(Flash) に保存する。無効だと RAM にしか保存されず、再起動で消える
警告Step 4 のフォルダで続けている場合

Step 4 の sdkconfig が残っている状態で sdkconfig.defaults にこれらを足しても、反映されないことがあります(第 4 章)。sdkconfig を削除してからビルドしてください。

9.3 全体のコード

/*
 * Step 5: パスキーでペアリングし、暗号化された接続でだけ使えるようにする
 *
 * Step 4 との違い:
 *   - ble_hs_cfg の sm_* でセキュリティ(IO 能力・MITM・ボンディング・LE Secure Connections)を設定
 *   - キャラクタリスティックに ENC / AUTHEN フラグを付ける(Notify の購読にも)
 *   - 接続したら自分からセキュリティを開始する
 *   - パスキー表示要求 (BLE_GAP_EVENT_PASSKEY_ACTION) に固定パスキーを返す
 *   - ボンディング情報を 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 // ペアリングコード (000000 - 999999)

#define CMD_PING   0x00
#define CMD_STATUS 0x01

/* c0a60001-18ff-4cd1-afce-4832ee44bcb7(バイト列は逆順=リトルエンディアンで書く) */
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); // 公開ヘッダに宣言がないので自分で宣言する
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    : 暗号化された接続でなければ拒否
 * *_AUTHEN : さらに MITM 保護つき(パスキー等)でペアリングした鍵でなければ拒否
 * NOTIFY_INDICATE_* は CCCD(購読設定)への書き込みに効く。付けないと未ペアリングでも購読できてしまう
 */
#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 イベント ---------------- */

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;
            // ペリフェラルから「暗号化してほしい」と要求する (Security Request)
            // ボンド済みなら保存済みの鍵で暗号化、未ボンドならペアリングが始まる
            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:
        // 暗号化の結果 (status=0 で成功)
        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: {
        // Security Manager から「パスキーをどうするか」の問い合わせ
        struct ble_sm_io pkey = { 0 };
        if (event->passkey.params.action == BLE_SM_IOACT_DISP) {
            // DisplayOnly: こちらがパスキーを「表示」し、相手(スマホ)が入力する
            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:
        // ボンド済みの相手が再ペアリングを要求した(相手側でボンド情報を消した場合など)
        // 古いボンド情報を消して、ペアリングをやり直させる
        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;
    }
}

/* ---------------- アドバタイズ ---------------- */

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);
}

/* ---------------- ホスト ---------------- */

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();
}

/* ---------------- 1 秒ごとの Notify ---------------- */

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; // ボンド保存領域が満杯なら古いものから消す

    // セキュリティ設定
    ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_DISP_ONLY; // 表示はできるが入力はできない機器
    ble_hs_cfg.sm_bonding = 1;                       // 鍵を保存する (ボンディング)
    ble_hs_cfg.sm_mitm = 1;                          // 中間者攻撃 (MITM) 対策を要求
    ble_hs_cfg.sm_sc = 1;                            // 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(); // ボンド情報の保存先 (NVS) を設定

    nimble_port_freertos_init(host_task);
    xTaskCreate(notify_task, "notify", 3072, NULL, 5, NULL);
}

9.4 セキュリティの設定

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;

第 8 章の Pairing Request / Response に載る項目 を、そのまま設定しています。

設定 値 意味
sm_io_cap BLE_SM_IO_CAP_DISP_ONLY 表示はできるが入力はできない → スマホが入力する Passkey Entry になる
sm_bonding 1 ボンディングする
sm_mitm 1 MITM 保護(認証された鍵)を要求する
sm_sc 1 LE Secure Connections を使う
sm_our_key_dist / sm_their_key_dist ENC + ID LTK と IRK を配布し合う
store_status_cb ble_store_util_status_rr ボンドの保存領域(既定 3 件)が満杯なら、一番古いボンドを消して 空ける
void ble_store_config_init(void); // 公開ヘッダに宣言がないので自分で宣言する
...
ble_store_config_init();

ble_store_config_init() は、ボンド情報の保存先(CONFIG_BT_NIMBLE_NVS_PERSIST なら NVS)を NimBLE に登録します。ESP-IDF のサンプルも、このように関数を自分で宣言して呼んでいます。

9.5 アクセス制御のフラグ

#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 / NOTIFY は プロパティ(できることの宣言)
  • *_ENC / *_AUTHEN は パーミッション(条件を満たさなければ拒否)

条件を満たさないアクセスは、アクセスコールバックが呼ばれる前に NimBLE が拒否 します。gatt_access_cb() の中でセキュリティを確認するコードを書く必要はありません。

9.6 接続したら暗号化を要求する

case BLE_GAP_EVENT_CONNECT:
    if (event->connect.status == 0) {
        conn_handle = event->connect.conn_handle;
        ble_gap_security_initiate(conn_handle);
    }

ble_gap_security_initiate() は、Peripheral の場合 Security Request を Central に送ります。Central は、

  • この相手の鍵を 保存していれば → その鍵で 暗号化を開始(パスキー不要)
  • 保存していなければ → ペアリングを開始

します。これを呼ばなくても、保護されたキャラクタリスティックに触った時点で Central がペアリングを始めますが、接続直後に呼んでおくと 最初から暗号化された状態 で使い始められます。

9.7 パスキーを「表示」する

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);
    }

ペアリングの途中で、Security Manager が 「パスキーをどうするか」 をアプリに聞いてきます。params.action が何を求めているかを表します。

action 意味 アプリがすること
BLE_SM_IOACT_DISP こちらが表示 する側 パスキーを決めて表示し、ble_sm_inject_io() で SM に渡す
BLE_SM_IOACT_INPUT こちらが 入力 する側 ユーザーに入力させ、その値を渡す
BLE_SM_IOACT_NUMCMP Numeric Comparison params.numcmp を表示し、一致したかを渡す
BLE_SM_IOACT_OOB / OOB_SC OOB 別経路で得たデータを渡す

DisplayOnly のこのデバイスに来るのは BLE_SM_IOACT_DISP だけです。このハンズオンでは シリアルログを「表示」 とみなしています。

ヒントランダムなパスキーにするには
#include "esp_random.h"
pkey.passkey = esp_random() % 1000000;   // 000000〜999999
ESP_LOGI(TAG, "Pairing passkey: %06lu", (unsigned long)pkey.passkey);

esp_random() は、無線が有効なとき ハードウェアの真の乱数 を返します。実機の製品では、このパスキーを LCD などに表示します。

9.8 暗号化の結果を確かめる

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", ...);
    }

暗号化が始まった(または失敗した)ときに呼ばれます。ble_gap_conn_find() で接続の情報を取り出すと、sec_state に 今の接続の安全性 が入っています。

メンバ 意味
encrypted 暗号化されているか
authenticated MITM 保護つきの鍵か(Passkey なら 1、Just Works なら 0)
bonded ボンド済みの相手か
key_size 鍵の長さ [バイト]。16 が最大

9.9 再ペアリングの要求

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;

ボンド済みの相手が、もう一度ペアリングしようとした ときに呼ばれます。スマホ側でボンドを消した場合などです。

  • BLE_GAP_REPEAT_PAIRING_RETRY を返すと、NimBLE はもう一度ペアリングを試みる。その前に 古いボンドを消しておく
  • BLE_GAP_REPEAT_PAIRING_IGNORE を返すと、再ペアリングを 拒否 する(なりすましで鍵を上書きされるのを防ぎたい場合)

ハンズオンでは使いやすさを優先して、再ペアリングを許しています。

9.10 動かしてみる

cd firmware/step5_pairing
idf.py set-target esp32c3
idf.py build
idf.py -p PORT erase-flash flash monitor   # 以前のボンド情報を消すため、初回は erase-flash

9.10.1 nRF Connect でペアリングする

  1. 以前のステップで同じボードに接続したことがあれば、スマホの Bluetooth 設定 で HANDSON-C3-XXXX の登録を解除しておく

  2. nRF Connect で CONNECT する

  3. すぐに ペアリングのダイアログ が出る(ESP32-C3 からの Security Request による)。シリアルモニタには

    I (xxx) STEP5: ==== Pairing passkey: 123456 ====

    が出ている。ダイアログに 123456 を入力する

  4. シリアルモニタに enc change status=0 encrypted=1 authenticated=1 bonded=1 key_size=16 が出れば成功

  5. Step 3・4 と同じように、Notify の購読やコマンドの送信ができることを確かめる

  6. 一度 切断して、もう一度接続 する。今度は パスキーを聞かれず、enc change … bonded=1 が出る

  7. ESP32-C3 を リセット してからもう一度接続しても、パスキーは聞かれない(ボンド情報が NVS に保存されているため)

9.10.2 わざと失敗させる

  • ダイアログで キャンセル する、または 違うパスキー を入れる → enc change status=…(0 以外)が出て、Read や Notify の購読が エラー(Insufficient Authentication) になる
  • idf.py -p PORT erase-flash flash で ESP32-C3 のボンド情報だけを消す → スマホは古い鍵で暗号化しようとして失敗する。スマホ側でも登録を解除 してから接続し直す
ヒントやってみよう
  1. BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC / _AUTHEN を外し、ble_gap_security_initiate() もコメントアウトしてビルドしよう。ペアリングのダイアログでキャンセルしたあと、Counter の Notify を購読できるか? Read はできるか?
  2. sm_mitm = 0 にし、キャラクタリスティックの *_AUTHEN をすべて外してみよう。ペアリングの方式はどう変わるか?
  3. ランダムなパスキーに変えてみよう
  1. Notify は購読できてしまい、値も届きます。一方、Read は READ_ENC / READ_AUTHEN で守られているので、Insufficient Authentication で拒否されます。CCCD のパーミッションが別であることを体感できます。
  2. MITM を要求しないので、IO Capability に関係なく Just Works(パスキーの入力なし)でペアリングできるようになります(スマホによっては「ペアリングしますか?」の確認だけ出る)。暗号化はされますが、authenticated=0 になります。
重要キーポイント
  • セキュリティの設定は ble_hs_cfg.sm_*。Pairing Request に載る項目そのもの
  • アクセス制御は パーミッションフラグ。コールバックの中で確認する必要はない
  • 接続したら ble_gap_security_initiate() で暗号化を要求
  • パスキーは BLE_GAP_EVENT_PASSKEY_ACTION で ble_sm_inject_io() に渡す
  • ボンド情報は ble_store_config_init() + CONFIG_BT_NIMBLE_NVS_PERSIST で Flash に保存