Introducing BLEPairing class

move all pairing/bonding related to BLEPairing
This commit is contained in:
hathach committed 2020-02-14 12:36:46 +07:00
1 parent 5b1eeab956
commit 53c9580f71
9 files changed
+478 -335

No files matched your search

+18 -18
View File
@@ -117,27 +117,27 @@
const char* dbg_err_str(int32_t err_id); // TODO move to other place
#if CFG_DEBUG
#define LOG_LV1(...) ADALOG(__VA_ARGS__)
#define LOG_LV1_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__)
#define LOG_LV1(...) ADALOG(__VA_ARGS__)
#define LOG_LV1_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__)
#else
#define LOG_LV1(...)
#define LOG_LV1_BUFFER(...)
#define LOG_LV1(...)
#define LOG_LV1_BUFFER(...)
#endif
#if CFG_DEBUG >= 2
#define LOG_LV2(...) ADALOG(__VA_ARGS__)
#define LOG_LV2_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__)
#define LOG_LV2(...) ADALOG(__VA_ARGS__)
#define LOG_LV2_BUFFER(...) ADALOG_BUFFER(__VA_ARGS__)
#else
#define LOG_LV2(...)
#define LOG_LV2_BUFFER(...)
#define LOG_LV2(...)
#define LOG_LV2_BUFFER(...)
#endif
#if CFG_DEBUG
#if __cplusplus
#define PRINTF ::printf
#define PRINTF ::printf
#else
#define PRINTF printf
#define PRINTF printf
#endif
#define PRINT_LOCATION() PRINTF("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__)
@@ -181,14 +181,14 @@ const char* dbg_err_str(int32_t err_id); // TODO move to other place
#else
#define PRINT_LOCATION()
#define PRINT_MESS(x)
#define PRTNT_HEAP()
#define PRINT_STR(x)
#define PRINT_INT(x)
#define PRINT_HEX(x)
#define PRINT_BUFFER(buf, n)
#define ADALOG(...)
#define PRINT_LOCATION()
#define PRINT_MESS(x)
#define PRTNT_HEAP()
#define PRINT_STR(x)
#define PRINT_INT(x)
#define PRINT_HEX(x)
#define PRINT_BUFFER(buf, n)
#define ADALOG(...)
#endif
+8 -2
View File
@@ -50,7 +50,10 @@
#include "queue.h"
#include "semphr.h"
#define DEBUG_MALLOC 1
#define DELAY_FOREVER portMAX_DELAY
enum
{
TASK_PRIO_LOWEST = 0, // Idle task, should not be used
@@ -65,8 +68,11 @@ enum
#define tick2ms(tck) ( ( ((uint64_t)(tck)) * 1000) / configTICK_RATE_HZ )
#define tick2us(tck) ( ( ((uint64_t)(tck)) * 1000000) / configTICK_RATE_HZ )
#define malloc_type(type) rtos_malloc( sizeof(type) )
#define rtos_malloc_type(_type) (_type*) rtos_malloc(sizeof(_type))
#if DEBUG_MALLOC
#define rtos_malloc_type(_type) ({ LOG_LV2("MALLOC", #_type " = %d bytes", sizeof(_type)); ((_type*) rtos_malloc(sizeof(_type))); })
#else
#define rtos_malloc_type(_type) ((_type*) rtos_malloc(sizeof(_type)))
#endif
static inline void* rtos_malloc(size_t _size)
{
@@ -116,8 +116,8 @@ void setup()
Bluefruit.setName("Bluefruit52");
// Serial.println("Setting pairing PIN to: " PAIRING_PIN);
Bluefruit.setPairingDisplayCallback(pairing_display_callback);
Bluefruit.setPairingCompleteCallback(pairing_complete_callback);
Bluefruit.Pairing.setDisplayCallback(pairing_display_callback);
Bluefruit.Pairing.setCompleteCallback(pairing_complete_callback);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
@@ -51,7 +51,7 @@ void setup()
Bluefruit.setName("Bluefruit52");
Serial.println("Setting pairing PIN to: " PAIRING_PIN);
Bluefruit.setPIN(PAIRING_PIN);
Bluefruit.Pairing.setPIN(PAIRING_PIN);
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
+2 -152
View File
@@ -36,20 +36,6 @@
#include "bluefruit.h"
#ifdef NRF_CRYPTOCELL
#include "Adafruit_nRFCrypto.h"
extern nRFCrypto_ECC _ecpki;
extern nRFCrypto_ECC_PrivateKey _private_key;
extern nRFCrypto_ECC_PublicKey _public_key;
extern uint8_t _lesc_public_rawkey[1+64]; // 1 byte for header
static ble_gap_lesc_p256_pk_t _lesc_peer_pubkey;
extern void swap_key_endian(uint8_t rawkey[]);
#endif
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
@@ -73,8 +59,6 @@ BLEConnection::BLEConnection(uint16_t conn_hdl, ble_gap_evt_connected_t const* e
_hvc_sem = NULL;
_hvc_received = false;
_pair_sem = NULL;
_ediv = 0xFFFF; // invalid ediv value
_bond_keys = NULL;
}
BLEConnection::~BLEConnection()
@@ -334,157 +318,23 @@ void BLEConnection::_eventHandler(ble_evt_t* evt)
* 3. Connection is secured BLE_GAP_EVT_CONN_SEC_UPDATE
*/
//--------------------------------------------------------------------+
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress, Peer asking for our info
_bond_keys = (bond_keys_t*) rtos_malloc( sizeof(bond_keys_t));
VERIFY(_bond_keys, );
memclr(_bond_keys, sizeof(bond_keys_t));
_ediv = 0xFFFF; // invalid value for ediv
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
ble_gap_sec_params_t const* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
(void) peer;
LOG_LV2("PAIR", "Peer Params: bond = %d, mitm = %d, lesc = %d, io_caps = %d",
peer->bond, peer->mitm, peer->lesc, peer->io_caps);
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &_bond_keys->own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = (ble_gap_lesc_p256_pk_t*) (_lesc_public_rawkey+1)
},
.keys_peer = {
.p_enc_key = &_bond_keys->peer_enc,
.p_id_key = &_bond_keys->peer_id,
.p_sign_key = NULL,
.p_pk = &_lesc_peer_pubkey
}
};
ble_gap_sec_params_t sec_param = Bluefruit.getSecureParam();
// use LESC when both support it
if ( peer->lesc && sec_param.lesc )
{
// keyset.
}
VERIFY_STATUS(sd_ble_gap_sec_params_reply(_conn_hdl, BLE_GAP_SEC_STATUS_SUCCESS,
_role == BLE_GAP_ROLE_PERIPH ? &sec_param : NULL, &keyset), );
}
break;
// case BLE_GAP_EVT_PASSKEY_DISPLAY:
// {
// ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
// LOG_LV2("PAIR", "Passkey = %.6s, match request = %d", passkey_display->passkey, passkey_display->match_request);
//
// if ( Bluefruit._pair_display_cb ) ada_callback(passkey_display->passkey, 6, )
//
// if (passkey_display->match_request)
// {
// // Match request require to report the match
// // sd_ble_gap_auth_key_reply();
// }
// }
// break;
case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
{
ble_gap_evt_lesc_dhkey_request_t* dhkey_req = &evt->evt.gap_evt.params.lesc_dhkey_request;
if ( dhkey_req->oobd_req )
{
// Out of Band not supported yet
}
uint8_t peer_raw_pubkey[64+1];
ble_gap_lesc_dhkey_t dhkey;
peer_raw_pubkey[0] = CRYS_EC_PointUncompressed;
memcpy(peer_raw_pubkey+1, dhkey_req->p_pk_peer->pk, 64);
swap_key_endian(peer_raw_pubkey+1);
swap_key_endian(peer_raw_pubkey+1+32);
nRFCrypto_ECC_PublicKey peer_pubkey;
peer_pubkey.begin(CRYS_ECPKI_DomainID_secp256r1);
peer_pubkey.fromRaw(peer_raw_pubkey, sizeof(peer_raw_pubkey));
nRFCrypto_ECC::SVDP_DH(_private_key, peer_pubkey, dhkey.key, sizeof(dhkey.key));
swap_key_endian(dhkey.key);
sd_ble_gap_lesc_dhkey_reply(_conn_hdl, &dhkey);
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
// Pairing process completed
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
LOG_LV2("PAIR", "Auth Status = 0x%02X, Bonded = %d, LESC = %d, Our Kdist = 0x%02X, Peer Kdist = 0x%02X ",
status->auth_status, status->bonded, status->lesc, *((uint8_t*) &status->kdist_own), *((uint8_t*) &status->kdist_peer));
// Pairing succeeded --> save encryption keys ( Bonding )
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
_paired = true;
_ediv = _bond_keys->own_enc.master_id.ediv;
bond_save_keys(_role, _conn_hdl, _bond_keys);
}
rtos_free(_bond_keys);
_bond_keys = NULL;
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Peer asks for the stored keys.
// - load key and return if bonded previously.
// - Else return NULL --> Initiate key exchange
ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
bond_keys_t bkeys;
varclr(&bkeys);
if ( bond_load_keys(_role, sec_req->master_id.ediv, &bkeys) )
{
sd_ble_gap_sec_info_reply(_conn_hdl, &bkeys.own_enc.enc_info, &bkeys.peer_id.id_info, NULL);
_ediv = bkeys.own_enc.master_id.ediv;
} else
{
sd_ble_gap_sec_info_reply(_conn_hdl, NULL, NULL, NULL);
}
// Pairing succeeded
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) _paired = true;
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec;
LOG_LV2("PAIR", "Security Mode = %d, Level = %d", conn_sec->sec_mode.sm, conn_sec->sec_mode.lv);
// Connection is secured (paired) if encryption level > 1
if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) )
{
// Previously bonded --> secure by re-connection process --> Load & Set SysAttr (Apply Service Context)
// Else Init SysAttr (first bonded)
if ( !bond_load_cccd(_role, _conn_hdl, _ediv) )
{
sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0);
}
_paired = true;
}
+359
View File
@@ -0,0 +1,359 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ha Thach (tinyusb.org) for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "bluefruit.h"
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
#define EDIV_INVALID 0xFFFF
//------------- IMPLEMENTATION -------------//
// convert 32-byte Number from Big <-> Little Endian to use with BLE
// Public Key = 32-byte N1 + 32-byte N2
void swap_key_endian(uint8_t rawkey[])
{
for(uint8_t i=0; i<32/2; i++)
{
uint8_t const p1 = i;
uint8_t const p2 = (31-i);
uint8_t temp = rawkey[p1];
rawkey[p1] = rawkey[p2];
rawkey[p2] = temp;
}
}
BLEPairing::BLEPairing(void)
{
_sec_param = ((ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
});
_ediv = EDIV_INVALID;
_bond_keys = NULL;
_display_cb = NULL;
_complete_cb = NULL;
}
bool BLEPairing::begin(void)
{
#ifdef NRF_CRYPTOCELL
// Initalize Crypto lib for LESC (safe to call multiple times)
nRFCrypto.begin();
// Init Private key
_private_key.begin(CRYS_ECPKI_DomainID_secp256r1);
// init public key
nRFCrypto_ECC_PublicKey pubkey;
pubkey.begin(CRYS_ECPKI_DomainID_secp256r1);
// Generate ECC Key pair
nRFCrypto_ECC::genKeyPair(_private_key, pubkey);
// Convert to Raw bytes to response to LESC event
pubkey.toRaw(_public_key_raw, sizeof(_public_key_raw));
pubkey.end();
// BLE use Little Endian, swap public key endian
// Public Key = 32-byte N1 + 32-byte N2
swap_key_endian(_public_key_raw+1);
swap_key_endian(_public_key_raw+1+32);
#endif
return true;
}
uint8_t* BLEPairing::getPublicKey(void)
{
// skip header byte
return _public_key_raw+1;
}
// Use Legacy SC static Passkey
bool BLEPairing::setPIN(const char* pin)
{
// back to open mode
if (pin == NULL)
{
_sec_param.bond = 1;
_sec_param.mitm = 0;
_sec_param.lesc = 0; // TODO NRF_CRYPTOCELL
_sec_param.io_caps = BLE_GAP_IO_CAPS_NONE;
}else
{
VERIFY ( strlen(pin) == BLE_GAP_PASSKEY_LEN );
// Static Passkey requires using
// - Legacy SC
// - IO cap: Display
// - MITM is on
_sec_param.bond = 1;
_sec_param.mitm = 1;
_sec_param.lesc = 0;
_sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
ble_opt_t opt;
opt.gap_opt.passkey.p_passkey = (const uint8_t*) pin;
VERIFY_STATUS( sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opt), false);
}
return true;
}
// Pairing using LESC with peripheral display
bool BLEPairing::setDisplayCallback(pair_display_cb_t fp)
{
_display_cb = fp;
if ( fp == NULL )
{
// TODO callback clear
}else
{
_sec_param.bond = 1;
_sec_param.mitm = 1;
// TODO NRF_CRYPTOCELL
// _sec_param.lesc = 0;
// _sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
_sec_param.lesc = 1;
_sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
ble_opt_t opt;
opt.gap_opt.passkey.p_passkey = NULL; // generate Passkey randomly
VERIFY_STATUS( sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opt), false);
}
return true;
}
void BLEPairing::setCompleteCallback(pair_complete_cb_t fp)
{
_complete_cb = fp;
}
//--------------------------------------------------------------------+
/* First-time Pairing
*
* Connect -> SEC_PARAMS_REQUEST -> PASSKEY_DISPLAY -> BLE_GAP_EVT_LESC_DHKEY_REQUEST ->
* CONN_SEC_UPDATE -> AUTH_STATUS
* 1. Either we or peer initiate the process
* 2. Peer ask for Secure Parameter ( I/O Caps ) BLE_GAP_EVT_SEC_PARAMS_REQUEST
* 3. Pair PassKey exchange
* 4. Connection is secured BLE_GAP_EVT_CONN_SEC_UPDATE
* 5. Long term Keys exchanged BLE_GAP_EVT_AUTH_STATUS
*
* Reconnect using bonded key
* Connect -> SEC_INFO_REQUEST -> CONN_SEC_UPDATE
* 1. Either we or peer initiate the process
* 2. Peer ask for Secure Info ( bond keys ) BLE_GAP_EVT_SEC_INFO_REQUEST
* 3. Connection is secured BLE_GAP_EVT_CONN_SEC_UPDATE
*/
//--------------------------------------------------------------------+
void BLEPairing::_eventHandler(ble_evt_t* evt)
{
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
switch(evt->header.evt_id)
{
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress, Peer asking for our info
_bond_keys = rtos_malloc_type(bond_keys_t);
VERIFY(_bond_keys, );
memclr(_bond_keys, sizeof(bond_keys_t));
_ediv = EDIV_INVALID;
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
ble_gap_sec_params_t const* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
(void) peer;
LOG_LV2("PAIR", "Peer Params: bond = %d, mitm = %d, lesc = %d, io_caps = %d",
peer->bond, peer->mitm, peer->lesc, peer->io_caps);
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &_bond_keys->own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = (ble_gap_lesc_p256_pk_t*) (_public_key_raw+1)
},
.keys_peer = {
.p_enc_key = &_bond_keys->peer_enc,
.p_id_key = &_bond_keys->peer_id,
.p_sign_key = NULL,
.p_pk = (ble_gap_lesc_p256_pk_t*) (_peer_pubkey_raw+1)
}
};
// use LESC when both support it
if ( peer->lesc && _sec_param.lesc )
{
// keyset.
}
VERIFY_STATUS(sd_ble_gap_sec_params_reply(conn_hdl, BLE_GAP_SEC_STATUS_SUCCESS,
conn->getRole() == BLE_GAP_ROLE_PERIPH ? &_sec_param : NULL, &keyset), );
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
LOG_LV2("PAIR", "Passkey = %.6s, match request = %d", passkey_display->passkey, passkey_display->match_request);
// Invoke display callback
if ( _display_cb ) ada_callback(passkey_display->passkey, 6, _display_cb, conn_hdl, passkey_display->passkey);
if (passkey_display->match_request)
{
// Match request require to report the match
// sd_ble_gap_auth_key_reply();
}
}
break;
case BLE_GAP_EVT_LESC_DHKEY_REQUEST:
{
ble_gap_evt_lesc_dhkey_request_t* dhkey_req = &evt->evt.gap_evt.params.lesc_dhkey_request;
if ( dhkey_req->oobd_req )
{
// Out of Band not supported yet
}
uint8_t peer_raw_pubkey[64+1];
ble_gap_lesc_dhkey_t dhkey;
peer_raw_pubkey[0] = CRYS_EC_PointUncompressed;
memcpy(peer_raw_pubkey+1, dhkey_req->p_pk_peer->pk, 64);
swap_key_endian(peer_raw_pubkey+1);
swap_key_endian(peer_raw_pubkey+1+32);
nRFCrypto_ECC_PublicKey peer_pubkey;
peer_pubkey.begin(CRYS_ECPKI_DomainID_secp256r1);
peer_pubkey.fromRaw(peer_raw_pubkey, sizeof(peer_raw_pubkey));
nRFCrypto_ECC::SVDP_DH(_private_key, peer_pubkey, dhkey.key, sizeof(dhkey.key));
swap_key_endian(dhkey.key);
sd_ble_gap_lesc_dhkey_reply(conn_hdl, &dhkey);
}
break;
// Pairing process completed
case BLE_GAP_EVT_AUTH_STATUS:
{
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
LOG_LV2("PAIR", "Auth Status = 0x%02X, Bonded = %d, LESC = %d, Our Kdist = 0x%02X, Peer Kdist = 0x%02X ",
status->auth_status, status->bonded, status->lesc, *((uint8_t*) &status->kdist_own), *((uint8_t*) &status->kdist_peer));
// Pairing succeeded --> save encryption keys ( Bonding )
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
_ediv = _bond_keys->own_enc.master_id.ediv;
bond_save_keys(conn->getRole(), conn_hdl, _bond_keys);
// _paired = true;
}
rtos_free(_bond_keys);
_bond_keys = NULL;
// Invoke callback
if (_complete_cb) ada_callback(NULL, 0, _complete_cb, conn_hdl, status->auth_status);
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Peer asks for the stored keys.
// - load key and return if bonded previously.
// - Else return NULL --> Initiate key exchange
ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
bond_keys_t bkeys;
varclr(&bkeys);
if ( bond_load_keys(conn->getRole(), sec_req->master_id.ediv, &bkeys) )
{
sd_ble_gap_sec_info_reply(conn_hdl, &bkeys.own_enc.enc_info, &bkeys.peer_id.id_info, NULL);
_ediv = bkeys.own_enc.master_id.ediv;
} else
{
sd_ble_gap_sec_info_reply(conn_hdl, NULL, NULL, NULL);
}
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec;
LOG_LV2("PAIR", "Security Mode = %d, Level = %d", conn_sec->sec_mode.sm, conn_sec->sec_mode.lv);
// Connection is secured (paired) if encryption level > 1
if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) )
{
// Previously bonded --> secure by re-connection process --> Load & Set SysAttr (Apply Service Context)
// Else Init SysAttr (first bonded)
if ( !bond_load_cccd(conn->getRole(), conn_hdl, _ediv) )
{
sd_ble_gatts_sys_attr_set(conn_hdl, NULL, 0, 0);
}
// _paired = true;
}
// if (_pair_sem) xSemaphoreGive(_pair_sem);
}
break;
default: break;
}
}
+75
View File
@@ -0,0 +1,75 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ha Thach (tinyusb.org) for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef BLEPAIRING_H_
#define BLEPAIRING_H_
#include "bluefruit_common.h"
#include "utility/bonding.h"
#ifdef NRF_CRYPTOCELL
#include "Adafruit_nRFCrypto.h"
#endif
class BLEPairing
{
public:
typedef void (*pair_display_cb_t ) (uint16_t conn_hdl, uint8_t const passkey[6]);
typedef void (*pair_complete_cb_t) (uint16_t conn_hdl, uint8_t auth_status);
BLEPairing(void);
bool begin(void);
uint8_t* getPublicKey(void);
// Static Passkey
bool setPIN(const char* pin);
//------------- Callbacks -------------//
bool setDisplayCallback(pair_display_cb_t fp);
void setCompleteCallback(pair_complete_cb_t fp);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal
* code. User should not call these directly
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
private:
ble_gap_sec_params_t _sec_param;
uint8_t _public_key_raw[1+64]; // raw key: 1 header + 64 data
uint8_t _peer_pubkey_raw[1+64];
nRFCrypto_ECC_PrivateKey _private_key;
uint16_t _ediv;
bond_keys_t* _bond_keys; // Shared keys with bonded device, size ~ 80 bytes
pair_display_cb_t _display_cb;
pair_complete_cb_t _complete_cb;
};
#endif /* BLEPAIRING_H_ */
+7 -150
View File
@@ -37,32 +37,6 @@
#include "bluefruit.h"
#include "utility/bonding.h"
#ifdef NRF_CRYPTOCELL
#include "Adafruit_nRFCrypto.h"
nRFCrypto_ECC _ecpki;
nRFCrypto_ECC_PrivateKey _private_key;
nRFCrypto_ECC_PublicKey _public_key;
uint8_t _lesc_public_rawkey[1+64]; // 1 byte for header
// convert 32-byte Number from Big <-> Little Endian to use with BLE
// Public Key = 32-byte N1 + 32-byte N2
void swap_key_endian(uint8_t rawkey[])
{
for(uint8_t i=0; i<32/2; i++)
{
uint8_t const p1 = i;
uint8_t const p2 = (31-i);
uint8_t temp = rawkey[p1];
rawkey[p1] = rawkey[p2];
rawkey[p2] = temp;
}
}
#endif
#ifndef CFG_BLE_TX_POWER_LEVEL
#define CFG_BLE_TX_POWER_LEVEL 0
#endif
@@ -203,22 +177,6 @@ AdafruitBluefruit::AdafruitBluefruit(void)
_event_cb = NULL;
_rssi_cb = NULL;
_pair_display_cb = NULL;
_pair_complete_cb = NULL;
_sec_param = ((ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
});
#ifdef NRF_CRYPTOCELL
// _sec_param.lesc = 1; // enable LESC if CryptoCell is present
@@ -486,6 +444,8 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// Init Peripheral role
VERIFY( Periph.begin() );
Pairing.begin();
// Default device name
ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN;
VERIFY_STATUS(sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) CFG_DEFAULT_NAME, strlen(CFG_DEFAULT_NAME)), false);
@@ -522,26 +482,6 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// Initialize bonding
bond_init();
// Initalize Crypto lib for LESC
#ifdef NRF_CRYPTOCELL
nRFCrypto.begin();
_ecpki.begin();
_private_key.begin(CRYS_ECPKI_DomainID_secp256r1);
_public_key.begin(CRYS_ECPKI_DomainID_secp256r1);
nRFCrypto_ECC::genKeyPair(_private_key, _public_key);
_public_key.toRaw(_lesc_public_rawkey, sizeof(_lesc_public_rawkey));
// PRINT_BUFFER(_lesc_public_rawkey+1, sizeof(_lesc_public_rawkey)-1);
// Public Key = 32-byte N1 + 32-byte N2
swap_key_endian(_lesc_public_rawkey+1);
swap_key_endian(_lesc_public_rawkey+1+32);
// PRINT_BUFFER(_lesc_public_rawkey+1, sizeof(_lesc_public_rawkey)-1);
#endif
return true;
}
@@ -707,69 +647,6 @@ void AdafruitBluefruit::setRssiCallback(rssi_cb_t fp)
}
// Use Legacy SC static Passkey
bool AdafruitBluefruit::setPIN(const char* pin)
{
// back to open mode
if (pin == NULL)
{
_sec_param.bond = 1;
_sec_param.mitm = 0;
_sec_param.lesc = 0; // TODO NRF_CRYPTOCELL
_sec_param.io_caps = BLE_GAP_IO_CAPS_NONE;
}else
{
VERIFY ( strlen(pin) == BLE_GAP_PASSKEY_LEN );
// Static Passkey requires using
// - Legacy SC
// - IO cap: Display
// - MITM is on
_sec_param.bond = 1;
_sec_param.mitm = 1;
_sec_param.lesc = 0;
_sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
ble_opt_t opt;
opt.gap_opt.passkey.p_passkey = (const uint8_t*) pin;
VERIFY_STATUS( sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opt), false);
}
return true;
}
// Pairing using LESC with peripheral display
bool AdafruitBluefruit::setPairingDisplayCallback(pair_display_cb_t fp)
{
_pair_display_cb = fp;
if ( fp == NULL )
{
// TODO callback clear
}else
{
_sec_param.bond = 1;
_sec_param.mitm = 1;
// TODO NRF_CRYPTOCELL
// _sec_param.lesc = 0;
// _sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
_sec_param.lesc = 1;
_sec_param.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
ble_opt_t opt;
opt.gap_opt.passkey.p_passkey = NULL; // generate Passkey randomly
VERIFY_STATUS( sd_ble_opt_set(BLE_GAP_OPT_PASSKEY, &opt), false);
}
return true;
}
void AdafruitBluefruit::setPairingCompleteCallback(pair_complete_cb_t fp)
{
_pair_complete_cb = fp;
}
/*------------------------------------------------------------------*/
/* Thread & SoftDevice Event handler
*------------------------------------------------------------------*/
@@ -881,7 +758,11 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
LOG_LV2("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl);
// GAP handler
if ( conn ) conn->_eventHandler(evt);
if ( conn )
{
conn->_eventHandler(evt);
Pairing._eventHandler(evt);
}
switch(evt->header.evt_id)
{
@@ -954,30 +835,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
LOG_LV2("PAIR", "Passkey = %.6s, match request = %d", passkey_display->passkey, passkey_display->match_request);
// Invoke display callback
if ( _pair_display_cb ) ada_callback(passkey_display->passkey, 6, _pair_display_cb, conn_hdl, passkey_display->passkey);
if (passkey_display->match_request)
{
// Match request require to report the match
// sd_ble_gap_auth_key_reply();
}
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
if (_pair_complete_cb) ada_callback(NULL, 0, _pair_complete_cb, conn_hdl, status->auth_status);
}
break;
case BLE_EVT_USER_MEM_REQUEST:
// We will handle Long Write sequence (RW Authorize PREP_WRITE_REQ)
sd_ble_user_mem_reply(conn_hdl, NULL);
+6 -10
View File
@@ -50,6 +50,7 @@
#include "BLEDiscovery.h"
#include "BLEConnection.h"
#include "BLEGatt.h"
#include "BLEPairing.h"
// Services
#include "services/BLEDis.h"
@@ -97,21 +98,20 @@ class AdafruitBluefruit
public:
typedef void (*event_cb_t) (ble_evt_t* evt);
typedef void (*rssi_cb_t) (uint16_t conn_hdl, int8_t rssi);
typedef void (*pair_display_cb_t ) (uint16_t conn_hdl, uint8_t const passkey[6]);
typedef void (*pair_complete_cb_t) (uint16_t conn_hdl, uint8_t auth_status);
AdafruitBluefruit(void); // Constructor
AdafruitBluefruit(void);
/*------------------------------------------------------------------*/
/* Lower Level Classes (Bluefruit.Advertising.*, etc.)
*------------------------------------------------------------------*/
BLEPeriph Periph;
BLECentral Central;
BLEPairing Pairing;
BLEGatt Gatt;
BLEAdvertising Advertising;
BLEAdvertisingData ScanResponse;
BLEScanner Scanner;
BLEPeriph Periph;
BLECentral Central;
BLEDiscovery Discovery;
/*------------------------------------------------------------------*/
@@ -175,9 +175,6 @@ class AdafruitBluefruit
// Security
//--------------------------------------------------------------------+
ble_gap_sec_params_t getSecureParam(void) { return _sec_param; }
bool setPIN(const char* pin); // Static Passkey
bool setPairingDisplayCallback(pair_display_cb_t fp);
void setPairingCompleteCallback(pair_complete_cb_t fp);
/*------------------------------------------------------------------*/
/* Callbacks
@@ -222,6 +219,7 @@ class AdafruitBluefruit
SemaphoreHandle_t _ble_event_sem;
SemaphoreHandle_t _soc_event_sem;
// Auto LED Blinky
TimerHandle_t _led_blink_th;
bool _led_conn;
@@ -232,8 +230,6 @@ class AdafruitBluefruit
//------------- Callbacks -------------//
rssi_cb_t _rssi_cb;
event_cb_t _event_cb;
pair_display_cb_t _pair_display_cb;
pair_complete_cb_t _pair_complete_cb;
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY