security_dispatcher.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. /**
  2. * Copyright (c) 2015 - 2018, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. #include "sdk_common.h"
  41. #if NRF_MODULE_ENABLED(PEER_MANAGER)
  42. #include "security_dispatcher.h"
  43. #include <string.h>
  44. #include "ble.h"
  45. #include "ble_gap.h"
  46. #include "ble_err.h"
  47. #include "ble_conn_state.h"
  48. #include "peer_manager_types.h"
  49. #include "peer_data_storage.h"
  50. #include "peer_database.h"
  51. #include "id_manager.h"
  52. #if PM_RA_PROTECTION_ENABLED
  53. #include "auth_status_tracker.h"
  54. #endif // PM_RA_PROTECTION_ENABLED
  55. #define NRF_LOG_MODULE_NAME peer_manager_smd
  56. #if PM_LOG_ENABLED
  57. #define NRF_LOG_LEVEL PM_LOG_LEVEL
  58. #define NRF_LOG_INFO_COLOR PM_LOG_INFO_COLOR
  59. #define NRF_LOG_DEBUG_COLOR PM_LOG_DEBUG_COLOR
  60. #else
  61. #define NRF_LOG_LEVEL 0
  62. #endif // PM_LOG_ENABLED
  63. #include "nrf_log.h"
  64. #include "nrf_log_ctrl.h"
  65. NRF_LOG_MODULE_REGISTER();
  66. #include "nrf_strerror.h"
  67. #ifndef PM_CENTRAL_ENABLED
  68. #define PM_CENTRAL_ENABLED 1
  69. #endif
  70. // The number of registered event handlers.
  71. #define SMD_EVENT_HANDLERS_CNT (sizeof(m_evt_handlers) / sizeof(m_evt_handlers[0]))
  72. STATIC_ASSERT((NRF_SDH_BLE_CENTRAL_LINK_COUNT == 0) || PM_CENTRAL_ENABLED,
  73. "Peer Manager Central operation must be enabled when using central links.");
  74. // Security Dispacher event handlers in Security Manager and GATT Cache Manager.
  75. extern void sm_smd_evt_handler(pm_evt_t * p_event);
  76. // Security Dispatcher events' handlers.
  77. // The number of elements in this array is SMD_EVENT_HANDLERS_CNT.
  78. static pm_evt_handler_internal_t const m_evt_handlers[] =
  79. {
  80. sm_smd_evt_handler
  81. };
  82. static bool m_module_initialized;
  83. static ble_conn_state_user_flag_id_t m_flag_sec_proc = BLE_CONN_STATE_USER_FLAG_INVALID;
  84. static ble_conn_state_user_flag_id_t m_flag_sec_proc_pairing = BLE_CONN_STATE_USER_FLAG_INVALID;
  85. static ble_conn_state_user_flag_id_t m_flag_sec_proc_bonding = BLE_CONN_STATE_USER_FLAG_INVALID;
  86. static ble_conn_state_user_flag_id_t m_flag_allow_repairing = BLE_CONN_STATE_USER_FLAG_INVALID;
  87. static ble_gap_lesc_p256_pk_t m_peer_pk;
  88. static __INLINE bool sec_procedure(uint16_t conn_handle)
  89. {
  90. return ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc);
  91. }
  92. static __INLINE bool pairing(uint16_t conn_handle)
  93. {
  94. return ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc_pairing);
  95. }
  96. static __INLINE bool bonding(uint16_t conn_handle)
  97. {
  98. return ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc_bonding);
  99. }
  100. static __INLINE bool allow_repairing(uint16_t conn_handle)
  101. {
  102. return ble_conn_state_user_flag_get(conn_handle, m_flag_allow_repairing);
  103. }
  104. /**@brief Function for sending an SMD event to all event handlers.
  105. *
  106. * @param[in] p_event The event to pass to all event handlers.
  107. */
  108. static void evt_send(pm_evt_t * p_event)
  109. {
  110. p_event->peer_id = im_peer_id_get_by_conn_handle(p_event->conn_handle);
  111. for (uint32_t i = 0; i < SMD_EVENT_HANDLERS_CNT; i++)
  112. {
  113. m_evt_handlers[i](p_event);
  114. }
  115. }
  116. /**@brief Function for sending a PM_EVT_CONN_SEC_START event.
  117. *
  118. * @param[in] conn_handle The connection handle the event pertains to.
  119. * @param[in] procedure The procedure that has started on the connection.
  120. */
  121. static void sec_start_send(uint16_t conn_handle,
  122. pm_conn_sec_procedure_t procedure)
  123. {
  124. pm_evt_t evt =
  125. {
  126. .evt_id = PM_EVT_CONN_SEC_START,
  127. .conn_handle = conn_handle,
  128. .params = {.conn_sec_start = {.procedure = procedure}}
  129. };
  130. evt_send(&evt);
  131. }
  132. /**@brief Function for sending a PM_EVT_ERROR_UNEXPECTED event.
  133. *
  134. * @param[in] conn_handle The connection handle the event pertains to.
  135. * @param[in] err_code The unexpected error that occurred.
  136. */
  137. static void send_unexpected_error(uint16_t conn_handle, ret_code_t err_code)
  138. {
  139. pm_evt_t error_evt =
  140. {
  141. .evt_id = PM_EVT_ERROR_UNEXPECTED,
  142. .conn_handle = conn_handle,
  143. .params =
  144. {
  145. .error_unexpected =
  146. {
  147. .error = err_code,
  148. .fds_error = false
  149. }
  150. }
  151. };
  152. evt_send(&error_evt);
  153. }
  154. /**@brief Function for sending a PM_EVT_STORAGE_FULL event.
  155. *
  156. * @param[in] conn_handle The connection handle the event pertains to.
  157. */
  158. static void send_storage_full_evt(uint16_t conn_handle)
  159. {
  160. pm_evt_t evt =
  161. {
  162. .evt_id = PM_EVT_STORAGE_FULL,
  163. .conn_handle = conn_handle
  164. };
  165. evt_send(&evt);
  166. }
  167. /**@brief Function for cleaning up after a failed security procedure.
  168. *
  169. * @param[in] conn_handle The handle of the connection the security procedure happens on.
  170. * @param[in] procedure The procedure that failed.
  171. * @param[in] error The error the procedure failed with.
  172. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES.
  173. */
  174. static void conn_sec_failure(uint16_t conn_handle,
  175. pm_conn_sec_procedure_t procedure,
  176. pm_sec_error_code_t error,
  177. uint8_t error_src)
  178. {
  179. pm_evt_t evt =
  180. {
  181. .evt_id = PM_EVT_CONN_SEC_FAILED,
  182. .conn_handle = conn_handle,
  183. .params =
  184. {
  185. .conn_sec_failed =
  186. {
  187. .procedure = procedure,
  188. .error = error,
  189. .error_src = error_src,
  190. }
  191. }
  192. };
  193. ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, false);
  194. evt_send(&evt);
  195. return;
  196. }
  197. /**@brief Function for cleaning up after a failed pairing procedure.
  198. *
  199. * @param[in] conn_handle The handle of the connection the pairing procedure happens on.
  200. * @param[in] error The error the procedure failed with.
  201. * @param[in] error_src The source of the error (local or remote). See @ref
  202. * BLE_GAP_SEC_STATUS_SOURCES.
  203. */
  204. static void pairing_failure(uint16_t conn_handle,
  205. pm_sec_error_code_t error,
  206. uint8_t error_src)
  207. {
  208. ret_code_t err_code = NRF_SUCCESS;
  209. pm_conn_sec_procedure_t procedure = bonding(conn_handle) ? PM_CONN_SEC_PROCEDURE_BONDING
  210. : PM_CONN_SEC_PROCEDURE_PAIRING;
  211. err_code = pdb_write_buf_release(PDB_TEMP_PEER_ID(conn_handle), PM_PEER_DATA_ID_BONDING);
  212. if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_NOT_FOUND /* No buffer was allocated */))
  213. {
  214. NRF_LOG_ERROR("Could not clean up after failed bonding procedure. "\
  215. "pdb_write_buf_release() returned %s. conn_handle: %d.",
  216. nrf_strerror_get(err_code),
  217. conn_handle);
  218. send_unexpected_error(conn_handle, err_code);
  219. }
  220. conn_sec_failure(conn_handle, procedure, error, error_src);
  221. return;
  222. }
  223. /**@brief Function for cleaning up after a failed encryption procedure.
  224. *
  225. * @param[in] conn_handle The handle of the connection the encryption procedure happens on.
  226. * @param[in] error The error the procedure failed with.
  227. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES.
  228. */
  229. static __INLINE void encryption_failure(uint16_t conn_handle,
  230. pm_sec_error_code_t error,
  231. uint8_t error_src)
  232. {
  233. conn_sec_failure(conn_handle, PM_CONN_SEC_PROCEDURE_ENCRYPTION, error, error_src);
  234. return;
  235. }
  236. /**@brief Function for possibly cleaning up after a failed pairing or encryption procedure.
  237. *
  238. * @param[in] conn_handle The handle of the connection the pairing procedure happens on.
  239. * @param[in] error The error the procedure failed with.
  240. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES.
  241. */
  242. static void link_secure_failure(uint16_t conn_handle,
  243. pm_sec_error_code_t error,
  244. uint8_t error_src)
  245. {
  246. if (sec_procedure(conn_handle))
  247. {
  248. if (pairing(conn_handle))
  249. {
  250. pairing_failure(conn_handle, error, error_src);
  251. }
  252. else
  253. {
  254. encryption_failure(conn_handle, error, error_src);
  255. }
  256. }
  257. }
  258. /**@brief Function for administrative actions to be taken when a security process has started.
  259. *
  260. * @param[in] conn_handle The connection the security process was attempted on.
  261. * @param[in] success Whether the procedure was started successfully.
  262. * @param[in] procedure The procedure that was started.
  263. */
  264. static void sec_proc_start(uint16_t conn_handle,
  265. bool success,
  266. pm_conn_sec_procedure_t procedure)
  267. {
  268. ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, success);
  269. if (success)
  270. {
  271. ble_conn_state_user_flag_set(conn_handle,
  272. m_flag_sec_proc_pairing,
  273. (procedure != PM_CONN_SEC_PROCEDURE_ENCRYPTION));
  274. ble_conn_state_user_flag_set(conn_handle,
  275. m_flag_sec_proc_bonding,
  276. (procedure == PM_CONN_SEC_PROCEDURE_BONDING));
  277. sec_start_send(conn_handle, procedure);
  278. }
  279. }
  280. /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_INFO_REQUEST event from the SoftDevice.
  281. *
  282. * @param[in] p_gap_evt The event from the SoftDevice.
  283. */
  284. static void sec_info_request_process(ble_gap_evt_t const * p_gap_evt)
  285. {
  286. ret_code_t err_code;
  287. ble_gap_enc_info_t const * p_enc_info = NULL;
  288. pm_peer_data_flash_t peer_data;
  289. pm_peer_id_t peer_id = im_peer_id_get_by_master_id(
  290. &p_gap_evt->params.sec_info_request.master_id);
  291. if (peer_id == PM_PEER_ID_INVALID)
  292. {
  293. peer_id = im_peer_id_get_by_conn_handle(p_gap_evt->conn_handle);
  294. }
  295. else
  296. {
  297. // The peer might have been unrecognized until now (since connecting). E.g. if using a
  298. // random non-resolvable advertising address. Report the discovered peer ID just in case.
  299. im_new_peer_id(p_gap_evt->conn_handle, peer_id);
  300. }
  301. sec_proc_start(p_gap_evt->conn_handle, true, PM_CONN_SEC_PROCEDURE_ENCRYPTION);
  302. if (peer_id != PM_PEER_ID_INVALID)
  303. {
  304. err_code = pdb_peer_data_ptr_get(peer_id, PM_PEER_DATA_ID_BONDING, &peer_data);
  305. if (err_code == NRF_SUCCESS)
  306. {
  307. // There is stored bonding data for this peer.
  308. ble_gap_enc_key_t const * p_existing_key = &peer_data.p_bonding_data->own_ltk;
  309. if ( p_existing_key->enc_info.lesc
  310. || (im_master_ids_compare(&p_existing_key->master_id,
  311. &p_gap_evt->params.sec_info_request.master_id)))
  312. {
  313. p_enc_info = &p_existing_key->enc_info;
  314. }
  315. }
  316. }
  317. err_code = sd_ble_gap_sec_info_reply(p_gap_evt->conn_handle, p_enc_info, NULL, NULL);
  318. if (err_code != NRF_SUCCESS)
  319. {
  320. NRF_LOG_ERROR("Could not complete encryption procedure. sd_ble_gap_sec_info_reply() "\
  321. "returned %s. conn_handle: %d, peer_id: %d.",
  322. nrf_strerror_get(err_code),
  323. p_gap_evt->conn_handle,
  324. peer_id);
  325. send_unexpected_error(p_gap_evt->conn_handle, err_code);
  326. }
  327. else if (p_enc_info == NULL)
  328. {
  329. encryption_failure(p_gap_evt->conn_handle,
  330. PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING,
  331. BLE_GAP_SEC_STATUS_SOURCE_LOCAL);
  332. }
  333. return;
  334. }
  335. /**@brief Function for sending a CONFIG_REQ event.
  336. *
  337. * @param[in] conn_handle The connection the sec parameters are needed for.
  338. */
  339. static void send_config_req(uint16_t conn_handle)
  340. {
  341. pm_evt_t evt;
  342. memset(&evt, 0, sizeof(evt));
  343. evt.evt_id = PM_EVT_CONN_SEC_CONFIG_REQ;
  344. evt.conn_handle = conn_handle;
  345. evt_send(&evt);
  346. }
  347. void smd_conn_sec_config_reply(uint16_t conn_handle, pm_conn_sec_config_t * p_conn_sec_config)
  348. {
  349. NRF_PM_DEBUG_CHECK(m_module_initialized);
  350. NRF_PM_DEBUG_CHECK(p_conn_sec_config != NULL);
  351. ble_conn_state_user_flag_set(conn_handle,
  352. m_flag_allow_repairing,
  353. p_conn_sec_config->allow_repairing);
  354. }
  355. /**@brief Function for processing the @ref BLE_GAP_EVT_DISCONNECT event from the SoftDevice.
  356. *
  357. * @param[in] p_gap_evt The event from the SoftDevice.
  358. */
  359. static void disconnect_process(ble_gap_evt_t const * p_gap_evt)
  360. {
  361. pm_sec_error_code_t error = (p_gap_evt->params.disconnected.reason
  362. == BLE_HCI_CONN_TERMINATED_DUE_TO_MIC_FAILURE)
  363. ? PM_CONN_SEC_ERROR_MIC_FAILURE : PM_CONN_SEC_ERROR_DISCONNECT;
  364. link_secure_failure(p_gap_evt->conn_handle, error, BLE_GAP_SEC_STATUS_SOURCE_LOCAL);
  365. }
  366. /**@brief Function for sending a PARAMS_REQ event.
  367. *
  368. * @param[in] conn_handle The connection the security parameters are needed for.
  369. * @param[in] p_peer_params The security parameters from the peer. Can be NULL if the peer's parameters
  370. * are not yet available.
  371. */
  372. static void send_params_req(uint16_t conn_handle, ble_gap_sec_params_t const * p_peer_params)
  373. {
  374. pm_evt_t evt =
  375. {
  376. .evt_id = PM_EVT_CONN_SEC_PARAMS_REQ,
  377. .conn_handle = conn_handle,
  378. .params =
  379. {
  380. .conn_sec_params_req =
  381. {
  382. .p_peer_params = p_peer_params
  383. },
  384. },
  385. };
  386. evt_send(&evt);
  387. }
  388. /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST event from the SoftDevice.
  389. *
  390. * @param[in] p_gap_evt The event from the SoftDevice.
  391. */
  392. static void sec_params_request_process(ble_gap_evt_t const * p_gap_evt)
  393. {
  394. if (ble_conn_state_role(p_gap_evt->conn_handle) == BLE_GAP_ROLE_PERIPH)
  395. {
  396. sec_proc_start(p_gap_evt->conn_handle,
  397. true,
  398. p_gap_evt->params.sec_params_request.peer_params.bond
  399. ? PM_CONN_SEC_PROCEDURE_BONDING
  400. : PM_CONN_SEC_PROCEDURE_PAIRING);
  401. }
  402. send_params_req(p_gap_evt->conn_handle, &p_gap_evt->params.sec_params_request.peer_params);
  403. return;
  404. }
  405. /**@brief Function for sending a Peer Manager event indicating that pairing has succeeded.
  406. *
  407. * @param[in] p_gap_evt The AUTH_STATUS event from the SoftDevice that triggered this.
  408. * @param[in] data_stored Whether bonding data was stored.
  409. */
  410. static void pairing_success_evt_send(ble_gap_evt_t const * p_gap_evt, bool data_stored)
  411. {
  412. pm_evt_t pairing_success_evt;
  413. pairing_success_evt.evt_id = PM_EVT_CONN_SEC_SUCCEEDED;
  414. pairing_success_evt.conn_handle = p_gap_evt->conn_handle;
  415. pairing_success_evt.params.conn_sec_succeeded.procedure = p_gap_evt->params.auth_status.bonded
  416. ? PM_CONN_SEC_PROCEDURE_BONDING
  417. : PM_CONN_SEC_PROCEDURE_PAIRING;
  418. pairing_success_evt.params.conn_sec_succeeded.data_stored = data_stored;
  419. evt_send(&pairing_success_evt);
  420. }
  421. /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice, when
  422. * the auth_status is success.
  423. *
  424. * @param[in] p_gap_evt The event from the SoftDevice.
  425. */
  426. static void auth_status_success_process(ble_gap_evt_t const * p_gap_evt)
  427. {
  428. ret_code_t err_code;
  429. uint16_t conn_handle = p_gap_evt->conn_handle;
  430. pm_peer_id_t peer_id;
  431. pm_peer_data_t peer_data;
  432. bool new_peer_id = false;
  433. ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, false);
  434. if (!p_gap_evt->params.auth_status.bonded)
  435. {
  436. pairing_success_evt_send(p_gap_evt, false);
  437. return;
  438. }
  439. err_code = pdb_write_buf_get(PDB_TEMP_PEER_ID(conn_handle), PM_PEER_DATA_ID_BONDING, 1, &peer_data);
  440. if (err_code != NRF_SUCCESS)
  441. {
  442. NRF_LOG_ERROR("RAM buffer for new bond was unavailable. pdb_write_buf_get() returned %s. conn_handle: %d.",
  443. nrf_strerror_get(err_code),
  444. conn_handle);
  445. send_unexpected_error(conn_handle, err_code);
  446. pairing_success_evt_send(p_gap_evt, false);
  447. return;
  448. }
  449. peer_id = im_peer_id_get_by_conn_handle(conn_handle);
  450. if (peer_id == PM_PEER_ID_INVALID)
  451. {
  452. peer_id = im_find_duplicate_bonding_data(peer_data.p_bonding_data, PM_PEER_ID_INVALID);
  453. if (peer_id != PM_PEER_ID_INVALID)
  454. {
  455. // The peer has been identified as someone we have already bonded with.
  456. im_new_peer_id(conn_handle, peer_id);
  457. // If the flag is true, the configuration has been requested before.
  458. if (!allow_repairing(conn_handle))
  459. {
  460. send_config_req(conn_handle);
  461. if (!allow_repairing(conn_handle))
  462. {
  463. pairing_success_evt_send(p_gap_evt, false);
  464. return;
  465. }
  466. }
  467. }
  468. }
  469. if (peer_id == PM_PEER_ID_INVALID)
  470. {
  471. peer_id = pds_peer_id_allocate();
  472. if (peer_id == PM_PEER_ID_INVALID)
  473. {
  474. NRF_LOG_ERROR("Could not allocate new peer_id for incoming bond.");
  475. send_unexpected_error(conn_handle, NRF_ERROR_NO_MEM);
  476. pairing_success_evt_send(p_gap_evt, false);
  477. return;
  478. }
  479. im_new_peer_id(conn_handle, peer_id);
  480. new_peer_id = true;
  481. }
  482. err_code = pdb_write_buf_store(PDB_TEMP_PEER_ID(conn_handle), PM_PEER_DATA_ID_BONDING, peer_id);
  483. if (err_code == NRF_SUCCESS)
  484. {
  485. pairing_success_evt_send(p_gap_evt, true);
  486. }
  487. else if (err_code == NRF_ERROR_STORAGE_FULL)
  488. {
  489. send_storage_full_evt(conn_handle);
  490. pairing_success_evt_send(p_gap_evt, true);
  491. }
  492. else
  493. {
  494. /* Unexpected error */
  495. NRF_LOG_ERROR("Could not store bond. pdb_write_buf_store() returned %s. "\
  496. "conn_handle: %d, peer_id: %d",
  497. nrf_strerror_get(err_code),
  498. conn_handle,
  499. peer_id);
  500. send_unexpected_error(conn_handle, err_code);
  501. pairing_success_evt_send(p_gap_evt, false);
  502. if (new_peer_id)
  503. {
  504. UNUSED_RETURN_VALUE(im_peer_free(peer_id)); // We are already in a bad state.
  505. }
  506. }
  507. return;
  508. }
  509. /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice, when
  510. * the auth_status is failure.
  511. *
  512. * @param[in] p_gap_evt The event from the SoftDevice.
  513. */
  514. static void auth_status_failure_process(ble_gap_evt_t const * p_gap_evt)
  515. {
  516. link_secure_failure(p_gap_evt->conn_handle,
  517. p_gap_evt->params.auth_status.auth_status,
  518. p_gap_evt->params.auth_status.error_src);
  519. }
  520. /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice.
  521. *
  522. * @param[in] p_gap_evt The event from the SoftDevice.
  523. */
  524. static void auth_status_process(ble_gap_evt_t const * p_gap_evt)
  525. {
  526. switch (p_gap_evt->params.auth_status.auth_status)
  527. {
  528. case BLE_GAP_SEC_STATUS_SUCCESS:
  529. auth_status_success_process(p_gap_evt);
  530. break;
  531. default:
  532. auth_status_failure_process(p_gap_evt);
  533. #if PM_RA_PROTECTION_ENABLED
  534. ast_auth_error_notify(p_gap_evt->conn_handle);
  535. #endif // PM_RA_PROTECTION_ENABLED
  536. break;
  537. }
  538. }
  539. /**@brief Function for processing the @ref BLE_GAP_EVT_CONN_SEC_UPDATE event from the SoftDevice.
  540. *
  541. * @param[in] p_gap_evt The event from the SoftDevice.
  542. */
  543. static void conn_sec_update_process(ble_gap_evt_t const * p_gap_evt)
  544. {
  545. if (!pairing(p_gap_evt->conn_handle))
  546. {
  547. // This is an encryption procedure (not pairing), so this event marks the end of the procedure.
  548. if (!ble_conn_state_encrypted(p_gap_evt->conn_handle))
  549. {
  550. encryption_failure(p_gap_evt->conn_handle,
  551. PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING,
  552. BLE_GAP_SEC_STATUS_SOURCE_REMOTE);
  553. }
  554. else
  555. {
  556. ble_conn_state_user_flag_set(p_gap_evt->conn_handle, m_flag_sec_proc, false);
  557. pm_evt_t evt;
  558. evt.evt_id = PM_EVT_CONN_SEC_SUCCEEDED;
  559. evt.conn_handle = p_gap_evt->conn_handle;
  560. evt.params.conn_sec_succeeded.procedure = PM_CONN_SEC_PROCEDURE_ENCRYPTION;
  561. evt.params.conn_sec_succeeded.data_stored = false;
  562. evt_send(&evt);
  563. }
  564. }
  565. }
  566. /**@brief Funtion for initializing a BLE Connection State user flag.
  567. *
  568. * @param[out] flag_id The flag to initialize.
  569. */
  570. static void flag_id_init(ble_conn_state_user_flag_id_t * p_flag_id)
  571. {
  572. if (*p_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
  573. {
  574. *p_flag_id = ble_conn_state_user_flag_acquire();
  575. }
  576. }
  577. ret_code_t smd_init(void)
  578. {
  579. NRF_PM_DEBUG_CHECK(!m_module_initialized);
  580. flag_id_init(&m_flag_sec_proc);
  581. flag_id_init(&m_flag_sec_proc_pairing);
  582. flag_id_init(&m_flag_sec_proc_bonding);
  583. flag_id_init(&m_flag_allow_repairing);
  584. if ((m_flag_sec_proc == BLE_CONN_STATE_USER_FLAG_INVALID) ||
  585. (m_flag_sec_proc_pairing == BLE_CONN_STATE_USER_FLAG_INVALID) ||
  586. (m_flag_sec_proc_bonding == BLE_CONN_STATE_USER_FLAG_INVALID) ||
  587. (m_flag_allow_repairing == BLE_CONN_STATE_USER_FLAG_INVALID))
  588. {
  589. NRF_LOG_ERROR("Could not acquire conn_state user flags. Increase "\
  590. "BLE_CONN_STATE_USER_FLAG_COUNT in the ble_conn_state module.");
  591. return NRF_ERROR_INTERNAL;
  592. }
  593. #if PM_RA_PROTECTION_ENABLED
  594. ret_code_t err_code = ast_init();
  595. if (err_code != NRF_SUCCESS)
  596. {
  597. return err_code;
  598. }
  599. #endif // PM_RA_PROTECTION_ENABLED
  600. m_module_initialized = true;
  601. return NRF_SUCCESS;
  602. }
  603. /**@brief Function for putting retrieving a buffer and putting pointers into a @ref ble_gap_sec_keyset_t.
  604. *
  605. * @param[in] conn_handle The connection the security procedure is happening on.
  606. * @param[in] role Our role in the connection.
  607. * @param[in] p_public_key Pointer to a buffer holding the public key, or NULL.
  608. * @param[out] p_sec_keyset Pointer to the keyset to be filled.
  609. *
  610. * @retval NRF_SUCCESS Success.
  611. * @retval NRF_ERROR_BUSY Could not process request at this time. Reattempt later.
  612. * @retval NRF_ERROR_INVALID_PARAM Data ID or Peer ID was invalid or unallocated.
  613. * @retval NRF_ERROR_INVALID_STATE The link is disconnected.
  614. * @retval NRF_ERROR_INTERNAL Fatal error.
  615. */
  616. static ret_code_t sec_keyset_fill(uint16_t conn_handle,
  617. uint8_t role,
  618. ble_gap_lesc_p256_pk_t * p_public_key,
  619. ble_gap_sec_keyset_t * p_sec_keyset)
  620. {
  621. ret_code_t err_code;
  622. pm_peer_data_t peer_data;
  623. if (p_sec_keyset == NULL)
  624. {
  625. NRF_LOG_ERROR("Internal error: %s received NULL for p_sec_keyset.", __func__);
  626. return NRF_ERROR_INTERNAL;
  627. }
  628. // Acquire a memory buffer to receive bonding data into.
  629. err_code = pdb_write_buf_get(PDB_TEMP_PEER_ID(conn_handle), PM_PEER_DATA_ID_BONDING, 1, &peer_data);
  630. if (err_code == NRF_ERROR_BUSY)
  631. {
  632. // No action.
  633. }
  634. else if (err_code != NRF_SUCCESS)
  635. {
  636. NRF_LOG_ERROR("Could not retrieve RAM buffer for incoming bond. pdb_write_buf_get() "\
  637. "returned %s. conn_handle: %d",
  638. nrf_strerror_get(err_code),
  639. conn_handle);
  640. err_code = NRF_ERROR_INTERNAL;
  641. }
  642. else /* if (err_code == NRF_SUCCESS) */
  643. {
  644. memset(peer_data.p_bonding_data, 0, sizeof(pm_peer_data_bonding_t));
  645. peer_data.p_bonding_data->own_role = role;
  646. p_sec_keyset->keys_own.p_enc_key = &peer_data.p_bonding_data->own_ltk;
  647. p_sec_keyset->keys_own.p_pk = p_public_key;
  648. p_sec_keyset->keys_peer.p_enc_key = &peer_data.p_bonding_data->peer_ltk;
  649. p_sec_keyset->keys_peer.p_id_key = &peer_data.p_bonding_data->peer_ble_id;
  650. p_sec_keyset->keys_peer.p_pk = &m_peer_pk;
  651. // Retrieve the address the peer used during connection establishment.
  652. // This address will be overwritten if ID is shared. Should not fail.
  653. err_code = im_ble_addr_get(conn_handle, &peer_data.p_bonding_data->peer_ble_id.id_addr_info);
  654. if (err_code != NRF_SUCCESS)
  655. {
  656. NRF_LOG_WARNING("im_ble_addr_get() returned %s. conn_handle: %d. Link was likely disconnected.",
  657. nrf_strerror_get(err_code),
  658. conn_handle);
  659. return NRF_ERROR_INVALID_STATE;
  660. }
  661. }
  662. return err_code;
  663. }
  664. ret_code_t smd_params_reply(uint16_t conn_handle,
  665. ble_gap_sec_params_t * p_sec_params,
  666. ble_gap_lesc_p256_pk_t * p_public_key)
  667. {
  668. NRF_PM_DEBUG_CHECK(m_module_initialized);
  669. uint8_t role = ble_conn_state_role(conn_handle);
  670. ret_code_t err_code = NRF_SUCCESS;
  671. uint8_t sec_status = BLE_GAP_SEC_STATUS_SUCCESS;
  672. ble_gap_sec_keyset_t sec_keyset;
  673. memset(&sec_keyset, 0, sizeof(ble_gap_sec_keyset_t));
  674. if (role == BLE_GAP_ROLE_PERIPH)
  675. {
  676. // Set the default value for allowing repairing at the start of the sec proc. (for peripheral)
  677. ble_conn_state_user_flag_set(conn_handle, m_flag_allow_repairing, false);
  678. }
  679. if (role == BLE_GAP_ROLE_INVALID)
  680. {
  681. return BLE_ERROR_INVALID_CONN_HANDLE;
  682. }
  683. #if PM_RA_PROTECTION_ENABLED
  684. if (ast_peer_blacklisted(conn_handle)) //Check for repeated attempts here.
  685. {
  686. sec_status = BLE_GAP_SEC_STATUS_REPEATED_ATTEMPTS;
  687. }
  688. else
  689. #endif // PM_RA_PROTECTION_ENABLED
  690. if (p_sec_params == NULL)
  691. {
  692. // NULL params means reject pairing.
  693. sec_status = BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP;
  694. }
  695. else
  696. {
  697. if ((im_peer_id_get_by_conn_handle(conn_handle) != PM_PEER_ID_INVALID) &&
  698. (role == BLE_GAP_ROLE_PERIPH) &&
  699. !allow_repairing(conn_handle))
  700. {
  701. // Bond already exists. Reject the pairing request if the user doesn't intervene.
  702. send_config_req(conn_handle);
  703. if (!allow_repairing(conn_handle))
  704. {
  705. // Reject pairing.
  706. sec_status = BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP;
  707. }
  708. }
  709. if (!p_sec_params->bond)
  710. {
  711. // Pairing, no bonding.
  712. sec_keyset.keys_own.p_pk = p_public_key;
  713. sec_keyset.keys_peer.p_pk = &m_peer_pk;
  714. }
  715. else if (sec_status != BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP)
  716. {
  717. // Bonding is to be performed, prepare to receive bonding data.
  718. err_code = sec_keyset_fill(conn_handle, role, p_public_key, &sec_keyset);
  719. }
  720. }
  721. if (err_code == NRF_SUCCESS)
  722. {
  723. // Everything OK, reply to SoftDevice. If an error happened, the user is given an
  724. // opportunity to change the parameters and retry the call.
  725. if (role == BLE_GAP_ROLE_PERIPH)
  726. {
  727. err_code = sd_ble_gap_sec_params_reply(conn_handle, sec_status, p_sec_params, &sec_keyset);
  728. }
  729. else
  730. {
  731. err_code = sd_ble_gap_sec_params_reply(conn_handle, sec_status, NULL, &sec_keyset);
  732. }
  733. }
  734. return err_code;
  735. }
  736. /**@brief Function for initiating pairing as a central, or all security as a periheral.
  737. *
  738. * See @ref smd_link_secure and @ref sd_ble_gap_authenticate for more information.
  739. */
  740. static ret_code_t link_secure_authenticate(uint16_t conn_handle,
  741. ble_gap_sec_params_t * p_sec_params)
  742. {
  743. ret_code_t err_code = sd_ble_gap_authenticate(conn_handle, p_sec_params);
  744. if (err_code == NRF_ERROR_NO_MEM)
  745. {
  746. // sd_ble_gap_authenticate() returned NRF_ERROR_NO_MEM. Too many other sec procedures running.
  747. err_code = NRF_ERROR_BUSY;
  748. }
  749. return err_code;
  750. }
  751. #if PM_CENTRAL_ENABLED
  752. /**@brief Function for initiating encryption as a central. See @ref smd_link_secure for more info.
  753. */
  754. static ret_code_t link_secure_central_encryption(uint16_t conn_handle,
  755. pm_peer_id_t peer_id)
  756. {
  757. pm_peer_data_flash_t peer_data;
  758. ret_code_t err_code;
  759. ble_gap_enc_key_t const * p_existing_key = NULL;
  760. bool lesc = false;
  761. err_code = pdb_peer_data_ptr_get(peer_id, PM_PEER_DATA_ID_BONDING, &peer_data);
  762. if (err_code == NRF_SUCCESS)
  763. {
  764. // Use peer's key since they are peripheral.
  765. p_existing_key = &(peer_data.p_bonding_data->peer_ltk);
  766. lesc = peer_data.p_bonding_data->own_ltk.enc_info.lesc;
  767. if (lesc) // LESC was used during bonding.
  768. {
  769. // For LESC, always use own key.
  770. p_existing_key = &(peer_data.p_bonding_data->own_ltk);
  771. }
  772. }
  773. if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_NOT_FOUND))
  774. {
  775. if (err_code != NRF_ERROR_BUSY)
  776. {
  777. NRF_LOG_ERROR("Could not retrieve stored bond. pdb_peer_data_ptr_get() returned %s. "\
  778. "peer_id: %d",
  779. nrf_strerror_get(err_code),
  780. peer_id);
  781. err_code = NRF_ERROR_INTERNAL;
  782. }
  783. }
  784. else if (p_existing_key == NULL) /* There is no bonding data stored. This means that a bonding
  785. procedure is in ongoing, or that the records in flash are
  786. in a bad state. */
  787. {
  788. err_code = NRF_ERROR_BUSY;
  789. }
  790. else if (!lesc && !im_master_id_is_valid(&(p_existing_key->master_id))) /* There is no valid LTK stored. */
  791. {
  792. // No LTK to encrypt with.
  793. err_code = NRF_ERROR_INVALID_DATA;
  794. }
  795. else
  796. {
  797. // Encrypt with existing LTK.
  798. err_code = sd_ble_gap_encrypt(conn_handle,
  799. &(p_existing_key->master_id),
  800. &(p_existing_key->enc_info));
  801. }
  802. sec_proc_start(conn_handle, err_code == NRF_SUCCESS, PM_CONN_SEC_PROCEDURE_ENCRYPTION);
  803. return err_code;
  804. }
  805. /**@brief Function for intiating security as a central. See @ref smd_link_secure for more info.
  806. */
  807. static ret_code_t link_secure_central(uint16_t conn_handle,
  808. ble_gap_sec_params_t * p_sec_params,
  809. bool force_repairing)
  810. {
  811. ret_code_t err_code;
  812. pm_peer_id_t peer_id;
  813. if (p_sec_params == NULL)
  814. {
  815. return link_secure_authenticate(conn_handle, NULL);
  816. }
  817. // Set the default value for allowing repairing at the start of the sec proc. (for central)
  818. ble_conn_state_user_flag_set(conn_handle, m_flag_allow_repairing, force_repairing);
  819. peer_id = im_peer_id_get_by_conn_handle(conn_handle);
  820. if ((peer_id != PM_PEER_ID_INVALID) && !force_repairing)
  821. {
  822. // There is already data in flash for this peer, and repairing has not been requested, so
  823. // the link will be encrypted with the existing keys.
  824. err_code = link_secure_central_encryption(conn_handle, peer_id);
  825. }
  826. else
  827. {
  828. // There are no existing keys, or repairing has been explicitly requested, so pairing
  829. // (possibly including bonding) will be performed to encrypt the link.
  830. err_code = link_secure_authenticate(conn_handle, p_sec_params);
  831. pm_conn_sec_procedure_t procedure = (p_sec_params && p_sec_params->bond) ?
  832. PM_CONN_SEC_PROCEDURE_BONDING :
  833. PM_CONN_SEC_PROCEDURE_PAIRING;
  834. sec_proc_start(conn_handle, err_code == NRF_SUCCESS, procedure);
  835. }
  836. return err_code;
  837. }
  838. /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_REQUEST event from the SoftDevice.
  839. *
  840. * @param[in] p_gap_evt The event from the SoftDevice.
  841. */
  842. static void sec_request_process(ble_gap_evt_t const * p_gap_evt)
  843. {
  844. pm_evt_t evt =
  845. {
  846. .evt_id = PM_EVT_SLAVE_SECURITY_REQ,
  847. .conn_handle = p_gap_evt->conn_handle,
  848. .params =
  849. {
  850. .slave_security_req =
  851. {
  852. .bond = p_gap_evt->params.sec_request.bond,
  853. .mitm = p_gap_evt->params.sec_request.mitm,
  854. }
  855. }
  856. };
  857. evt_send(&evt);
  858. return;
  859. }
  860. #endif // PM_CENTRAL_ENABLED
  861. /**@brief Function for asking the central to secure the link. See @ref smd_link_secure for more info.
  862. */
  863. static ret_code_t link_secure_peripheral(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params)
  864. {
  865. ret_code_t err_code = NRF_SUCCESS;
  866. if (p_sec_params != NULL)
  867. {
  868. err_code = link_secure_authenticate(conn_handle, p_sec_params);
  869. }
  870. return err_code;
  871. }
  872. ret_code_t smd_link_secure(uint16_t conn_handle,
  873. ble_gap_sec_params_t * p_sec_params,
  874. bool force_repairing)
  875. {
  876. NRF_PM_DEBUG_CHECK(m_module_initialized);
  877. uint8_t role = ble_conn_state_role(conn_handle);
  878. switch (role)
  879. {
  880. #if PM_CENTRAL_ENABLED
  881. case BLE_GAP_ROLE_CENTRAL:
  882. return link_secure_central(conn_handle, p_sec_params, force_repairing);
  883. #endif
  884. case BLE_GAP_ROLE_PERIPH:
  885. return link_secure_peripheral(conn_handle, p_sec_params);
  886. default:
  887. return BLE_ERROR_INVALID_CONN_HANDLE;
  888. }
  889. }
  890. void smd_ble_evt_handler(ble_evt_t const * p_ble_evt)
  891. {
  892. switch (p_ble_evt->header.evt_id)
  893. {
  894. case BLE_GAP_EVT_DISCONNECTED:
  895. disconnect_process(&(p_ble_evt->evt.gap_evt));
  896. break;
  897. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  898. sec_params_request_process(&(p_ble_evt->evt.gap_evt));
  899. break;
  900. case BLE_GAP_EVT_SEC_INFO_REQUEST:
  901. sec_info_request_process(&(p_ble_evt->evt.gap_evt));
  902. break;
  903. #if PM_CENTRAL_ENABLED
  904. case BLE_GAP_EVT_SEC_REQUEST:
  905. sec_request_process(&(p_ble_evt->evt.gap_evt));
  906. break;
  907. #endif
  908. case BLE_GAP_EVT_AUTH_STATUS:
  909. auth_status_process(&(p_ble_evt->evt.gap_evt));
  910. break;
  911. case BLE_GAP_EVT_CONN_SEC_UPDATE:
  912. conn_sec_update_process(&(p_ble_evt->evt.gap_evt));
  913. break;
  914. };
  915. }
  916. #endif //NRF_MODULE_ENABLED(PEER_MANAGER)