From 9da05fac773eac88cf843bf94419c4f21bc978ce Mon Sep 17 00:00:00 2001 From: Darshan Dobariya Date: Mon, 26 Feb 2024 11:56:32 +0530 Subject: [PATCH] feat(nimble): Authorize or deauthorize a BLE device for a connection --- nimble/host/include/host/ble_esp_gap.h | 17 ++++++++++++++++ nimble/host/include/host/ble_gap.h | 4 ++++ nimble/host/src/ble_gap.c | 28 ++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/nimble/host/include/host/ble_esp_gap.h b/nimble/host/include/host/ble_esp_gap.h index d62ab9373..3da02bbb4 100644 --- a/nimble/host/include/host/ble_esp_gap.h +++ b/nimble/host/include/host/ble_esp_gap.h @@ -63,6 +63,23 @@ int ble_gap_clear_legacy_adv(void); int ble_gap_duplicate_exception_list(uint8_t subcode, uint8_t type, uint8_t *value, void *cb); #endif +/** + * Authorizes or deauthorizes a BLE device for a connection. + * + * This function updates the security flags of a BLE connection to authorize or + * deauthorize a device for the specified connection. + * + * @param conn_handle The handle corresponding to the connection to + * authorize. + * @param authorized Authorized the device or not. + * + * @return 0 on success; + * BLE_HS_ENOTCONN if the connection handle is not found. + * BLE_HS_EAUTHOR if the device is not authenticated before authorization. + */ +int +ble_gap_dev_authorization(uint16_t conn_handle, bool authorized); + void ble_gap_rx_test_evt(const void *buf, uint8_t len); void ble_gap_tx_test_evt(const void *buf, uint8_t len); void ble_gap_end_test_evt(const void *buf, uint8_t len); diff --git a/nimble/host/include/host/ble_gap.h b/nimble/host/include/host/ble_gap.h index 0c3a07106..35dd203fd 100644 --- a/nimble/host/include/host/ble_gap.h +++ b/nimble/host/include/host/ble_gap.h @@ -202,6 +202,10 @@ struct ble_gap_sec_state { /** Size of a key used for encryption */ unsigned key_size:5; + + /** Current device security state*/ + unsigned authorize:1; + }; /** Advertising parameters */ diff --git a/nimble/host/src/ble_gap.c b/nimble/host/src/ble_gap.c index 8a0c2beec..5eb4d54df 100644 --- a/nimble/host/src/ble_gap.c +++ b/nimble/host/src/ble_gap.c @@ -6247,6 +6247,34 @@ done: #endif } +int +ble_gap_dev_authorization(uint16_t conn_handle, bool authorized) +{ + struct ble_hs_conn *conn = ble_hs_conn_find(conn_handle); + + if (conn != NULL) { + if (!(conn->bhc_sec_state.authenticated)) { + // Device should be authenticated before authorization + BLE_HS_LOG(ERROR, "Authorized should occur after successful Authentication(MITM protection) \n"); + return BLE_HS_EAUTHOR; + } + + // Update connection security flags + if (authorized) { + conn->bhc_sec_state.authorize = 1; + } else { + conn->bhc_sec_state.authorize = 0; + } + + } else { + // Connection handle not found + BLE_HS_LOG(ERROR, "Can't find connection \n"); + return BLE_HS_ENOTCONN; + } + + return 0; +} + int ble_gap_pair_initiate(uint16_t conn_handle) {