1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN 24 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "sm.c" 39 40 #include <string.h> 41 #include <inttypes.h> 42 43 #include "ble/le_device_db.h" 44 #include "ble/core.h" 45 #include "ble/sm.h" 46 #include "bluetooth_company_id.h" 47 #include "btstack_bool.h" 48 #include "btstack_crypto.h" 49 #include "btstack_debug.h" 50 #include "btstack_event.h" 51 #include "btstack_linked_list.h" 52 #include "btstack_memory.h" 53 #include "btstack_tlv.h" 54 #include "gap.h" 55 #include "hci.h" 56 #include "hci_dump.h" 57 #include "l2cap.h" 58 59 #if !defined(ENABLE_LE_PERIPHERAL) && !defined(ENABLE_LE_CENTRAL) 60 #error "LE Security Manager used, but neither ENABLE_LE_PERIPHERAL nor ENABLE_LE_CENTRAL defined. Please add at least one to btstack_config.h." 61 #endif 62 63 #if defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION) && (!defined(ENABLE_CLASSIC) || !defined(ENABLE_LE_SECURE_CONNECTIONS)) 64 #error "Cross Transport Key Derivation requires support for LE Secure Connections and BR/EDR (Classic)" 65 #endif 66 67 // assert SM Public Key can be sent/received 68 #ifdef ENABLE_LE_SECURE_CONNECTIONS 69 #if HCI_ACL_PAYLOAD_SIZE < 69 70 #error "HCI_ACL_PAYLOAD_SIZE must be at least 69 bytes when using LE Secure Conection. Please increase HCI_ACL_PAYLOAD_SIZE or disable ENABLE_LE_SECURE_CONNECTIONS" 71 #endif 72 #endif 73 74 #if defined(ENABLE_LE_PERIPHERAL) && defined(ENABLE_LE_CENTRAL) 75 #define IS_RESPONDER(role) (role) 76 #else 77 #ifdef ENABLE_LE_CENTRAL 78 // only central - never responder (avoid 'unused variable' warnings) 79 #define IS_RESPONDER(role) (0 && role) 80 #else 81 // only peripheral - always responder (avoid 'unused variable' warnings) 82 #define IS_RESPONDER(role) (1 || role) 83 #endif 84 #endif 85 86 #if defined(ENABLE_LE_SIGNED_WRITE) || defined(ENABLE_LE_SECURE_CONNECTIONS) 87 #define USE_CMAC_ENGINE 88 #endif 89 90 91 #define BTSTACK_TAG32(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D)) 92 93 // 94 // SM internal types and globals 95 // 96 97 typedef enum { 98 DKG_W4_WORKING, 99 DKG_CALC_IRK, 100 DKG_CALC_DHK, 101 DKG_READY 102 } derived_key_generation_t; 103 104 typedef enum { 105 RAU_IDLE, 106 RAU_GET_RANDOM, 107 RAU_W4_RANDOM, 108 RAU_GET_ENC, 109 RAU_W4_ENC, 110 } random_address_update_t; 111 112 typedef enum { 113 CMAC_IDLE, 114 CMAC_CALC_SUBKEYS, 115 CMAC_W4_SUBKEYS, 116 CMAC_CALC_MI, 117 CMAC_W4_MI, 118 CMAC_CALC_MLAST, 119 CMAC_W4_MLAST 120 } cmac_state_t; 121 122 typedef enum { 123 JUST_WORKS, 124 PK_RESP_INPUT, // Initiator displays PK, responder inputs PK 125 PK_INIT_INPUT, // Responder displays PK, initiator inputs PK 126 PK_BOTH_INPUT, // Only input on both, both input PK 127 NUMERIC_COMPARISON, // Only numerical compparison (yes/no) on on both sides 128 OOB // OOB available on one (SC) or both sides (legacy) 129 } stk_generation_method_t; 130 131 typedef enum { 132 SM_USER_RESPONSE_IDLE, 133 SM_USER_RESPONSE_PENDING, 134 SM_USER_RESPONSE_CONFIRM, 135 SM_USER_RESPONSE_PASSKEY, 136 SM_USER_RESPONSE_DECLINE 137 } sm_user_response_t; 138 139 typedef enum { 140 SM_AES128_IDLE, 141 SM_AES128_ACTIVE 142 } sm_aes128_state_t; 143 144 typedef enum { 145 ADDRESS_RESOLUTION_IDLE, 146 ADDRESS_RESOLUTION_GENERAL, 147 ADDRESS_RESOLUTION_FOR_CONNECTION, 148 } address_resolution_mode_t; 149 150 typedef enum { 151 ADDRESS_RESOLUTION_SUCCEEDED, 152 ADDRESS_RESOLUTION_FAILED, 153 } address_resolution_event_t; 154 155 typedef enum { 156 EC_KEY_GENERATION_IDLE, 157 EC_KEY_GENERATION_ACTIVE, 158 EC_KEY_GENERATION_DONE, 159 } ec_key_generation_state_t; 160 161 typedef enum { 162 SM_STATE_VAR_DHKEY_NEEDED = 1 << 0, 163 SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1, 164 SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2, 165 } sm_state_var_t; 166 167 typedef enum { 168 SM_SC_OOB_IDLE, 169 SM_SC_OOB_W4_RANDOM, 170 SM_SC_OOB_W2_CALC_CONFIRM, 171 SM_SC_OOB_W4_CONFIRM, 172 } sm_sc_oob_state_t; 173 174 typedef uint8_t sm_key24_t[3]; 175 typedef uint8_t sm_key56_t[7]; 176 typedef uint8_t sm_key256_t[32]; 177 178 // 179 // GLOBAL DATA 180 // 181 182 static bool sm_initialized; 183 184 static bool test_use_fixed_local_csrk; 185 static bool test_use_fixed_local_irk; 186 187 #ifdef ENABLE_TESTING_SUPPORT 188 static uint8_t test_pairing_failure; 189 #endif 190 191 // configuration 192 static uint8_t sm_accepted_stk_generation_methods; 193 static uint8_t sm_max_encryption_key_size; 194 static uint8_t sm_min_encryption_key_size; 195 static uint8_t sm_auth_req = 0; 196 static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 197 static uint32_t sm_fixed_passkey_in_display_role; 198 static bool sm_reconstruct_ltk_without_le_device_db_entry; 199 200 #ifdef ENABLE_LE_PERIPHERAL 201 static uint8_t sm_slave_request_security; 202 #endif 203 204 #ifdef ENABLE_LE_SECURE_CONNECTIONS 205 static bool sm_sc_only_mode; 206 static uint8_t sm_sc_oob_random[16]; 207 static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value); 208 static sm_sc_oob_state_t sm_sc_oob_state; 209 #endif 210 211 212 static bool sm_persistent_keys_random_active; 213 static const btstack_tlv_t * sm_tlv_impl; 214 static void * sm_tlv_context; 215 216 // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values 217 static sm_key_t sm_persistent_er; 218 static sm_key_t sm_persistent_ir; 219 220 // derived from sm_persistent_ir 221 static sm_key_t sm_persistent_dhk; 222 static sm_key_t sm_persistent_irk; 223 static derived_key_generation_t dkg_state; 224 225 // derived from sm_persistent_er 226 // .. 227 228 // random address update 229 static random_address_update_t rau_state; 230 static bd_addr_t sm_random_address; 231 232 #ifdef USE_CMAC_ENGINE 233 // CMAC Calculation: General 234 static btstack_crypto_aes128_cmac_t sm_cmac_request; 235 static void (*sm_cmac_done_callback)(uint8_t hash[8]); 236 static uint8_t sm_cmac_active; 237 static uint8_t sm_cmac_hash[16]; 238 #endif 239 240 // CMAC for ATT Signed Writes 241 #ifdef ENABLE_LE_SIGNED_WRITE 242 static uint16_t sm_cmac_signed_write_message_len; 243 static uint8_t sm_cmac_signed_write_header[3]; 244 static const uint8_t * sm_cmac_signed_write_message; 245 static uint8_t sm_cmac_signed_write_sign_counter[4]; 246 #endif 247 248 // CMAC for Secure Connection functions 249 #ifdef ENABLE_LE_SECURE_CONNECTIONS 250 static sm_connection_t * sm_cmac_connection; 251 static uint8_t sm_cmac_sc_buffer[80]; 252 #endif 253 254 // resolvable private address lookup / CSRK calculation 255 static int sm_address_resolution_test; 256 static uint8_t sm_address_resolution_addr_type; 257 static bd_addr_t sm_address_resolution_address; 258 static void * sm_address_resolution_context; 259 static address_resolution_mode_t sm_address_resolution_mode; 260 static btstack_linked_list_t sm_address_resolution_general_queue; 261 262 // aes128 crypto engine. 263 static sm_aes128_state_t sm_aes128_state; 264 265 // crypto 266 static btstack_crypto_random_t sm_crypto_random_request; 267 static btstack_crypto_aes128_t sm_crypto_aes128_request; 268 #ifdef ENABLE_LE_SECURE_CONNECTIONS 269 static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request; 270 #endif 271 272 // temp storage for random data 273 static uint8_t sm_random_data[8]; 274 static uint8_t sm_aes128_key[16]; 275 static uint8_t sm_aes128_plaintext[16]; 276 static uint8_t sm_aes128_ciphertext[16]; 277 278 // to receive events 279 static btstack_packet_callback_registration_t hci_event_callback_registration; 280 static btstack_packet_callback_registration_t l2cap_event_callback_registration; 281 282 /* to dispatch sm event */ 283 static btstack_linked_list_t sm_event_handlers; 284 285 /* to schedule calls to sm_run */ 286 static btstack_timer_source_t sm_run_timer; 287 288 // LE Secure Connections 289 #ifdef ENABLE_LE_SECURE_CONNECTIONS 290 static ec_key_generation_state_t ec_key_generation_state; 291 static uint8_t ec_q[64]; 292 #endif 293 294 // 295 // Volume 3, Part H, Chapter 24 296 // "Security shall be initiated by the Security Manager in the device in the master role. 297 // The device in the slave role shall be the responding device." 298 // -> master := initiator, slave := responder 299 // 300 301 // data needed for security setup 302 typedef struct sm_setup_context { 303 304 btstack_timer_source_t sm_timeout; 305 306 // user response, (Phase 1 and/or 2) 307 uint8_t sm_user_response; 308 uint8_t sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count 309 310 // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3 311 uint8_t sm_key_distribution_send_set; 312 uint8_t sm_key_distribution_sent_set; 313 uint8_t sm_key_distribution_expected_set; 314 uint8_t sm_key_distribution_received_set; 315 316 // Phase 2 (Pairing over SMP) 317 stk_generation_method_t sm_stk_generation_method; 318 sm_key_t sm_tk; 319 uint8_t sm_have_oob_data; 320 uint8_t sm_use_secure_connections; 321 322 sm_key_t sm_c1_t3_value; // c1 calculation 323 sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1 324 sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1 325 sm_key_t sm_local_random; 326 sm_key_t sm_local_confirm; 327 sm_key_t sm_peer_random; 328 sm_key_t sm_peer_confirm; 329 uint8_t sm_m_addr_type; // address and type can be removed 330 uint8_t sm_s_addr_type; // '' 331 bd_addr_t sm_m_address; // '' 332 bd_addr_t sm_s_address; // '' 333 sm_key_t sm_ltk; 334 335 uint8_t sm_state_vars; 336 #ifdef ENABLE_LE_SECURE_CONNECTIONS 337 uint8_t sm_peer_q[64]; // also stores random for EC key generation during init 338 sm_key_t sm_peer_nonce; // might be combined with sm_peer_random 339 sm_key_t sm_local_nonce; // might be combined with sm_local_random 340 uint8_t sm_dhkey[32]; 341 sm_key_t sm_peer_dhkey_check; 342 sm_key_t sm_local_dhkey_check; 343 sm_key_t sm_ra; 344 sm_key_t sm_rb; 345 sm_key_t sm_t; // used for f5 and h6 346 sm_key_t sm_mackey; 347 uint8_t sm_passkey_bit; // also stores number of generated random bytes for EC key generation 348 #endif 349 350 // Phase 3 351 352 // key distribution, we generate 353 uint16_t sm_local_y; 354 uint16_t sm_local_div; 355 uint16_t sm_local_ediv; 356 uint8_t sm_local_rand[8]; 357 sm_key_t sm_local_ltk; 358 sm_key_t sm_local_csrk; 359 sm_key_t sm_local_irk; 360 // sm_local_address/addr_type not needed 361 362 // key distribution, received from peer 363 uint16_t sm_peer_y; 364 uint16_t sm_peer_div; 365 uint16_t sm_peer_ediv; 366 uint8_t sm_peer_rand[8]; 367 sm_key_t sm_peer_ltk; 368 sm_key_t sm_peer_irk; 369 sm_key_t sm_peer_csrk; 370 uint8_t sm_peer_addr_type; 371 bd_addr_t sm_peer_address; 372 #ifdef ENABLE_LE_SIGNED_WRITE 373 int sm_le_device_index; 374 #endif 375 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 376 link_key_t sm_link_key; 377 link_key_type_t sm_link_key_type; 378 #endif 379 } sm_setup_context_t; 380 381 // 382 static sm_setup_context_t the_setup; 383 static sm_setup_context_t * setup = &the_setup; 384 385 // active connection - the one for which the_setup is used for 386 static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID; 387 388 // @return 1 if oob data is available 389 // stores oob data in provided 16 byte buffer if not null 390 static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL; 391 static int (*sm_get_sc_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_sc_peer_confirm, uint8_t * oob_sc_peer_random); 392 static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk); 393 394 static void sm_run(void); 395 static void sm_state_reset(void); 396 static void sm_done_for_handle(hci_con_handle_t con_handle); 397 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle); 398 static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk); 399 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 400 static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type); 401 #endif 402 static inline int sm_calc_actual_encryption_key_size(int other); 403 static int sm_validate_stk_generation_method(void); 404 static void sm_handle_encryption_result_address_resolution(void *arg); 405 static void sm_handle_encryption_result_dkg_dhk(void *arg); 406 static void sm_handle_encryption_result_dkg_irk(void *arg); 407 static void sm_handle_encryption_result_enc_a(void *arg); 408 static void sm_handle_encryption_result_enc_b(void *arg); 409 static void sm_handle_encryption_result_enc_c(void *arg); 410 static void sm_handle_encryption_result_enc_csrk(void *arg); 411 static void sm_handle_encryption_result_enc_d(void * arg); 412 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg); 413 static void sm_handle_encryption_result_enc_ph3_y(void *arg); 414 #ifdef ENABLE_LE_PERIPHERAL 415 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg); 416 static void sm_handle_encryption_result_enc_ph4_y(void *arg); 417 #endif 418 static void sm_handle_encryption_result_enc_stk(void *arg); 419 static void sm_handle_encryption_result_rau(void *arg); 420 static void sm_handle_random_result_ph2_tk(void * arg); 421 static void sm_handle_random_result_rau(void * arg); 422 #ifdef ENABLE_LE_SECURE_CONNECTIONS 423 static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash)); 424 static void sm_ec_generate_new_key(void); 425 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg); 426 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg); 427 static int sm_passkey_entry(stk_generation_method_t method); 428 #endif 429 static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason); 430 431 static void log_info_hex16(const char * name, uint16_t value){ 432 log_info("%-6s 0x%04x", name, value); 433 } 434 435 // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){ 436 // return packet[0]; 437 // } 438 static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){ 439 return packet[1]; 440 } 441 static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){ 442 return packet[2]; 443 } 444 static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){ 445 return packet[3]; 446 } 447 static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){ 448 return packet[4]; 449 } 450 static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){ 451 return packet[5]; 452 } 453 static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){ 454 return packet[6]; 455 } 456 457 static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){ 458 packet[0] = code; 459 } 460 static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){ 461 packet[1] = io_capability; 462 } 463 static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){ 464 packet[2] = oob_data_flag; 465 } 466 static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){ 467 packet[3] = auth_req; 468 } 469 static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){ 470 packet[4] = max_encryption_key_size; 471 } 472 static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){ 473 packet[5] = initiator_key_distribution; 474 } 475 static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){ 476 packet[6] = responder_key_distribution; 477 } 478 479 static bool sm_is_null_random(uint8_t random[8]){ 480 return btstack_is_null(random, 8); 481 } 482 483 static bool sm_is_null_key(uint8_t * key){ 484 return btstack_is_null(key, 16); 485 } 486 487 // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth 488 static void sm_run_timer_handler(btstack_timer_source_t * ts){ 489 UNUSED(ts); 490 sm_run(); 491 } 492 static void sm_trigger_run(void){ 493 if (!sm_initialized) return; 494 (void)btstack_run_loop_remove_timer(&sm_run_timer); 495 btstack_run_loop_set_timer(&sm_run_timer, 0); 496 btstack_run_loop_add_timer(&sm_run_timer); 497 } 498 499 // Key utils 500 static void sm_reset_tk(void){ 501 int i; 502 for (i=0;i<16;i++){ 503 setup->sm_tk[i] = 0; 504 } 505 } 506 507 // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0 508 // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0."" 509 static void sm_truncate_key(sm_key_t key, int max_encryption_size){ 510 int i; 511 for (i = max_encryption_size ; i < 16 ; i++){ 512 key[15-i] = 0; 513 } 514 } 515 516 // ER / IR checks 517 static void sm_er_ir_set_default(void){ 518 int i; 519 for (i=0;i<16;i++){ 520 sm_persistent_er[i] = 0x30 + i; 521 sm_persistent_ir[i] = 0x90 + i; 522 } 523 } 524 525 static int sm_er_is_default(void){ 526 int i; 527 for (i=0;i<16;i++){ 528 if (sm_persistent_er[i] != (0x30+i)) return 0; 529 } 530 return 1; 531 } 532 533 static int sm_ir_is_default(void){ 534 int i; 535 for (i=0;i<16;i++){ 536 if (sm_persistent_ir[i] != (0x90+i)) return 0; 537 } 538 return 1; 539 } 540 541 static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){ 542 UNUSED(channel); 543 544 // log event 545 hci_dump_packet(packet_type, 1, packet, size); 546 // dispatch to all event handlers 547 btstack_linked_list_iterator_t it; 548 btstack_linked_list_iterator_init(&it, &sm_event_handlers); 549 while (btstack_linked_list_iterator_has_next(&it)){ 550 btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it); 551 entry->callback(packet_type, 0, packet, size); 552 } 553 } 554 555 static void sm_setup_event_base(uint8_t * event, int event_size, uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){ 556 event[0] = type; 557 event[1] = event_size - 2; 558 little_endian_store_16(event, 2, con_handle); 559 event[4] = addr_type; 560 reverse_bd_addr(address, &event[5]); 561 } 562 563 static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){ 564 uint8_t event[11]; 565 sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address); 566 sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event)); 567 } 568 569 static void sm_notify_client_index(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint16_t index){ 570 // fetch addr and addr type from db, only called for valid entries 571 bd_addr_t identity_address; 572 int identity_address_type; 573 le_device_db_info(index, &identity_address_type, identity_address, NULL); 574 575 uint8_t event[20]; 576 sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address); 577 event[11] = identity_address_type; 578 reverse_bd_addr(identity_address, &event[12]); 579 little_endian_store_16(event, 18, index); 580 sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event)); 581 } 582 583 static void sm_notify_client_status(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint8_t status){ 584 uint8_t event[12]; 585 sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address); 586 event[11] = status; 587 sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event)); 588 } 589 590 591 static void sm_reencryption_started(sm_connection_t * sm_conn){ 592 593 if (sm_conn->sm_reencryption_active) return; 594 595 sm_conn->sm_reencryption_active = true; 596 597 int identity_addr_type; 598 bd_addr_t identity_addr; 599 if (sm_conn->sm_le_db_index >= 0){ 600 // fetch addr and addr type from db, only called for valid entries 601 le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL); 602 } else { 603 // for legacy pairing with LTK re-construction, use current peer addr 604 identity_addr_type = sm_conn->sm_peer_addr_type; 605 memcpy(identity_addr, sm_conn->sm_peer_address, 6); 606 } 607 608 sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr); 609 } 610 611 static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){ 612 613 if (!sm_conn->sm_reencryption_active) return; 614 615 sm_conn->sm_reencryption_active = false; 616 617 int identity_addr_type; 618 bd_addr_t identity_addr; 619 if (sm_conn->sm_le_db_index >= 0){ 620 // fetch addr and addr type from db, only called for valid entries 621 le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL); 622 } else { 623 // for legacy pairing with LTK re-construction, use current peer addr 624 identity_addr_type = sm_conn->sm_peer_addr_type; 625 memcpy(identity_addr, sm_conn->sm_peer_address, 6); 626 } 627 628 sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status); 629 } 630 631 static void sm_pairing_started(sm_connection_t * sm_conn){ 632 633 if (sm_conn->sm_pairing_active) return; 634 635 sm_conn->sm_pairing_active = true; 636 637 uint8_t event[11]; 638 sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_STARTED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address); 639 sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event)); 640 } 641 642 static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){ 643 644 if (!sm_conn->sm_pairing_active) return; 645 646 sm_conn->sm_pairing_active = false; 647 648 uint8_t event[13]; 649 sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_COMPLETE, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address); 650 event[11] = status; 651 event[12] = reason; 652 sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event)); 653 } 654 655 // SMP Timeout implementation 656 657 // Upon transmission of the Pairing Request command or reception of the Pairing Request command, 658 // the Security Manager Timer shall be reset and started. 659 // 660 // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission. 661 // 662 // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed, 663 // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP 664 // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been 665 // established. 666 667 static void sm_timeout_handler(btstack_timer_source_t * timer){ 668 log_info("SM timeout"); 669 sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer); 670 sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT; 671 sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT); 672 sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0); 673 sm_done_for_handle(sm_conn->sm_handle); 674 675 // trigger handling of next ready connection 676 sm_run(); 677 } 678 static void sm_timeout_start(sm_connection_t * sm_conn){ 679 btstack_run_loop_remove_timer(&setup->sm_timeout); 680 btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn); 681 btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler); 682 btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout 683 btstack_run_loop_add_timer(&setup->sm_timeout); 684 } 685 static void sm_timeout_stop(void){ 686 btstack_run_loop_remove_timer(&setup->sm_timeout); 687 } 688 static void sm_timeout_reset(sm_connection_t * sm_conn){ 689 sm_timeout_stop(); 690 sm_timeout_start(sm_conn); 691 } 692 693 // end of sm timeout 694 695 // GAP Random Address updates 696 static gap_random_address_type_t gap_random_adress_type; 697 static btstack_timer_source_t gap_random_address_update_timer; 698 static uint32_t gap_random_adress_update_period; 699 700 static void gap_random_address_trigger(void){ 701 log_info("gap_random_address_trigger, state %u", rau_state); 702 if (rau_state != RAU_IDLE) return; 703 rau_state = RAU_GET_RANDOM; 704 sm_trigger_run(); 705 } 706 707 static void gap_random_address_update_handler(btstack_timer_source_t * timer){ 708 UNUSED(timer); 709 710 log_info("GAP Random Address Update due"); 711 btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period); 712 btstack_run_loop_add_timer(&gap_random_address_update_timer); 713 gap_random_address_trigger(); 714 } 715 716 static void gap_random_address_update_start(void){ 717 btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler); 718 btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period); 719 btstack_run_loop_add_timer(&gap_random_address_update_timer); 720 } 721 722 static void gap_random_address_update_stop(void){ 723 btstack_run_loop_remove_timer(&gap_random_address_update_timer); 724 } 725 726 // ah(k,r) helper 727 // r = padding || r 728 // r - 24 bit value 729 static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){ 730 // r'= padding || r 731 memset(r_prime, 0, 16); 732 (void)memcpy(&r_prime[13], r, 3); 733 } 734 735 // d1 helper 736 // d' = padding || r || d 737 // d,r - 16 bit values 738 static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){ 739 // d'= padding || r || d 740 memset(d1_prime, 0, 16); 741 big_endian_store_16(d1_prime, 12, r); 742 big_endian_store_16(d1_prime, 14, d); 743 } 744 745 // calculate arguments for first AES128 operation in C1 function 746 static void sm_c1_t1(sm_key_t r, uint8_t preq[7], uint8_t pres[7], uint8_t iat, uint8_t rat, uint8_t * t1){ 747 748 // p1 = pres || preq || rat’ || iat’ 749 // "The octet of iat’ becomes the least significant octet of p1 and the most signifi- 750 // cant octet of pres becomes the most significant octet of p1. 751 // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq 752 // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then 753 // p1 is 0x05000800000302070710000001010001." 754 755 sm_key_t p1; 756 reverse_56(pres, &p1[0]); 757 reverse_56(preq, &p1[7]); 758 p1[14] = rat; 759 p1[15] = iat; 760 log_info_key("p1", p1); 761 log_info_key("r", r); 762 763 // t1 = r xor p1 764 int i; 765 for (i=0;i<16;i++){ 766 t1[i] = r[i] ^ p1[i]; 767 } 768 log_info_key("t1", t1); 769 } 770 771 // calculate arguments for second AES128 operation in C1 function 772 static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){ 773 // p2 = padding || ia || ra 774 // "The least significant octet of ra becomes the least significant octet of p2 and 775 // the most significant octet of padding becomes the most significant octet of p2. 776 // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is 777 // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6. 778 779 sm_key_t p2; 780 memset(p2, 0, 16); 781 (void)memcpy(&p2[4], ia, 6); 782 (void)memcpy(&p2[10], ra, 6); 783 log_info_key("p2", p2); 784 785 // c1 = e(k, t2_xor_p2) 786 int i; 787 for (i=0;i<16;i++){ 788 t3[i] = t2[i] ^ p2[i]; 789 } 790 log_info_key("t3", t3); 791 } 792 793 static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){ 794 log_info_key("r1", r1); 795 log_info_key("r2", r2); 796 (void)memcpy(&r_prime[8], &r2[8], 8); 797 (void)memcpy(&r_prime[0], &r1[8], 8); 798 } 799 800 801 // decide on stk generation based on 802 // - pairing request 803 // - io capabilities 804 // - OOB data availability 805 static void sm_setup_tk(void){ 806 807 // horizontal: initiator capabilities 808 // vertial: responder capabilities 809 static const stk_generation_method_t stk_generation_method [5] [5] = { 810 { JUST_WORKS, JUST_WORKS, PK_INIT_INPUT, JUST_WORKS, PK_INIT_INPUT }, 811 { JUST_WORKS, JUST_WORKS, PK_INIT_INPUT, JUST_WORKS, PK_INIT_INPUT }, 812 { PK_RESP_INPUT, PK_RESP_INPUT, PK_BOTH_INPUT, JUST_WORKS, PK_RESP_INPUT }, 813 { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, 814 { PK_RESP_INPUT, PK_RESP_INPUT, PK_INIT_INPUT, JUST_WORKS, PK_RESP_INPUT }, 815 }; 816 817 // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations 818 #ifdef ENABLE_LE_SECURE_CONNECTIONS 819 static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = { 820 { JUST_WORKS, JUST_WORKS, PK_INIT_INPUT, JUST_WORKS, PK_INIT_INPUT }, 821 { JUST_WORKS, NUMERIC_COMPARISON, PK_INIT_INPUT, JUST_WORKS, NUMERIC_COMPARISON }, 822 { PK_RESP_INPUT, PK_RESP_INPUT, PK_BOTH_INPUT, JUST_WORKS, PK_RESP_INPUT }, 823 { JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS, JUST_WORKS }, 824 { PK_RESP_INPUT, NUMERIC_COMPARISON, PK_INIT_INPUT, JUST_WORKS, NUMERIC_COMPARISON }, 825 }; 826 #endif 827 828 // default: just works 829 setup->sm_stk_generation_method = JUST_WORKS; 830 831 #ifdef ENABLE_LE_SECURE_CONNECTIONS 832 setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq) 833 & sm_pairing_packet_get_auth_req(setup->sm_s_pres) 834 & SM_AUTHREQ_SECURE_CONNECTION ) != 0u; 835 #else 836 setup->sm_use_secure_connections = 0; 837 #endif 838 log_info("Secure pairing: %u", setup->sm_use_secure_connections); 839 840 841 // decide if OOB will be used based on SC vs. Legacy and oob flags 842 bool use_oob; 843 if (setup->sm_use_secure_connections){ 844 // In LE Secure Connections pairing, the out of band method is used if at least 845 // one device has the peer device's out of band authentication data available. 846 use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0; 847 } else { 848 // In LE legacy pairing, the out of band method is used if both the devices have 849 // the other device's out of band authentication data available. 850 use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0; 851 } 852 if (use_oob){ 853 log_info("SM: have OOB data"); 854 log_info_key("OOB", setup->sm_tk); 855 setup->sm_stk_generation_method = OOB; 856 return; 857 } 858 859 // If both devices have not set the MITM option in the Authentication Requirements 860 // Flags, then the IO capabilities shall be ignored and the Just Works association 861 // model shall be used. 862 if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u) 863 && ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){ 864 log_info("SM: MITM not required by both -> JUST WORKS"); 865 return; 866 } 867 868 // Reset TK as it has been setup in sm_init_setup 869 sm_reset_tk(); 870 871 // Also use just works if unknown io capabilites 872 if ((sm_pairing_packet_get_io_capability(setup->sm_m_preq) > IO_CAPABILITY_KEYBOARD_DISPLAY) || (sm_pairing_packet_get_io_capability(setup->sm_s_pres) > IO_CAPABILITY_KEYBOARD_DISPLAY)){ 873 return; 874 } 875 876 // Otherwise the IO capabilities of the devices shall be used to determine the 877 // pairing method as defined in Table 2.4. 878 // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array 879 const stk_generation_method_t (*generation_method)[5] = stk_generation_method; 880 881 #ifdef ENABLE_LE_SECURE_CONNECTIONS 882 // table not define by default 883 if (setup->sm_use_secure_connections){ 884 generation_method = stk_generation_method_with_secure_connection; 885 } 886 #endif 887 setup->sm_stk_generation_method = generation_method[sm_pairing_packet_get_io_capability(setup->sm_s_pres)][sm_pairing_packet_get_io_capability(setup->sm_m_preq)]; 888 889 log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u", 890 sm_pairing_packet_get_io_capability(setup->sm_m_preq), sm_pairing_packet_get_io_capability(setup->sm_s_pres), setup->sm_stk_generation_method); 891 } 892 893 static int sm_key_distribution_flags_for_set(uint8_t key_set){ 894 int flags = 0; 895 if (key_set & SM_KEYDIST_ENC_KEY){ 896 flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 897 flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 898 } 899 if (key_set & SM_KEYDIST_ID_KEY){ 900 flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 901 flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 902 } 903 if (key_set & SM_KEYDIST_SIGN){ 904 flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 905 } 906 return flags; 907 } 908 909 static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){ 910 setup->sm_key_distribution_received_set = 0; 911 setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive); 912 setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send); 913 setup->sm_key_distribution_sent_set = 0; 914 #ifdef ENABLE_LE_SIGNED_WRITE 915 setup->sm_le_device_index = -1; 916 #endif 917 } 918 919 // CSRK Key Lookup 920 921 922 static int sm_address_resolution_idle(void){ 923 return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE; 924 } 925 926 static void sm_address_resolution_start_lookup(uint8_t addr_type, hci_con_handle_t con_handle, bd_addr_t addr, address_resolution_mode_t mode, void * context){ 927 (void)memcpy(sm_address_resolution_address, addr, 6); 928 sm_address_resolution_addr_type = addr_type; 929 sm_address_resolution_test = 0; 930 sm_address_resolution_mode = mode; 931 sm_address_resolution_context = context; 932 sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr); 933 } 934 935 int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){ 936 // check if already in list 937 btstack_linked_list_iterator_t it; 938 sm_lookup_entry_t * entry; 939 btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue); 940 while(btstack_linked_list_iterator_has_next(&it)){ 941 entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it); 942 if (entry->address_type != address_type) continue; 943 if (memcmp(entry->address, address, 6)) continue; 944 // already in list 945 return BTSTACK_BUSY; 946 } 947 entry = btstack_memory_sm_lookup_entry_get(); 948 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 949 entry->address_type = (bd_addr_type_t) address_type; 950 (void)memcpy(entry->address, address, 6); 951 btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry); 952 sm_trigger_run(); 953 return 0; 954 } 955 956 // CMAC calculation using AES Engineq 957 #ifdef USE_CMAC_ENGINE 958 959 static void sm_cmac_done_trampoline(void * arg){ 960 UNUSED(arg); 961 sm_cmac_active = 0; 962 (*sm_cmac_done_callback)(sm_cmac_hash); 963 sm_trigger_run(); 964 } 965 966 int sm_cmac_ready(void){ 967 return sm_cmac_active == 0u; 968 } 969 #endif 970 971 #ifdef ENABLE_LE_SECURE_CONNECTIONS 972 // generic cmac calculation 973 static void sm_cmac_message_start(const sm_key_t key, uint16_t message_len, const uint8_t * message, void (*done_callback)(uint8_t * hash)){ 974 sm_cmac_active = 1; 975 sm_cmac_done_callback = done_callback; 976 btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL); 977 } 978 #endif 979 980 // cmac for ATT Message signing 981 #ifdef ENABLE_LE_SIGNED_WRITE 982 983 static void sm_cmac_generator_start(const sm_key_t key, uint16_t message_len, uint8_t (*get_byte_callback)(uint16_t offset), void (*done_callback)(uint8_t * hash)){ 984 sm_cmac_active = 1; 985 sm_cmac_done_callback = done_callback; 986 btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL); 987 } 988 989 static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){ 990 if (offset >= sm_cmac_signed_write_message_len) { 991 log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len); 992 return 0; 993 } 994 995 offset = sm_cmac_signed_write_message_len - 1 - offset; 996 997 // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4] 998 if (offset < 3){ 999 return sm_cmac_signed_write_header[offset]; 1000 } 1001 int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4; 1002 if (offset < actual_message_len_incl_header){ 1003 return sm_cmac_signed_write_message[offset - 3]; 1004 } 1005 return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header]; 1006 } 1007 1008 void sm_cmac_signed_write_start(const sm_key_t k, uint8_t opcode, hci_con_handle_t con_handle, uint16_t message_len, const uint8_t * message, uint32_t sign_counter, void (*done_handler)(uint8_t * hash)){ 1009 // ATT Message Signing 1010 sm_cmac_signed_write_header[0] = opcode; 1011 little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle); 1012 little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter); 1013 uint16_t total_message_len = 3 + message_len + 4; // incl. virtually prepended att opcode, handle and appended sign_counter in LE 1014 sm_cmac_signed_write_message = message; 1015 sm_cmac_signed_write_message_len = total_message_len; 1016 sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler); 1017 } 1018 #endif 1019 1020 static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){ 1021 setup->sm_user_response = SM_USER_RESPONSE_PENDING; 1022 uint8_t event[12]; 1023 sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address); 1024 event[11] = setup->sm_use_secure_connections ? 1 : 0; 1025 sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1026 } 1027 1028 static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn, uint8_t event_type){ 1029 uint8_t event[16]; 1030 uint32_t passkey = big_endian_read_32(setup->sm_tk, 12); 1031 sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle, 1032 sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address); 1033 event[11] = setup->sm_use_secure_connections ? 1 : 0; 1034 little_endian_store_32(event, 12, passkey); 1035 sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1036 } 1037 1038 static void sm_trigger_user_response(sm_connection_t * sm_conn){ 1039 // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input 1040 setup->sm_user_response = SM_USER_RESPONSE_IDLE; 1041 sm_conn->sm_pairing_active = true; 1042 switch (setup->sm_stk_generation_method){ 1043 case PK_RESP_INPUT: 1044 if (IS_RESPONDER(sm_conn->sm_role)){ 1045 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER); 1046 } else { 1047 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER); 1048 } 1049 break; 1050 case PK_INIT_INPUT: 1051 if (IS_RESPONDER(sm_conn->sm_role)){ 1052 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER); 1053 } else { 1054 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER); 1055 } 1056 break; 1057 case PK_BOTH_INPUT: 1058 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER); 1059 break; 1060 case NUMERIC_COMPARISON: 1061 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST); 1062 break; 1063 case JUST_WORKS: 1064 sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST); 1065 break; 1066 case OOB: 1067 // client already provided OOB data, let's skip notification. 1068 break; 1069 default: 1070 btstack_assert(false); 1071 break; 1072 } 1073 } 1074 1075 static bool sm_key_distribution_all_received(void) { 1076 log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, setup->sm_key_distribution_expected_set); 1077 return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set; 1078 } 1079 1080 static void sm_done_for_handle(hci_con_handle_t con_handle){ 1081 if (sm_active_connection_handle == con_handle){ 1082 sm_timeout_stop(); 1083 sm_active_connection_handle = HCI_CON_HANDLE_INVALID; 1084 log_info("sm: connection 0x%x released setup context", con_handle); 1085 1086 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1087 // generate new ec key after each pairing (that used it) 1088 if (setup->sm_use_secure_connections){ 1089 sm_ec_generate_new_key(); 1090 } 1091 #endif 1092 } 1093 } 1094 1095 static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done 1096 connection->sm_engine_state = SM_INITIATOR_CONNECTED; 1097 sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0); 1098 sm_done_for_handle(connection->sm_handle); 1099 } 1100 1101 static int sm_key_distribution_flags_for_auth_req(void){ 1102 1103 int flags = SM_KEYDIST_ID_KEY; 1104 if (sm_auth_req & SM_AUTHREQ_BONDING){ 1105 // encryption and signing information only if bonding requested 1106 flags |= SM_KEYDIST_ENC_KEY; 1107 #ifdef ENABLE_LE_SIGNED_WRITE 1108 flags |= SM_KEYDIST_SIGN; 1109 #endif 1110 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1111 // LinkKey for CTKD requires SC 1112 if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){ 1113 flags |= SM_KEYDIST_LINK_KEY; 1114 } 1115 #endif 1116 } 1117 return flags; 1118 } 1119 1120 static void sm_reset_setup(void){ 1121 // fill in sm setup 1122 setup->sm_state_vars = 0; 1123 setup->sm_keypress_notification = 0; 1124 setup->sm_have_oob_data = 0; 1125 sm_reset_tk(); 1126 } 1127 1128 static void sm_init_setup(sm_connection_t * sm_conn){ 1129 // fill in sm setup 1130 setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type; 1131 (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6); 1132 1133 // query client for Legacy Pairing OOB data 1134 if (sm_get_oob_data != NULL) { 1135 setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk); 1136 } 1137 1138 // if available and SC supported, also ask for SC OOB Data 1139 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1140 memset(setup->sm_ra, 0, 16); 1141 memset(setup->sm_rb, 0, 16); 1142 if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){ 1143 if (sm_get_sc_oob_data != NULL){ 1144 if (IS_RESPONDER(sm_conn->sm_role)){ 1145 setup->sm_have_oob_data = (*sm_get_sc_oob_data)( 1146 sm_conn->sm_peer_addr_type, 1147 sm_conn->sm_peer_address, 1148 setup->sm_peer_confirm, 1149 setup->sm_ra); 1150 } else { 1151 setup->sm_have_oob_data = (*sm_get_sc_oob_data)( 1152 sm_conn->sm_peer_addr_type, 1153 sm_conn->sm_peer_address, 1154 setup->sm_peer_confirm, 1155 setup->sm_rb); 1156 } 1157 } else { 1158 setup->sm_have_oob_data = 0; 1159 } 1160 } 1161 #endif 1162 1163 sm_pairing_packet_t * local_packet; 1164 if (IS_RESPONDER(sm_conn->sm_role)){ 1165 // slave 1166 local_packet = &setup->sm_s_pres; 1167 setup->sm_m_addr_type = sm_conn->sm_peer_addr_type; 1168 setup->sm_s_addr_type = sm_conn->sm_own_addr_type; 1169 (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6); 1170 (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6); 1171 } else { 1172 // master 1173 local_packet = &setup->sm_m_preq; 1174 setup->sm_s_addr_type = sm_conn->sm_peer_addr_type; 1175 setup->sm_m_addr_type = sm_conn->sm_own_addr_type; 1176 (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6); 1177 (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6); 1178 1179 uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req(); 1180 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags); 1181 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags); 1182 } 1183 1184 uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2; 1185 uint8_t max_encryption_key_size = sm_max_encryption_key_size; 1186 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1187 // enable SC for SC only mode 1188 if (sm_sc_only_mode){ 1189 auth_req |= SM_AUTHREQ_SECURE_CONNECTION; 1190 max_encryption_key_size = 16; 1191 } 1192 #endif 1193 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1194 // set CT2 if SC + Bonding + CTKD 1195 const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING; 1196 if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){ 1197 auth_req |= SM_AUTHREQ_CT2; 1198 } 1199 #endif 1200 sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities); 1201 sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data); 1202 sm_pairing_packet_set_auth_req(*local_packet, auth_req); 1203 sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size); 1204 } 1205 1206 static int sm_stk_generation_init(sm_connection_t * sm_conn){ 1207 1208 sm_pairing_packet_t * remote_packet; 1209 uint8_t keys_to_send; 1210 uint8_t keys_to_receive; 1211 if (IS_RESPONDER(sm_conn->sm_role)){ 1212 // slave / responder 1213 remote_packet = &setup->sm_m_preq; 1214 keys_to_send = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq); 1215 keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq); 1216 } else { 1217 // master / initiator 1218 remote_packet = &setup->sm_s_pres; 1219 keys_to_send = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres); 1220 keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres); 1221 } 1222 1223 // check key size 1224 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1225 // SC Only mandates 128 bit key size 1226 if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) { 1227 return SM_REASON_ENCRYPTION_KEY_SIZE; 1228 } 1229 #endif 1230 sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet)); 1231 if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE; 1232 1233 // decide on STK generation method / SC 1234 sm_setup_tk(); 1235 log_info("SMP: generation method %u", setup->sm_stk_generation_method); 1236 1237 // check if STK generation method is acceptable by client 1238 if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS; 1239 1240 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1241 // Check LE SC Only mode 1242 if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){ 1243 log_info("SC Only mode active but SC not possible"); 1244 return SM_REASON_AUTHENTHICATION_REQUIREMENTS; 1245 } 1246 1247 // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection 1248 if (setup->sm_use_secure_connections){ 1249 keys_to_send &= ~SM_KEYDIST_ENC_KEY; 1250 keys_to_receive &= ~SM_KEYDIST_ENC_KEY; 1251 } 1252 #endif 1253 1254 // identical to responder 1255 sm_setup_key_distribution(keys_to_send, keys_to_receive); 1256 1257 // JUST WORKS doens't provide authentication 1258 sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1; 1259 1260 return 0; 1261 } 1262 1263 static void sm_address_resolution_handle_event(address_resolution_event_t event){ 1264 1265 // cache and reset context 1266 int matched_device_id = sm_address_resolution_test; 1267 address_resolution_mode_t mode = sm_address_resolution_mode; 1268 void * context = sm_address_resolution_context; 1269 1270 // reset context 1271 sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE; 1272 sm_address_resolution_context = NULL; 1273 sm_address_resolution_test = -1; 1274 hci_con_handle_t con_handle = 0; 1275 1276 sm_connection_t * sm_connection; 1277 sm_key_t ltk; 1278 bool have_ltk; 1279 #ifdef ENABLE_LE_CENTRAL 1280 bool trigger_pairing; 1281 #endif 1282 switch (mode){ 1283 case ADDRESS_RESOLUTION_GENERAL: 1284 break; 1285 case ADDRESS_RESOLUTION_FOR_CONNECTION: 1286 sm_connection = (sm_connection_t *) context; 1287 con_handle = sm_connection->sm_handle; 1288 1289 // have ltk -> start encryption / send security request 1290 // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request 1291 // "When a bond has been created between two devices, any reconnection should result in the local device 1292 // enabling or requesting encryption with the remote device before initiating any service request." 1293 1294 switch (event){ 1295 case ADDRESS_RESOLUTION_SUCCEEDED: 1296 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED; 1297 sm_connection->sm_le_db_index = matched_device_id; 1298 log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index); 1299 1300 le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 1301 have_ltk = !sm_is_null_key(ltk); 1302 1303 if (sm_connection->sm_role) { 1304 #ifdef ENABLE_LE_PERIPHERAL 1305 // IRK required before, continue 1306 if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){ 1307 sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 1308 break; 1309 } 1310 if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){ 1311 sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED; 1312 break; 1313 } 1314 bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0); 1315 sm_connection->sm_pairing_requested = 0; 1316 #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION 1317 // trigger security request for Proactive Authentication if LTK available 1318 trigger_security_request = trigger_security_request || have_ltk; 1319 #endif 1320 1321 log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u", 1322 sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request); 1323 1324 if (trigger_security_request){ 1325 sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 1326 if (have_ltk){ 1327 sm_reencryption_started(sm_connection); 1328 } else { 1329 sm_pairing_started(sm_connection); 1330 } 1331 sm_trigger_run(); 1332 } 1333 #endif 1334 } else { 1335 1336 #ifdef ENABLE_LE_CENTRAL 1337 // check if pairing already requested and reset requests 1338 trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received; 1339 log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u", 1340 sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk); 1341 sm_connection->sm_security_request_received = 0; 1342 sm_connection->sm_pairing_requested = 0; 1343 bool trigger_reencryption = false; 1344 1345 if (have_ltk){ 1346 #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION 1347 trigger_reencryption = true; 1348 #else 1349 if (trigger_pairing){ 1350 trigger_reencryption = true; 1351 } else { 1352 log_info("central: defer enabling encryption for bonded device"); 1353 } 1354 #endif 1355 } 1356 1357 if (trigger_reencryption){ 1358 log_info("central: enable encryption for bonded device"); 1359 sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK; 1360 break; 1361 } 1362 1363 // pairing_request -> send pairing request 1364 if (trigger_pairing){ 1365 sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 1366 break; 1367 } 1368 #endif 1369 } 1370 break; 1371 case ADDRESS_RESOLUTION_FAILED: 1372 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED; 1373 if (sm_connection->sm_role) { 1374 #ifdef ENABLE_LE_PERIPHERAL 1375 // LTK request received before, IRK required -> negative LTK reply 1376 if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){ 1377 sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 1378 } 1379 // send security request if requested 1380 bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0); 1381 sm_connection->sm_pairing_requested = 0; 1382 if (trigger_security_request){ 1383 sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 1384 sm_pairing_started(sm_connection); 1385 } 1386 break; 1387 #endif 1388 } 1389 #ifdef ENABLE_LE_CENTRAL 1390 if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break; 1391 sm_connection->sm_security_request_received = 0; 1392 sm_connection->sm_pairing_requested = 0; 1393 sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 1394 #endif 1395 break; 1396 1397 default: 1398 btstack_assert(false); 1399 break; 1400 } 1401 break; 1402 default: 1403 break; 1404 } 1405 1406 switch (event){ 1407 case ADDRESS_RESOLUTION_SUCCEEDED: 1408 sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id); 1409 break; 1410 case ADDRESS_RESOLUTION_FAILED: 1411 sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address); 1412 break; 1413 default: 1414 btstack_assert(false); 1415 break; 1416 } 1417 } 1418 1419 static void sm_store_bonding_information(sm_connection_t * sm_conn){ 1420 int le_db_index = -1; 1421 1422 // lookup device based on IRK 1423 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 1424 int i; 1425 for (i=0; i < le_device_db_max_count(); i++){ 1426 sm_key_t irk; 1427 bd_addr_t address; 1428 int address_type = BD_ADDR_TYPE_UNKNOWN; 1429 le_device_db_info(i, &address_type, address, irk); 1430 // skip unused entries 1431 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue; 1432 // compare Identity Address 1433 if (memcmp(address, setup->sm_peer_address, 6) != 0) continue; 1434 // compare Identity Resolving Key 1435 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue; 1436 1437 log_info("sm: device found for IRK, updating"); 1438 le_db_index = i; 1439 break; 1440 } 1441 } else { 1442 // assert IRK is set to zero 1443 memset(setup->sm_peer_irk, 0, 16); 1444 } 1445 1446 // if not found, lookup via public address if possible 1447 log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address)); 1448 if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){ 1449 int i; 1450 for (i=0; i < le_device_db_max_count(); i++){ 1451 bd_addr_t address; 1452 int address_type = BD_ADDR_TYPE_UNKNOWN; 1453 le_device_db_info(i, &address_type, address, NULL); 1454 // skip unused entries 1455 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue; 1456 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address)); 1457 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){ 1458 log_info("sm: device found for public address, updating"); 1459 le_db_index = i; 1460 break; 1461 } 1462 } 1463 } 1464 1465 // if not found, add to db 1466 bool new_to_le_device_db = false; 1467 if (le_db_index < 0) { 1468 le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk); 1469 new_to_le_device_db = true; 1470 } 1471 1472 if (le_db_index >= 0){ 1473 1474 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 1475 if (!new_to_le_device_db){ 1476 hci_remove_le_device_db_entry_from_resolving_list(le_db_index); 1477 } 1478 hci_load_le_device_db_entry_into_resolving_list(le_db_index); 1479 #else 1480 UNUSED(new_to_le_device_db); 1481 #endif 1482 1483 sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index); 1484 sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED; 1485 sm_conn->sm_le_db_index = le_db_index; 1486 1487 #ifdef ENABLE_LE_SIGNED_WRITE 1488 // store local CSRK 1489 setup->sm_le_device_index = le_db_index; 1490 if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 1491 log_info("sm: store local CSRK"); 1492 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk); 1493 le_device_db_local_counter_set(le_db_index, 0); 1494 } 1495 1496 // store remote CSRK 1497 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 1498 log_info("sm: store remote CSRK"); 1499 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk); 1500 le_device_db_remote_counter_set(le_db_index, 0); 1501 } 1502 #endif 1503 // store encryption information for secure connections: LTK generated by ECDH 1504 if (setup->sm_use_secure_connections){ 1505 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated); 1506 uint8_t zero_rand[8]; 1507 memset(zero_rand, 0, 8); 1508 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size, 1509 sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1); 1510 } 1511 1512 // store encryption information for legacy pairing: peer LTK, EDIV, RAND 1513 else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION) 1514 && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){ 1515 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated); 1516 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk, 1517 sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0); 1518 1519 } 1520 } 1521 } 1522 1523 static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){ 1524 sm_conn->sm_pairing_failed_reason = reason; 1525 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 1526 } 1527 1528 static int sm_lookup_by_address(void) { 1529 int i; 1530 for (i=0; i < le_device_db_max_count(); i++){ 1531 bd_addr_t address; 1532 int address_type = BD_ADDR_TYPE_UNKNOWN; 1533 le_device_db_info(i, &address_type, address, NULL); 1534 // skip unused entries 1535 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue; 1536 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){ 1537 return i; 1538 } 1539 } 1540 return -1; 1541 } 1542 1543 static void sm_remove_le_device_db_entry(uint16_t i) { 1544 le_device_db_remove(i); 1545 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 1546 // to remove an entry from the resolving list requires its identity address, which was already deleted 1547 // fully reload resolving list instead 1548 gap_load_resolving_list_from_le_device_db(); 1549 #endif 1550 } 1551 1552 static uint8_t sm_key_distribution_validate_received(sm_connection_t * sm_conn){ 1553 // if identity is provided, abort if we have bonding with same address but different irk 1554 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 1555 int index = sm_lookup_by_address(); 1556 if (index >= 0){ 1557 sm_key_t irk; 1558 le_device_db_info(index, NULL, NULL, irk); 1559 if (memcmp(irk, setup->sm_peer_irk, 16) != 0){ 1560 // IRK doesn't match, delete bonding information 1561 log_info("New IRK for %s (type %u) does not match stored IRK -> delete bonding information", bd_addr_to_str(sm_conn->sm_peer_address), sm_conn->sm_peer_addr_type); 1562 sm_remove_le_device_db_entry(index); 1563 } 1564 } 1565 } 1566 return 0; 1567 } 1568 1569 static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){ 1570 1571 // abort pairing if received keys are not valid 1572 uint8_t reason = sm_key_distribution_validate_received(sm_conn); 1573 if (reason != 0){ 1574 sm_pairing_error(sm_conn, reason); 1575 return; 1576 } 1577 1578 // only store pairing information if both sides are bondable, i.e., the bonadble flag is set 1579 bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) 1580 & sm_pairing_packet_get_auth_req(setup->sm_s_pres) 1581 & SM_AUTHREQ_BONDING ) != 0u; 1582 1583 if (bonding_enabled){ 1584 sm_store_bonding_information(sm_conn); 1585 } else { 1586 log_info("Ignoring received keys, bonding not enabled"); 1587 } 1588 } 1589 1590 static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){ 1591 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 1592 } 1593 1594 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1595 1596 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn); 1597 static int sm_passkey_used(stk_generation_method_t method); 1598 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method); 1599 1600 static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){ 1601 if (setup->sm_stk_generation_method == OOB){ 1602 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 1603 } else { 1604 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_w2_cmac_for_confirmation, (void *)(uintptr_t) sm_conn->sm_handle); 1605 } 1606 } 1607 1608 static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){ 1609 if (IS_RESPONDER(sm_conn->sm_role)){ 1610 // Responder 1611 if (setup->sm_stk_generation_method == OOB){ 1612 // generate Nb 1613 log_info("Generate Nb"); 1614 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_send_pairing_random, (void *)(uintptr_t) sm_conn->sm_handle); 1615 } else { 1616 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 1617 } 1618 } else { 1619 // Initiator role 1620 switch (setup->sm_stk_generation_method){ 1621 case JUST_WORKS: 1622 sm_sc_prepare_dhkey_check(sm_conn); 1623 break; 1624 1625 case NUMERIC_COMPARISON: 1626 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2; 1627 break; 1628 case PK_INIT_INPUT: 1629 case PK_RESP_INPUT: 1630 case PK_BOTH_INPUT: 1631 if (setup->sm_passkey_bit < 20u) { 1632 sm_sc_start_calculating_local_confirm(sm_conn); 1633 } else { 1634 sm_sc_prepare_dhkey_check(sm_conn); 1635 } 1636 break; 1637 case OOB: 1638 sm_sc_prepare_dhkey_check(sm_conn); 1639 break; 1640 default: 1641 btstack_assert(false); 1642 break; 1643 } 1644 } 1645 } 1646 1647 static void sm_sc_cmac_done(uint8_t * hash){ 1648 log_info("sm_sc_cmac_done: "); 1649 log_info_hexdump(hash, 16); 1650 1651 if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){ 1652 sm_sc_oob_state = SM_SC_OOB_IDLE; 1653 (*sm_sc_oob_callback)(hash, sm_sc_oob_random); 1654 return; 1655 } 1656 1657 sm_connection_t * sm_conn = sm_cmac_connection; 1658 sm_cmac_connection = NULL; 1659 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1660 link_key_type_t link_key_type; 1661 #endif 1662 1663 switch (sm_conn->sm_engine_state){ 1664 case SM_SC_W4_CMAC_FOR_CONFIRMATION: 1665 (void)memcpy(setup->sm_local_confirm, hash, 16); 1666 sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION; 1667 break; 1668 case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION: 1669 // check 1670 if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){ 1671 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED); 1672 break; 1673 } 1674 sm_sc_state_after_receiving_random(sm_conn); 1675 break; 1676 case SM_SC_W4_CALCULATE_G2: { 1677 uint32_t vab = big_endian_read_32(hash, 12) % 1000000; 1678 big_endian_store_32(setup->sm_tk, 12, vab); 1679 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 1680 sm_trigger_user_response(sm_conn); 1681 break; 1682 } 1683 case SM_SC_W4_CALCULATE_F5_SALT: 1684 (void)memcpy(setup->sm_t, hash, 16); 1685 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY; 1686 break; 1687 case SM_SC_W4_CALCULATE_F5_MACKEY: 1688 (void)memcpy(setup->sm_mackey, hash, 16); 1689 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK; 1690 break; 1691 case SM_SC_W4_CALCULATE_F5_LTK: 1692 // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk 1693 // Errata Service Release to the Bluetooth Specification: ESR09 1694 // E6405 – Cross transport key derivation from a key of size less than 128 bits 1695 // Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 1696 (void)memcpy(setup->sm_ltk, hash, 16); 1697 (void)memcpy(setup->sm_local_ltk, hash, 16); 1698 sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size); 1699 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK; 1700 break; 1701 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 1702 (void)memcpy(setup->sm_local_dhkey_check, hash, 16); 1703 if (IS_RESPONDER(sm_conn->sm_role)){ 1704 // responder 1705 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){ 1706 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 1707 } else { 1708 sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 1709 } 1710 } else { 1711 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1712 } 1713 break; 1714 case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 1715 if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){ 1716 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 1717 break; 1718 } 1719 if (IS_RESPONDER(sm_conn->sm_role)){ 1720 // responder 1721 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1722 } else { 1723 // initiator 1724 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 1725 } 1726 break; 1727 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1728 case SM_SC_W4_CALCULATE_ILK: 1729 (void)memcpy(setup->sm_t, hash, 16); 1730 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY; 1731 break; 1732 case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY: 1733 reverse_128(hash, setup->sm_t); 1734 link_key_type = sm_conn->sm_connection_authenticated ? 1735 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256; 1736 log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type); 1737 gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type); 1738 if (IS_RESPONDER(sm_conn->sm_role)){ 1739 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 1740 } else { 1741 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 1742 } 1743 sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0); 1744 sm_done_for_handle(sm_conn->sm_handle); 1745 break; 1746 case SM_BR_EDR_W4_CALCULATE_ILK: 1747 (void)memcpy(setup->sm_t, hash, 16); 1748 sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK; 1749 break; 1750 case SM_BR_EDR_W4_CALCULATE_LE_LTK: 1751 log_info("Derived LE LTK from BR/EDR Link Key"); 1752 log_info_key("Link Key", hash); 1753 (void)memcpy(setup->sm_ltk, hash, 16); 1754 sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size); 1755 sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256; 1756 sm_store_bonding_information(sm_conn); 1757 sm_done_for_handle(sm_conn->sm_handle); 1758 break; 1759 #endif 1760 default: 1761 log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state); 1762 break; 1763 } 1764 sm_trigger_run(); 1765 } 1766 1767 static void f4_engine(sm_connection_t * sm_conn, const sm_key256_t u, const sm_key256_t v, const sm_key_t x, uint8_t z){ 1768 const uint16_t message_len = 65; 1769 sm_cmac_connection = sm_conn; 1770 (void)memcpy(sm_cmac_sc_buffer, u, 32); 1771 (void)memcpy(sm_cmac_sc_buffer + 32, v, 32); 1772 sm_cmac_sc_buffer[64] = z; 1773 log_info("f4 key"); 1774 log_info_hexdump(x, 16); 1775 log_info("f4 message"); 1776 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1777 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1778 } 1779 1780 static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 }; 1781 static const uint8_t f5_length[] = { 0x01, 0x00}; 1782 1783 static void f5_calculate_salt(sm_connection_t * sm_conn){ 1784 1785 static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE}; 1786 1787 log_info("f5_calculate_salt"); 1788 // calculate salt for f5 1789 const uint16_t message_len = 32; 1790 sm_cmac_connection = sm_conn; 1791 (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len); 1792 sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1793 } 1794 1795 static inline void f5_mackkey(sm_connection_t * sm_conn, sm_key_t t, const sm_key_t n1, const sm_key_t n2, const sm_key56_t a1, const sm_key56_t a2){ 1796 const uint16_t message_len = 53; 1797 sm_cmac_connection = sm_conn; 1798 1799 // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey 1800 sm_cmac_sc_buffer[0] = 0; 1801 (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4); 1802 (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16); 1803 (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16); 1804 (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7); 1805 (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7); 1806 (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2); 1807 log_info("f5 key"); 1808 log_info_hexdump(t, 16); 1809 log_info("f5 message for MacKey"); 1810 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1811 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1812 } 1813 1814 static void f5_calculate_mackey(sm_connection_t * sm_conn){ 1815 sm_key56_t bd_addr_master, bd_addr_slave; 1816 bd_addr_master[0] = setup->sm_m_addr_type; 1817 bd_addr_slave[0] = setup->sm_s_addr_type; 1818 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1819 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1820 if (IS_RESPONDER(sm_conn->sm_role)){ 1821 // responder 1822 f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave); 1823 } else { 1824 // initiator 1825 f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave); 1826 } 1827 } 1828 1829 // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused 1830 static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){ 1831 const uint16_t message_len = 53; 1832 sm_cmac_connection = sm_conn; 1833 sm_cmac_sc_buffer[0] = 1; 1834 // 1..52 setup before 1835 log_info("f5 key"); 1836 log_info_hexdump(t, 16); 1837 log_info("f5 message for LTK"); 1838 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1839 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1840 } 1841 1842 static void f5_calculate_ltk(sm_connection_t * sm_conn){ 1843 f5_ltk(sm_conn, setup->sm_t); 1844 } 1845 1846 static void f6_setup(const sm_key_t n1, const sm_key_t n2, const sm_key_t r, const sm_key24_t io_cap, const sm_key56_t a1, const sm_key56_t a2){ 1847 (void)memcpy(sm_cmac_sc_buffer, n1, 16); 1848 (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16); 1849 (void)memcpy(sm_cmac_sc_buffer + 32, r, 16); 1850 (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3); 1851 (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7); 1852 (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7); 1853 } 1854 1855 static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){ 1856 const uint16_t message_len = 65; 1857 sm_cmac_connection = sm_conn; 1858 log_info("f6 key"); 1859 log_info_hexdump(w, 16); 1860 log_info("f6 message"); 1861 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1862 sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1863 } 1864 1865 // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32 1866 // - U is 256 bits 1867 // - V is 256 bits 1868 // - X is 128 bits 1869 // - Y is 128 bits 1870 static void g2_engine(sm_connection_t * sm_conn, const sm_key256_t u, const sm_key256_t v, const sm_key_t x, const sm_key_t y){ 1871 const uint16_t message_len = 80; 1872 sm_cmac_connection = sm_conn; 1873 (void)memcpy(sm_cmac_sc_buffer, u, 32); 1874 (void)memcpy(sm_cmac_sc_buffer + 32, v, 32); 1875 (void)memcpy(sm_cmac_sc_buffer + 64, y, 16); 1876 log_info("g2 key"); 1877 log_info_hexdump(x, 16); 1878 log_info("g2 message"); 1879 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1880 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1881 } 1882 1883 static void g2_calculate(sm_connection_t * sm_conn) { 1884 // calc Va if numeric comparison 1885 if (IS_RESPONDER(sm_conn->sm_role)){ 1886 // responder 1887 g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);; 1888 } else { 1889 // initiator 1890 g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce); 1891 } 1892 } 1893 1894 static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){ 1895 uint8_t z = 0; 1896 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1897 // some form of passkey 1898 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1899 z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u); 1900 setup->sm_passkey_bit++; 1901 } 1902 f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z); 1903 } 1904 1905 static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){ 1906 // OOB 1907 if (setup->sm_stk_generation_method == OOB){ 1908 if (IS_RESPONDER(sm_conn->sm_role)){ 1909 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0); 1910 } else { 1911 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0); 1912 } 1913 return; 1914 } 1915 1916 uint8_t z = 0; 1917 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1918 // some form of passkey 1919 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1920 // sm_passkey_bit was increased before sending confirm value 1921 z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u); 1922 } 1923 f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z); 1924 } 1925 1926 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){ 1927 log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0); 1928 1929 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){ 1930 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1931 return; 1932 } else { 1933 sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY; 1934 } 1935 } 1936 1937 static void sm_sc_dhkey_calculated(void * arg){ 1938 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 1939 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 1940 if (sm_conn == NULL) return; 1941 1942 log_info("dhkey"); 1943 log_info_hexdump(&setup->sm_dhkey[0], 32); 1944 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED; 1945 // trigger next step 1946 if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){ 1947 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1948 } 1949 sm_trigger_run(); 1950 } 1951 1952 static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){ 1953 // calculate DHKCheck 1954 sm_key56_t bd_addr_master, bd_addr_slave; 1955 bd_addr_master[0] = setup->sm_m_addr_type; 1956 bd_addr_slave[0] = setup->sm_s_addr_type; 1957 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1958 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1959 uint8_t iocap_a[3]; 1960 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1961 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1962 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 1963 uint8_t iocap_b[3]; 1964 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 1965 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 1966 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 1967 if (IS_RESPONDER(sm_conn->sm_role)){ 1968 // responder 1969 f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 1970 f6_engine(sm_conn, setup->sm_mackey); 1971 } else { 1972 // initiator 1973 f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 1974 f6_engine(sm_conn, setup->sm_mackey); 1975 } 1976 } 1977 1978 static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){ 1979 // validate E = f6() 1980 sm_key56_t bd_addr_master, bd_addr_slave; 1981 bd_addr_master[0] = setup->sm_m_addr_type; 1982 bd_addr_slave[0] = setup->sm_s_addr_type; 1983 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1984 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1985 1986 uint8_t iocap_a[3]; 1987 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1988 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1989 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 1990 uint8_t iocap_b[3]; 1991 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 1992 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 1993 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 1994 if (IS_RESPONDER(sm_conn->sm_role)){ 1995 // responder 1996 f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 1997 f6_engine(sm_conn, setup->sm_mackey); 1998 } else { 1999 // initiator 2000 f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 2001 f6_engine(sm_conn, setup->sm_mackey); 2002 } 2003 } 2004 2005 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2006 2007 // 2008 // Link Key Conversion Function h6 2009 // 2010 // h6(W, keyID) = AES-CMAC_W(keyID) 2011 // - W is 128 bits 2012 // - keyID is 32 bits 2013 static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){ 2014 const uint16_t message_len = 4; 2015 sm_cmac_connection = sm_conn; 2016 big_endian_store_32(sm_cmac_sc_buffer, 0, key_id); 2017 log_info("h6 key"); 2018 log_info_hexdump(w, 16); 2019 log_info("h6 message"); 2020 log_info_hexdump(sm_cmac_sc_buffer, message_len); 2021 sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 2022 } 2023 // 2024 // Link Key Conversion Function h7 2025 // 2026 // h7(SALT, W) = AES-CMAC_SALT(W) 2027 // - SALT is 128 bits 2028 // - W is 128 bits 2029 static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) { 2030 const uint16_t message_len = 16; 2031 sm_cmac_connection = sm_conn; 2032 log_info("h7 key"); 2033 log_info_hexdump(salt, 16); 2034 log_info("h7 message"); 2035 log_info_hexdump(w, 16); 2036 sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done); 2037 } 2038 2039 // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated) 2040 // Errata Service Release to the Bluetooth Specification: ESR09 2041 // E6405 – Cross transport key derivation from a key of size less than 128 bits 2042 // "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 2043 2044 static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){ 2045 h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031); // "tmp1" 2046 } 2047 2048 static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){ 2049 h6_engine(sm_conn, setup->sm_link_key, 0x746D7032); // "tmp2" 2050 } 2051 2052 static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){ 2053 h6_engine(sm_conn, setup->sm_t, 0x6c656272); // "lebr" 2054 } 2055 2056 static void h6_calculate_le_ltk(sm_connection_t * sm_conn){ 2057 h6_engine(sm_conn, setup->sm_t, 0x62726C65); // "brle" 2058 } 2059 2060 static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){ 2061 const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31}; // "tmp1" 2062 h7_engine(sm_conn, salt, setup->sm_local_ltk); 2063 } 2064 2065 static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){ 2066 const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32}; // "tmp2" 2067 h7_engine(sm_conn, salt, setup->sm_link_key); 2068 } 2069 2070 static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){ 2071 hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle); 2072 btstack_assert(hci_connection != NULL); 2073 reverse_128(hci_connection->link_key, setup->sm_link_key); 2074 setup->sm_link_key_type = hci_connection->link_key_type; 2075 } 2076 2077 static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){ 2078 bool use_h7 = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) & sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_CT2) != 0; 2079 connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6; 2080 } 2081 2082 #endif 2083 2084 #endif 2085 2086 // key management legacy connections: 2087 // - potentially two different LTKs based on direction. each device stores LTK provided by peer 2088 // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect) 2089 // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder 2090 // - responder reconnects: responder uses LTK receveived from master 2091 2092 // key management secure connections: 2093 // - both devices store same LTK from ECDH key exchange. 2094 2095 #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL) 2096 static void sm_load_security_info(sm_connection_t * sm_connection){ 2097 int encryption_key_size; 2098 int authenticated; 2099 int authorized; 2100 int secure_connection; 2101 2102 // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled 2103 le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk, 2104 &encryption_key_size, &authenticated, &authorized, &secure_connection); 2105 log_info("db index %u, key size %u, authenticated %u, authorized %u, secure connetion %u", sm_connection->sm_le_db_index, encryption_key_size, authenticated, authorized, secure_connection); 2106 sm_connection->sm_actual_encryption_key_size = encryption_key_size; 2107 sm_connection->sm_connection_authenticated = authenticated; 2108 sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN; 2109 sm_connection->sm_connection_sc = secure_connection; 2110 } 2111 #endif 2112 2113 #ifdef ENABLE_LE_PERIPHERAL 2114 static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){ 2115 (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8); 2116 setup->sm_local_ediv = sm_connection->sm_local_ediv; 2117 // re-establish used key encryption size 2118 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 2119 sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u; 2120 // no db for authenticated flag hack: flag is stored in bit 4 of LSB 2121 sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u; 2122 // Legacy paring -> not SC 2123 sm_connection->sm_connection_sc = 0; 2124 log_info("sm: received ltk request with key size %u, authenticated %u", 2125 sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated); 2126 } 2127 #endif 2128 2129 // distributed key generation 2130 static bool sm_run_dpkg(void){ 2131 switch (dkg_state){ 2132 case DKG_CALC_IRK: 2133 // already busy? 2134 if (sm_aes128_state == SM_AES128_IDLE) { 2135 log_info("DKG_CALC_IRK started"); 2136 // IRK = d1(IR, 1, 0) 2137 sm_d1_d_prime(1, 0, sm_aes128_plaintext); // plaintext = d1 prime 2138 sm_aes128_state = SM_AES128_ACTIVE; 2139 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_irk, sm_handle_encryption_result_dkg_irk, NULL); 2140 return true; 2141 } 2142 break; 2143 case DKG_CALC_DHK: 2144 // already busy? 2145 if (sm_aes128_state == SM_AES128_IDLE) { 2146 log_info("DKG_CALC_DHK started"); 2147 // DHK = d1(IR, 3, 0) 2148 sm_d1_d_prime(3, 0, sm_aes128_plaintext); // plaintext = d1 prime 2149 sm_aes128_state = SM_AES128_ACTIVE; 2150 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_dhk, sm_handle_encryption_result_dkg_dhk, NULL); 2151 return true; 2152 } 2153 break; 2154 default: 2155 break; 2156 } 2157 return false; 2158 } 2159 2160 // random address updates 2161 static bool sm_run_rau(void){ 2162 switch (rau_state){ 2163 case RAU_GET_RANDOM: 2164 rau_state = RAU_W4_RANDOM; 2165 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL); 2166 return true; 2167 case RAU_GET_ENC: 2168 // already busy? 2169 if (sm_aes128_state == SM_AES128_IDLE) { 2170 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext); 2171 sm_aes128_state = SM_AES128_ACTIVE; 2172 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL); 2173 return true; 2174 } 2175 break; 2176 default: 2177 break; 2178 } 2179 return false; 2180 } 2181 2182 // CSRK Lookup 2183 static bool sm_run_csrk(void){ 2184 btstack_linked_list_iterator_t it; 2185 2186 // -- if csrk lookup ready, find connection that require csrk lookup 2187 if (sm_address_resolution_idle()){ 2188 hci_connections_get_iterator(&it); 2189 while(btstack_linked_list_iterator_has_next(&it)){ 2190 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2191 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2192 if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){ 2193 // and start lookup 2194 sm_address_resolution_start_lookup(sm_connection->sm_peer_addr_type, sm_connection->sm_handle, sm_connection->sm_peer_address, ADDRESS_RESOLUTION_FOR_CONNECTION, sm_connection); 2195 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED; 2196 break; 2197 } 2198 } 2199 } 2200 2201 // -- if csrk lookup ready, resolved addresses for received addresses 2202 if (sm_address_resolution_idle()) { 2203 if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){ 2204 sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue; 2205 btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry); 2206 sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL); 2207 btstack_memory_sm_lookup_entry_free(entry); 2208 } 2209 } 2210 2211 // -- Continue with device lookup by public or resolvable private address 2212 if (!sm_address_resolution_idle()){ 2213 while (sm_address_resolution_test < le_device_db_max_count()){ 2214 int addr_type = BD_ADDR_TYPE_UNKNOWN; 2215 bd_addr_t addr; 2216 sm_key_t irk; 2217 le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk); 2218 2219 // skip unused entries 2220 if (addr_type == BD_ADDR_TYPE_UNKNOWN){ 2221 sm_address_resolution_test++; 2222 continue; 2223 } 2224 2225 log_info("LE Device Lookup: device %u of %u", sm_address_resolution_test, le_device_db_max_count()); 2226 2227 if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){ 2228 log_info("LE Device Lookup: found by { addr_type, address} "); 2229 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED); 2230 break; 2231 } 2232 2233 // if connection type is public, it must be a different one 2234 if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){ 2235 sm_address_resolution_test++; 2236 continue; 2237 } 2238 2239 // skip AH if no IRK 2240 if (sm_is_null_key(irk)){ 2241 sm_address_resolution_test++; 2242 continue; 2243 } 2244 2245 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2246 2247 log_info("LE Device Lookup: calculate AH"); 2248 log_info_key("IRK", irk); 2249 2250 (void)memcpy(sm_aes128_key, irk, 16); 2251 sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext); 2252 sm_aes128_state = SM_AES128_ACTIVE; 2253 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL); 2254 return true; 2255 } 2256 2257 if (sm_address_resolution_test >= le_device_db_max_count()){ 2258 log_info("LE Device Lookup: not found"); 2259 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED); 2260 } 2261 } 2262 return false; 2263 } 2264 2265 // SC OOB 2266 static bool sm_run_oob(void){ 2267 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2268 switch (sm_sc_oob_state){ 2269 case SM_SC_OOB_W2_CALC_CONFIRM: 2270 if (!sm_cmac_ready()) break; 2271 sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM; 2272 f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0); 2273 return true; 2274 default: 2275 break; 2276 } 2277 #endif 2278 return false; 2279 } 2280 2281 static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){ 2282 l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size); 2283 } 2284 2285 // handle basic actions that don't requires the full context 2286 static bool sm_run_basic(void){ 2287 btstack_linked_list_iterator_t it; 2288 hci_connections_get_iterator(&it); 2289 while(btstack_linked_list_iterator_has_next(&it)){ 2290 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2291 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2292 switch(sm_connection->sm_engine_state){ 2293 2294 // general 2295 case SM_GENERAL_SEND_PAIRING_FAILED: { 2296 uint8_t buffer[2]; 2297 buffer[0] = SM_CODE_PAIRING_FAILED; 2298 buffer[1] = sm_connection->sm_pairing_failed_reason; 2299 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 2300 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer)); 2301 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason); 2302 sm_done_for_handle(sm_connection->sm_handle); 2303 break; 2304 } 2305 2306 // responder side 2307 case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY: 2308 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 2309 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 2310 return true; 2311 2312 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2313 case SM_SC_RECEIVED_LTK_REQUEST: 2314 switch (sm_connection->sm_irk_lookup_state){ 2315 case IRK_LOOKUP_FAILED: 2316 log_info("LTK Request: IRK Lookup Failed)"); 2317 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 2318 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 2319 return true; 2320 default: 2321 break; 2322 } 2323 break; 2324 #endif 2325 default: 2326 break; 2327 } 2328 } 2329 return false; 2330 } 2331 2332 static void sm_run_activate_connection(void){ 2333 // Find connections that requires setup context and make active if no other is locked 2334 btstack_linked_list_iterator_t it; 2335 hci_connections_get_iterator(&it); 2336 while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){ 2337 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2338 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2339 // - if no connection locked and we're ready/waiting for setup context, fetch it and start 2340 bool done = true; 2341 int err; 2342 UNUSED(err); 2343 2344 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2345 // assert ec key is ready 2346 if ( (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED) 2347 || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST) 2348 || (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){ 2349 if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){ 2350 sm_ec_generate_new_key(); 2351 } 2352 if (ec_key_generation_state != EC_KEY_GENERATION_DONE){ 2353 continue; 2354 } 2355 } 2356 #endif 2357 2358 switch (sm_connection->sm_engine_state) { 2359 #ifdef ENABLE_LE_PERIPHERAL 2360 case SM_RESPONDER_SEND_SECURITY_REQUEST: 2361 case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED: 2362 case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST: 2363 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2364 case SM_SC_RECEIVED_LTK_REQUEST: 2365 #endif 2366 #endif 2367 #ifdef ENABLE_LE_CENTRAL 2368 case SM_INITIATOR_PH4_HAS_LTK: 2369 case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST: 2370 #endif 2371 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2372 case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED: 2373 case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST: 2374 #endif 2375 // just lock context 2376 break; 2377 default: 2378 done = false; 2379 break; 2380 } 2381 if (done){ 2382 sm_active_connection_handle = sm_connection->sm_handle; 2383 log_info("sm: connection 0x%04x locked setup context as %s, state %u", sm_active_connection_handle, sm_connection->sm_role ? "responder" : "initiator", sm_connection->sm_engine_state); 2384 } 2385 } 2386 } 2387 2388 static void sm_run_send_keypress_notification(sm_connection_t * connection){ 2389 int i; 2390 uint8_t flags = setup->sm_keypress_notification & 0x1fu; 2391 uint8_t num_actions = setup->sm_keypress_notification >> 5; 2392 uint8_t action = 0; 2393 for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){ 2394 if (flags & (1u<<i)){ 2395 bool clear_flag = true; 2396 switch (i){ 2397 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 2398 case SM_KEYPRESS_PASSKEY_CLEARED: 2399 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 2400 default: 2401 break; 2402 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 2403 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 2404 num_actions--; 2405 clear_flag = num_actions == 0u; 2406 break; 2407 } 2408 if (clear_flag){ 2409 flags &= ~(1<<i); 2410 } 2411 action = i; 2412 break; 2413 } 2414 } 2415 setup->sm_keypress_notification = (num_actions << 5) | flags; 2416 2417 // send keypress notification 2418 uint8_t buffer[2]; 2419 buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION; 2420 buffer[1] = action; 2421 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2422 2423 // try 2424 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid); 2425 } 2426 2427 static void sm_run_distribute_keys(sm_connection_t * connection){ 2428 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){ 2429 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2430 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2431 uint8_t buffer[17]; 2432 buffer[0] = SM_CODE_ENCRYPTION_INFORMATION; 2433 reverse_128(setup->sm_ltk, &buffer[1]); 2434 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2435 sm_timeout_reset(connection); 2436 return; 2437 } 2438 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){ 2439 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2440 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2441 uint8_t buffer[11]; 2442 buffer[0] = SM_CODE_MASTER_IDENTIFICATION; 2443 little_endian_store_16(buffer, 1, setup->sm_local_ediv); 2444 reverse_64(setup->sm_local_rand, &buffer[3]); 2445 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2446 sm_timeout_reset(connection); 2447 return; 2448 } 2449 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 2450 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2451 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2452 uint8_t buffer[17]; 2453 buffer[0] = SM_CODE_IDENTITY_INFORMATION; 2454 reverse_128(sm_persistent_irk, &buffer[1]); 2455 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2456 sm_timeout_reset(connection); 2457 return; 2458 } 2459 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){ 2460 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2461 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2462 bd_addr_t local_address; 2463 uint8_t buffer[8]; 2464 buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION; 2465 switch (gap_random_address_get_mode()){ 2466 case GAP_RANDOM_ADDRESS_TYPE_OFF: 2467 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 2468 // public or static random 2469 gap_le_get_own_address(&buffer[1], local_address); 2470 break; 2471 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 2472 case GAP_RANDOM_ADDRESS_RESOLVABLE: 2473 // fallback to public 2474 gap_local_bd_addr(local_address); 2475 buffer[1] = 0; 2476 break; 2477 default: 2478 btstack_assert(false); 2479 break; 2480 } 2481 reverse_bd_addr(local_address, &buffer[2]); 2482 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2483 sm_timeout_reset(connection); 2484 return; 2485 } 2486 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 2487 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2488 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2489 2490 #ifdef ENABLE_LE_SIGNED_WRITE 2491 // hack to reproduce test runs 2492 if (test_use_fixed_local_csrk){ 2493 memset(setup->sm_local_csrk, 0xcc, 16); 2494 } 2495 2496 // store local CSRK 2497 if (setup->sm_le_device_index >= 0){ 2498 log_info("sm: store local CSRK"); 2499 le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk); 2500 le_device_db_local_counter_set(setup->sm_le_device_index, 0); 2501 } 2502 #endif 2503 2504 uint8_t buffer[17]; 2505 buffer[0] = SM_CODE_SIGNING_INFORMATION; 2506 reverse_128(setup->sm_local_csrk, &buffer[1]); 2507 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2508 sm_timeout_reset(connection); 2509 return; 2510 } 2511 btstack_assert(false); 2512 } 2513 2514 static bool sm_ctkd_from_le(sm_connection_t *sm_connection) { 2515 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2516 // requirements to derive link key from LE: 2517 // - use secure connections 2518 if (setup->sm_use_secure_connections == 0) return false; 2519 // - bonding needs to be enabled: 2520 bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) & sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_BONDING ) != 0u; 2521 if (!bonding_enabled) return false; 2522 // - need identity address / public addr 2523 bool have_identity_address_info = ((setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION) != 0) || (setup->sm_peer_addr_type == 0); 2524 if (!have_identity_address_info) return false; 2525 // - there is no stored BR/EDR link key or the derived key has at least the same level of authentication (bail if stored key has higher authentication) 2526 // this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all. 2527 // If SC is authenticated, we consider it safe to overwrite a stored key. 2528 // If stored link key is not authenticated, it could already be compromised by a MITM attack. Allowing overwrite by unauthenticated derived key does not make it worse. 2529 uint8_t link_key[16]; 2530 link_key_type_t link_key_type; 2531 bool have_link_key = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type); 2532 bool link_key_authenticated = gap_authenticated_for_link_key_type(link_key_type); 2533 bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0; 2534 if (have_link_key && link_key_authenticated && !derived_key_authenticated) { 2535 return false; 2536 } 2537 // get started (all of the above are true) 2538 return true; 2539 #else 2540 UNUSED(sm_connection); 2541 return false; 2542 #endif 2543 } 2544 2545 static void sm_key_distribution_complete_responder(sm_connection_t * connection){ 2546 if (sm_ctkd_from_le(connection)){ 2547 bool use_h7 = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) & sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_CT2) != 0; 2548 connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6; 2549 } else { 2550 connection->sm_engine_state = SM_RESPONDER_IDLE; 2551 sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0); 2552 sm_done_for_handle(connection->sm_handle); 2553 } 2554 } 2555 2556 static void sm_key_distribution_complete_initiator(sm_connection_t * connection){ 2557 if (sm_ctkd_from_le(connection)){ 2558 bool use_h7 = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) & sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_CT2) != 0; 2559 connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6; 2560 } else { 2561 sm_master_pairing_success(connection); 2562 } 2563 } 2564 2565 static void sm_run(void){ 2566 2567 // assert that stack has already bootet 2568 if (hci_get_state() != HCI_STATE_WORKING) return; 2569 2570 // assert that we can send at least commands 2571 if (!hci_can_send_command_packet_now()) return; 2572 2573 // pause until IR/ER are ready 2574 if (sm_persistent_keys_random_active) return; 2575 2576 bool done; 2577 2578 // 2579 // non-connection related behaviour 2580 // 2581 2582 done = sm_run_dpkg(); 2583 if (done) return; 2584 2585 done = sm_run_rau(); 2586 if (done) return; 2587 2588 done = sm_run_csrk(); 2589 if (done) return; 2590 2591 done = sm_run_oob(); 2592 if (done) return; 2593 2594 // assert that we can send at least commands - cmd might have been sent by crypto engine 2595 if (!hci_can_send_command_packet_now()) return; 2596 2597 // handle basic actions that don't requires the full context 2598 done = sm_run_basic(); 2599 if (done) return; 2600 2601 // 2602 // active connection handling 2603 // -- use loop to handle next connection if lock on setup context is released 2604 2605 while (true) { 2606 2607 sm_run_activate_connection(); 2608 2609 if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return; 2610 2611 // 2612 // active connection handling 2613 // 2614 2615 sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle); 2616 if (!connection) { 2617 log_info("no connection for handle 0x%04x", sm_active_connection_handle); 2618 return; 2619 } 2620 2621 // assert that we could send a SM PDU - not needed for all of the following 2622 if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) { 2623 log_info("cannot send now, requesting can send now event"); 2624 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid); 2625 return; 2626 } 2627 2628 // send keypress notifications 2629 if (setup->sm_keypress_notification){ 2630 sm_run_send_keypress_notification(connection); 2631 return; 2632 } 2633 2634 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2635 // assert that sm cmac engine is ready 2636 if (sm_cmac_ready() == false){ 2637 break; 2638 } 2639 #endif 2640 2641 int key_distribution_flags; 2642 UNUSED(key_distribution_flags); 2643 #ifdef ENABLE_LE_PERIPHERAL 2644 int err; 2645 bool have_ltk; 2646 uint8_t ltk[16]; 2647 #endif 2648 2649 log_info("sm_run: state %u", connection->sm_engine_state); 2650 switch (connection->sm_engine_state){ 2651 2652 // secure connections, initiator + responding states 2653 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2654 case SM_SC_W2_CMAC_FOR_CONFIRMATION: 2655 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION; 2656 sm_sc_calculate_local_confirm(connection); 2657 break; 2658 case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION: 2659 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION; 2660 sm_sc_calculate_remote_confirm(connection); 2661 break; 2662 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 2663 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK; 2664 sm_sc_calculate_f6_for_dhkey_check(connection); 2665 break; 2666 case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 2667 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 2668 sm_sc_calculate_f6_to_verify_dhkey_check(connection); 2669 break; 2670 case SM_SC_W2_CALCULATE_F5_SALT: 2671 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT; 2672 f5_calculate_salt(connection); 2673 break; 2674 case SM_SC_W2_CALCULATE_F5_MACKEY: 2675 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY; 2676 f5_calculate_mackey(connection); 2677 break; 2678 case SM_SC_W2_CALCULATE_F5_LTK: 2679 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK; 2680 f5_calculate_ltk(connection); 2681 break; 2682 case SM_SC_W2_CALCULATE_G2: 2683 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2; 2684 g2_calculate(connection); 2685 break; 2686 #endif 2687 2688 #ifdef ENABLE_LE_CENTRAL 2689 // initiator side 2690 2691 case SM_INITIATOR_PH4_HAS_LTK: { 2692 sm_reset_setup(); 2693 sm_load_security_info(connection); 2694 2695 sm_key_t peer_ltk_flipped; 2696 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped); 2697 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED; 2698 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv); 2699 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0); 2700 uint32_t rand_low = big_endian_read_32(setup->sm_peer_rand, 4); 2701 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped); 2702 2703 // notify after sending 2704 sm_reencryption_started(connection); 2705 return; 2706 } 2707 2708 case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST: 2709 sm_reset_setup(); 2710 sm_init_setup(connection); 2711 2712 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST); 2713 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE; 2714 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t)); 2715 sm_timeout_reset(connection); 2716 2717 // notify after sending 2718 sm_pairing_started(connection); 2719 break; 2720 #endif 2721 2722 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2723 2724 case SM_SC_SEND_PUBLIC_KEY_COMMAND: { 2725 bool trigger_user_response = false; 2726 bool trigger_start_calculating_local_confirm = false; 2727 uint8_t buffer[65]; 2728 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY; 2729 // 2730 reverse_256(&ec_q[0], &buffer[1]); 2731 reverse_256(&ec_q[32], &buffer[33]); 2732 2733 #ifdef ENABLE_TESTING_SUPPORT 2734 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){ 2735 log_info("testing_support: invalidating public key"); 2736 // flip single bit of public key coordinate 2737 buffer[1] ^= 1; 2738 } 2739 #endif 2740 2741 // stk generation method 2742 // passkey entry: notify app to show passkey or to request passkey 2743 switch (setup->sm_stk_generation_method){ 2744 case JUST_WORKS: 2745 case NUMERIC_COMPARISON: 2746 if (IS_RESPONDER(connection->sm_role)){ 2747 // responder 2748 trigger_start_calculating_local_confirm = true; 2749 connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE; 2750 } else { 2751 // initiator 2752 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2753 } 2754 break; 2755 case PK_INIT_INPUT: 2756 case PK_RESP_INPUT: 2757 case PK_BOTH_INPUT: 2758 // use random TK for display 2759 (void)memcpy(setup->sm_ra, setup->sm_tk, 16); 2760 (void)memcpy(setup->sm_rb, setup->sm_tk, 16); 2761 setup->sm_passkey_bit = 0; 2762 2763 if (IS_RESPONDER(connection->sm_role)){ 2764 // responder 2765 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2766 } else { 2767 // initiator 2768 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2769 } 2770 trigger_user_response = true; 2771 break; 2772 case OOB: 2773 if (IS_RESPONDER(connection->sm_role)){ 2774 // responder 2775 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2776 } else { 2777 // initiator 2778 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2779 } 2780 break; 2781 default: 2782 btstack_assert(false); 2783 break; 2784 } 2785 2786 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2787 sm_timeout_reset(connection); 2788 2789 // trigger user response and calc confirm after sending pdu 2790 if (trigger_user_response){ 2791 sm_trigger_user_response(connection); 2792 } 2793 if (trigger_start_calculating_local_confirm){ 2794 sm_sc_start_calculating_local_confirm(connection); 2795 } 2796 break; 2797 } 2798 case SM_SC_SEND_CONFIRMATION: { 2799 uint8_t buffer[17]; 2800 buffer[0] = SM_CODE_PAIRING_CONFIRM; 2801 reverse_128(setup->sm_local_confirm, &buffer[1]); 2802 if (IS_RESPONDER(connection->sm_role)){ 2803 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2804 } else { 2805 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2806 } 2807 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2808 sm_timeout_reset(connection); 2809 break; 2810 } 2811 case SM_SC_SEND_PAIRING_RANDOM: { 2812 uint8_t buffer[17]; 2813 buffer[0] = SM_CODE_PAIRING_RANDOM; 2814 reverse_128(setup->sm_local_nonce, &buffer[1]); 2815 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit); 2816 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){ 2817 log_info("SM_SC_SEND_PAIRING_RANDOM A"); 2818 if (IS_RESPONDER(connection->sm_role)){ 2819 // responder 2820 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2821 } else { 2822 // initiator 2823 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2824 } 2825 } else { 2826 log_info("SM_SC_SEND_PAIRING_RANDOM B"); 2827 if (IS_RESPONDER(connection->sm_role)){ 2828 // responder 2829 if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){ 2830 log_info("SM_SC_SEND_PAIRING_RANDOM B1"); 2831 connection->sm_engine_state = SM_SC_W2_CALCULATE_G2; 2832 } else { 2833 log_info("SM_SC_SEND_PAIRING_RANDOM B2"); 2834 sm_sc_prepare_dhkey_check(connection); 2835 } 2836 } else { 2837 // initiator 2838 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2839 } 2840 } 2841 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2842 sm_timeout_reset(connection); 2843 break; 2844 } 2845 case SM_SC_SEND_DHKEY_CHECK_COMMAND: { 2846 uint8_t buffer[17]; 2847 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK; 2848 reverse_128(setup->sm_local_dhkey_check, &buffer[1]); 2849 2850 if (IS_RESPONDER(connection->sm_role)){ 2851 connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC; 2852 } else { 2853 connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 2854 } 2855 2856 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2857 sm_timeout_reset(connection); 2858 break; 2859 } 2860 2861 #endif 2862 2863 #ifdef ENABLE_LE_PERIPHERAL 2864 2865 case SM_RESPONDER_SEND_SECURITY_REQUEST: { 2866 const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req}; 2867 connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST; 2868 sm_send_connectionless(connection, (uint8_t *) buffer, sizeof(buffer)); 2869 sm_timeout_start(connection); 2870 break; 2871 } 2872 2873 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2874 case SM_SC_RECEIVED_LTK_REQUEST: 2875 switch (connection->sm_irk_lookup_state){ 2876 case IRK_LOOKUP_SUCCEEDED: 2877 // assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null 2878 // start using context by loading security info 2879 sm_reset_setup(); 2880 sm_load_security_info(connection); 2881 if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){ 2882 (void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16); 2883 connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 2884 sm_reencryption_started(connection); 2885 sm_trigger_run(); 2886 break; 2887 } 2888 log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)"); 2889 connection->sm_engine_state = SM_RESPONDER_IDLE; 2890 hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle); 2891 return; 2892 default: 2893 // just wait until IRK lookup is completed 2894 break; 2895 } 2896 break; 2897 #endif /* ENABLE_LE_SECURE_CONNECTIONS */ 2898 2899 case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED: 2900 sm_reset_setup(); 2901 2902 // handle Pairing Request with LTK available 2903 switch (connection->sm_irk_lookup_state) { 2904 case IRK_LOOKUP_SUCCEEDED: 2905 le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 2906 have_ltk = !sm_is_null_key(ltk); 2907 if (have_ltk){ 2908 log_info("pairing request but LTK available"); 2909 // emit re-encryption start/fail sequence 2910 sm_reencryption_started(connection); 2911 sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING); 2912 } 2913 break; 2914 default: 2915 break; 2916 } 2917 2918 sm_init_setup(connection); 2919 2920 // recover pairing request 2921 (void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t)); 2922 err = sm_stk_generation_init(connection); 2923 2924 #ifdef ENABLE_TESTING_SUPPORT 2925 if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){ 2926 log_info("testing_support: respond with pairing failure %u", test_pairing_failure); 2927 err = test_pairing_failure; 2928 } 2929 #endif 2930 if (err != 0){ 2931 // emit pairing started/failed sequence 2932 sm_pairing_started(connection); 2933 sm_pairing_error(connection, err); 2934 sm_trigger_run(); 2935 break; 2936 } 2937 2938 sm_timeout_start(connection); 2939 2940 // generate random number first, if we need to show passkey, otherwise send response 2941 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 2942 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph2_tk, (void *)(uintptr_t) connection->sm_handle); 2943 break; 2944 } 2945 2946 /* fall through */ 2947 2948 case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE: 2949 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE); 2950 2951 // start with initiator key dist flags 2952 key_distribution_flags = sm_key_distribution_flags_for_auth_req(); 2953 2954 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2955 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection 2956 if (setup->sm_use_secure_connections){ 2957 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY; 2958 } 2959 #endif 2960 // setup in response 2961 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq) & key_distribution_flags); 2962 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq) & key_distribution_flags); 2963 2964 // update key distribution after ENC was dropped 2965 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres), sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres)); 2966 2967 if (setup->sm_use_secure_connections){ 2968 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2969 } else { 2970 connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM; 2971 } 2972 2973 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t)); 2974 sm_timeout_reset(connection); 2975 2976 // notify after sending 2977 sm_pairing_started(connection); 2978 2979 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 2980 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){ 2981 sm_trigger_user_response(connection); 2982 } 2983 return; 2984 #endif 2985 2986 case SM_PH2_SEND_PAIRING_RANDOM: { 2987 uint8_t buffer[17]; 2988 buffer[0] = SM_CODE_PAIRING_RANDOM; 2989 reverse_128(setup->sm_local_random, &buffer[1]); 2990 if (IS_RESPONDER(connection->sm_role)){ 2991 connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST; 2992 } else { 2993 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM; 2994 } 2995 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2996 sm_timeout_reset(connection); 2997 break; 2998 } 2999 3000 case SM_PH2_C1_GET_ENC_A: 3001 // already busy? 3002 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3003 // calculate confirm using aes128 engine - step 1 3004 sm_c1_t1(setup->sm_local_random, (uint8_t*) &setup->sm_m_preq, (uint8_t*) &setup->sm_s_pres, setup->sm_m_addr_type, setup->sm_s_addr_type, sm_aes128_plaintext); 3005 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A; 3006 sm_aes128_state = SM_AES128_ACTIVE; 3007 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_a, (void *)(uintptr_t) connection->sm_handle); 3008 break; 3009 3010 case SM_PH2_C1_GET_ENC_C: 3011 // already busy? 3012 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3013 // calculate m_confirm using aes128 engine - step 1 3014 sm_c1_t1(setup->sm_peer_random, (uint8_t*) &setup->sm_m_preq, (uint8_t*) &setup->sm_s_pres, setup->sm_m_addr_type, setup->sm_s_addr_type, sm_aes128_plaintext); 3015 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C; 3016 sm_aes128_state = SM_AES128_ACTIVE; 3017 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_c, (void *)(uintptr_t) connection->sm_handle); 3018 break; 3019 3020 case SM_PH2_CALC_STK: 3021 // already busy? 3022 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3023 // calculate STK 3024 if (IS_RESPONDER(connection->sm_role)){ 3025 sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext); 3026 } else { 3027 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 3028 } 3029 connection->sm_engine_state = SM_PH2_W4_STK; 3030 sm_aes128_state = SM_AES128_ACTIVE; 3031 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_stk, (void *)(uintptr_t) connection->sm_handle); 3032 break; 3033 3034 case SM_PH3_Y_GET_ENC: 3035 // already busy? 3036 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3037 // PH3B2 - calculate Y from - enc 3038 3039 // dm helper (was sm_dm_r_prime) 3040 // r' = padding || r 3041 // r - 64 bit value 3042 memset(&sm_aes128_plaintext[0], 0, 8); 3043 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 3044 3045 // Y = dm(DHK, Rand) 3046 connection->sm_engine_state = SM_PH3_Y_W4_ENC; 3047 sm_aes128_state = SM_AES128_ACTIVE; 3048 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_dhk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_ph3_y, (void *)(uintptr_t) connection->sm_handle); 3049 break; 3050 3051 case SM_PH2_C1_SEND_PAIRING_CONFIRM: { 3052 uint8_t buffer[17]; 3053 buffer[0] = SM_CODE_PAIRING_CONFIRM; 3054 reverse_128(setup->sm_local_confirm, &buffer[1]); 3055 if (IS_RESPONDER(connection->sm_role)){ 3056 connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM; 3057 } else { 3058 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM; 3059 } 3060 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 3061 sm_timeout_reset(connection); 3062 return; 3063 } 3064 #ifdef ENABLE_LE_PERIPHERAL 3065 case SM_RESPONDER_PH2_SEND_LTK_REPLY: { 3066 // cache key before using 3067 sm_cache_ltk(connection, setup->sm_ltk); 3068 sm_key_t stk_flipped; 3069 reverse_128(setup->sm_ltk, stk_flipped); 3070 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 3071 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped); 3072 return; 3073 } 3074 case SM_RESPONDER_PH4_SEND_LTK_REPLY: { 3075 // allow to override LTK 3076 if (sm_get_ltk_callback != NULL){ 3077 (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk); 3078 } 3079 // cache key before using 3080 sm_cache_ltk(connection, setup->sm_ltk); 3081 sm_key_t ltk_flipped; 3082 reverse_128(setup->sm_ltk, ltk_flipped); 3083 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED; 3084 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped); 3085 return; 3086 } 3087 3088 case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST: 3089 // already busy? 3090 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3091 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv); 3092 3093 sm_reset_setup(); 3094 sm_start_calculating_ltk_from_ediv_and_rand(connection); 3095 3096 sm_reencryption_started(connection); 3097 3098 // dm helper (was sm_dm_r_prime) 3099 // r' = padding || r 3100 // r - 64 bit value 3101 memset(&sm_aes128_plaintext[0], 0, 8); 3102 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 3103 3104 // Y = dm(DHK, Rand) 3105 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC; 3106 sm_aes128_state = SM_AES128_ACTIVE; 3107 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_dhk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_enc_ph4_y, (void *)(uintptr_t) connection->sm_handle); 3108 return; 3109 #endif 3110 #ifdef ENABLE_LE_CENTRAL 3111 case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: { 3112 sm_key_t stk_flipped; 3113 reverse_128(setup->sm_ltk, stk_flipped); 3114 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 3115 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped); 3116 return; 3117 } 3118 #endif 3119 3120 case SM_PH3_DISTRIBUTE_KEYS: 3121 // send next key 3122 if (setup->sm_key_distribution_send_set != 0){ 3123 sm_run_distribute_keys(connection); 3124 } 3125 3126 // more to send? 3127 if (setup->sm_key_distribution_send_set != 0){ 3128 return; 3129 } 3130 3131 // keys are sent 3132 if (IS_RESPONDER(connection->sm_role)){ 3133 // slave -> receive master keys if any 3134 if (sm_key_distribution_all_received()){ 3135 sm_key_distribution_handle_all_received(connection); 3136 sm_key_distribution_complete_responder(connection); 3137 // start CTKD right away 3138 continue; 3139 } else { 3140 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3141 } 3142 } else { 3143 sm_master_pairing_success(connection); 3144 } 3145 break; 3146 3147 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3148 case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST: 3149 // fill in sm setup (lite version of sm_init_setup) 3150 sm_reset_setup(); 3151 setup->sm_peer_addr_type = connection->sm_peer_addr_type; 3152 setup->sm_m_addr_type = connection->sm_peer_addr_type; 3153 setup->sm_s_addr_type = connection->sm_own_addr_type; 3154 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6); 3155 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6); 3156 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6); 3157 setup->sm_use_secure_connections = true; 3158 sm_ctkd_fetch_br_edr_link_key(connection); 3159 3160 // Enc Key and IRK if requested 3161 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY; 3162 #ifdef ENABLE_LE_SIGNED_WRITE 3163 // Plus signing key if supported 3164 key_distribution_flags |= SM_KEYDIST_ID_KEY; 3165 #endif 3166 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST); 3167 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0); 3168 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0); 3169 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2); 3170 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size); 3171 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags); 3172 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags); 3173 3174 // set state and send pairing response 3175 sm_timeout_start(connection); 3176 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE; 3177 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t)); 3178 break; 3179 3180 case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED: 3181 // fill in sm setup (lite version of sm_init_setup) 3182 sm_reset_setup(); 3183 setup->sm_peer_addr_type = connection->sm_peer_addr_type; 3184 setup->sm_m_addr_type = connection->sm_peer_addr_type; 3185 setup->sm_s_addr_type = connection->sm_own_addr_type; 3186 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6); 3187 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6); 3188 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6); 3189 setup->sm_use_secure_connections = true; 3190 sm_ctkd_fetch_br_edr_link_key(connection); 3191 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t)); 3192 3193 // Enc Key and IRK if requested 3194 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY; 3195 #ifdef ENABLE_LE_SIGNED_WRITE 3196 // Plus signing key if supported 3197 key_distribution_flags |= SM_KEYDIST_ID_KEY; 3198 #endif 3199 // drop flags not requested by initiator 3200 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq); 3201 3202 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use: 3203 // - the IO Capability field, 3204 // - the OOB data flag field, and 3205 // - all bits in the Auth Req field except the CT2 bit. 3206 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE); 3207 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0); 3208 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0); 3209 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2); 3210 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size); 3211 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags); 3212 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags); 3213 3214 // configure key distribution, LTK is derived locally 3215 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY; 3216 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags); 3217 3218 // set state and send pairing response 3219 sm_timeout_start(connection); 3220 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 3221 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t)); 3222 break; 3223 case SM_BR_EDR_DISTRIBUTE_KEYS: 3224 if (setup->sm_key_distribution_send_set != 0) { 3225 sm_run_distribute_keys(connection); 3226 return; 3227 } 3228 // keys are sent 3229 if (IS_RESPONDER(connection->sm_role)) { 3230 // responder -> receive master keys if there are any 3231 if (!sm_key_distribution_all_received()){ 3232 connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS; 3233 break; 3234 } 3235 } 3236 // otherwise start CTKD right away (responder and no keys to receive / initiator) 3237 sm_ctkd_start_from_br_edr(connection); 3238 continue; 3239 case SM_SC_W2_CALCULATE_ILK_USING_H6: 3240 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK; 3241 h6_calculate_ilk_from_le_ltk(connection); 3242 break; 3243 case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY: 3244 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY; 3245 h6_calculate_br_edr_link_key(connection); 3246 break; 3247 case SM_SC_W2_CALCULATE_ILK_USING_H7: 3248 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK; 3249 h7_calculate_ilk_from_le_ltk(connection); 3250 break; 3251 case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6: 3252 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK; 3253 h6_calculate_ilk_from_br_edr(connection); 3254 break; 3255 case SM_BR_EDR_W2_CALCULATE_LE_LTK: 3256 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK; 3257 h6_calculate_le_ltk(connection); 3258 break; 3259 case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7: 3260 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK; 3261 h7_calculate_ilk_from_br_edr(connection); 3262 break; 3263 #endif 3264 3265 default: 3266 break; 3267 } 3268 3269 // check again if active connection was released 3270 if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break; 3271 } 3272 } 3273 3274 // sm_aes128_state stays active 3275 static void sm_handle_encryption_result_enc_a(void *arg){ 3276 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3277 sm_aes128_state = SM_AES128_IDLE; 3278 3279 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3280 if (connection == NULL) return; 3281 3282 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 3283 sm_aes128_state = SM_AES128_ACTIVE; 3284 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, setup->sm_c1_t3_value, setup->sm_local_confirm, sm_handle_encryption_result_enc_b, (void *)(uintptr_t) connection->sm_handle); 3285 } 3286 3287 static void sm_handle_encryption_result_enc_b(void *arg){ 3288 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3289 sm_aes128_state = SM_AES128_IDLE; 3290 3291 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3292 if (connection == NULL) return; 3293 3294 log_info_key("c1!", setup->sm_local_confirm); 3295 connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM; 3296 sm_trigger_run(); 3297 } 3298 3299 // sm_aes128_state stays active 3300 static void sm_handle_encryption_result_enc_c(void *arg){ 3301 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3302 sm_aes128_state = SM_AES128_IDLE; 3303 3304 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3305 if (connection == NULL) return; 3306 3307 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 3308 sm_aes128_state = SM_AES128_ACTIVE; 3309 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, setup->sm_c1_t3_value, sm_aes128_ciphertext, sm_handle_encryption_result_enc_d, (void *)(uintptr_t) connection->sm_handle); 3310 } 3311 3312 static void sm_handle_encryption_result_enc_d(void * arg){ 3313 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3314 sm_aes128_state = SM_AES128_IDLE; 3315 3316 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3317 if (connection == NULL) return; 3318 3319 log_info_key("c1!", sm_aes128_ciphertext); 3320 if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){ 3321 sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED); 3322 sm_trigger_run(); 3323 return; 3324 } 3325 if (IS_RESPONDER(connection->sm_role)){ 3326 connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 3327 sm_trigger_run(); 3328 } else { 3329 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 3330 sm_aes128_state = SM_AES128_ACTIVE; 3331 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, setup->sm_tk, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_stk, (void *)(uintptr_t) connection->sm_handle); 3332 } 3333 } 3334 3335 static void sm_handle_encryption_result_enc_stk(void *arg){ 3336 sm_aes128_state = SM_AES128_IDLE; 3337 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3338 3339 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3340 if (connection == NULL) return; 3341 3342 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 3343 log_info_key("stk", setup->sm_ltk); 3344 if (IS_RESPONDER(connection->sm_role)){ 3345 connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 3346 } else { 3347 connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 3348 } 3349 sm_trigger_run(); 3350 } 3351 3352 // sm_aes128_state stays active 3353 static void sm_handle_encryption_result_enc_ph3_y(void *arg){ 3354 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3355 sm_aes128_state = SM_AES128_IDLE; 3356 3357 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3358 if (connection == NULL) return; 3359 3360 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 3361 log_info_hex16("y", setup->sm_local_y); 3362 // PH3B3 - calculate EDIV 3363 setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div; 3364 log_info_hex16("ediv", setup->sm_local_ediv); 3365 // PH3B4 - calculate LTK - enc 3366 // LTK = d1(ER, DIV, 0)) 3367 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 3368 sm_aes128_state = SM_AES128_ACTIVE; 3369 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph3_ltk, (void *)(uintptr_t) connection->sm_handle); 3370 } 3371 3372 #ifdef ENABLE_LE_PERIPHERAL 3373 // sm_aes128_state stays active 3374 static void sm_handle_encryption_result_enc_ph4_y(void *arg){ 3375 sm_aes128_state = SM_AES128_IDLE; 3376 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3377 3378 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3379 if (connection == NULL) return; 3380 3381 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 3382 log_info_hex16("y", setup->sm_local_y); 3383 3384 // PH3B3 - calculate DIV 3385 setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv; 3386 log_info_hex16("ediv", setup->sm_local_ediv); 3387 // PH3B4 - calculate LTK - enc 3388 // LTK = d1(ER, DIV, 0)) 3389 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 3390 sm_aes128_state = SM_AES128_ACTIVE; 3391 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph4_ltk, (void *)(uintptr_t) connection->sm_handle); 3392 } 3393 #endif 3394 3395 // sm_aes128_state stays active 3396 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){ 3397 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3398 sm_aes128_state = SM_AES128_IDLE; 3399 3400 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3401 if (connection == NULL) return; 3402 3403 log_info_key("ltk", setup->sm_ltk); 3404 // calc CSRK next 3405 sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext); 3406 sm_aes128_state = SM_AES128_ACTIVE; 3407 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_local_csrk, sm_handle_encryption_result_enc_csrk, (void *)(uintptr_t) connection->sm_handle); 3408 } 3409 3410 static void sm_handle_encryption_result_enc_csrk(void *arg){ 3411 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3412 sm_aes128_state = SM_AES128_IDLE; 3413 3414 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3415 if (connection == NULL) return; 3416 3417 sm_aes128_state = SM_AES128_IDLE; 3418 log_info_key("csrk", setup->sm_local_csrk); 3419 if (setup->sm_key_distribution_send_set){ 3420 connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3421 } else { 3422 // no keys to send, just continue 3423 if (IS_RESPONDER(connection->sm_role)){ 3424 if (sm_key_distribution_all_received()){ 3425 sm_key_distribution_handle_all_received(connection); 3426 sm_key_distribution_complete_responder(connection); 3427 } else { 3428 // slave -> receive master keys 3429 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3430 } 3431 } else { 3432 sm_key_distribution_complete_initiator(connection); 3433 } 3434 } 3435 sm_trigger_run(); 3436 } 3437 3438 #ifdef ENABLE_LE_PERIPHERAL 3439 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){ 3440 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3441 sm_aes128_state = SM_AES128_IDLE; 3442 3443 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3444 if (connection == NULL) return; 3445 3446 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 3447 log_info_key("ltk", setup->sm_ltk); 3448 connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 3449 sm_trigger_run(); 3450 } 3451 #endif 3452 3453 static void sm_handle_encryption_result_address_resolution(void *arg){ 3454 UNUSED(arg); 3455 sm_aes128_state = SM_AES128_IDLE; 3456 3457 // compare calulated address against connecting device 3458 uint8_t * hash = &sm_aes128_ciphertext[13]; 3459 if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){ 3460 log_info("LE Device Lookup: matched resolvable private address"); 3461 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED); 3462 sm_trigger_run(); 3463 return; 3464 } 3465 // no match, try next 3466 sm_address_resolution_test++; 3467 sm_trigger_run(); 3468 } 3469 3470 static void sm_handle_encryption_result_dkg_irk(void *arg){ 3471 UNUSED(arg); 3472 sm_aes128_state = SM_AES128_IDLE; 3473 3474 log_info_key("irk", sm_persistent_irk); 3475 dkg_state = DKG_CALC_DHK; 3476 sm_trigger_run(); 3477 } 3478 3479 static void sm_handle_encryption_result_dkg_dhk(void *arg){ 3480 UNUSED(arg); 3481 sm_aes128_state = SM_AES128_IDLE; 3482 3483 log_info_key("dhk", sm_persistent_dhk); 3484 dkg_state = DKG_READY; 3485 sm_trigger_run(); 3486 } 3487 3488 static void sm_handle_encryption_result_rau(void *arg){ 3489 UNUSED(arg); 3490 sm_aes128_state = SM_AES128_IDLE; 3491 3492 (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3); 3493 rau_state = RAU_IDLE; 3494 hci_le_random_address_set(sm_random_address); 3495 3496 sm_trigger_run(); 3497 } 3498 3499 static void sm_handle_random_result_rau(void * arg){ 3500 UNUSED(arg); 3501 // non-resolvable vs. resolvable 3502 switch (gap_random_adress_type){ 3503 case GAP_RANDOM_ADDRESS_RESOLVABLE: 3504 // resolvable: use random as prand and calc address hash 3505 // "The two most significant bits of prand shall be equal to ‘0’ and ‘1" 3506 sm_random_address[0u] &= 0x3fu; 3507 sm_random_address[0u] |= 0x40u; 3508 rau_state = RAU_GET_ENC; 3509 break; 3510 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 3511 default: 3512 // "The two most significant bits of the address shall be equal to ‘0’"" 3513 sm_random_address[0u] &= 0x3fu; 3514 rau_state = RAU_IDLE; 3515 hci_le_random_address_set(sm_random_address); 3516 break; 3517 } 3518 sm_trigger_run(); 3519 } 3520 3521 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3522 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){ 3523 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3524 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3525 if (connection == NULL) return; 3526 3527 connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 3528 sm_trigger_run(); 3529 } 3530 3531 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){ 3532 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3533 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3534 if (connection == NULL) return; 3535 3536 connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 3537 sm_trigger_run(); 3538 } 3539 #endif 3540 3541 static void sm_handle_random_result_ph2_random(void * arg){ 3542 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3543 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3544 if (connection == NULL) return; 3545 3546 connection->sm_engine_state = SM_PH2_C1_GET_ENC_A; 3547 sm_trigger_run(); 3548 } 3549 3550 static void sm_handle_random_result_ph2_tk(void * arg){ 3551 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3552 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3553 if (connection == NULL) return; 3554 3555 sm_reset_tk(); 3556 uint32_t tk; 3557 if (sm_fixed_passkey_in_display_role == 0xffffffffU){ 3558 // map random to 0-999999 without speding much cycles on a modulus operation 3559 tk = little_endian_read_32(sm_random_data,0); 3560 tk = tk & 0xfffff; // 1048575 3561 if (tk >= 999999u){ 3562 tk = tk - 999999u; 3563 } 3564 } else { 3565 // override with pre-defined passkey 3566 tk = sm_fixed_passkey_in_display_role; 3567 } 3568 big_endian_store_32(setup->sm_tk, 12, tk); 3569 if (IS_RESPONDER(connection->sm_role)){ 3570 connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE; 3571 } else { 3572 if (setup->sm_use_secure_connections){ 3573 connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 3574 } else { 3575 connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 3576 sm_trigger_user_response(connection); 3577 // response_idle == nothing <--> sm_trigger_user_response() did not require response 3578 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 3579 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) connection->sm_handle); 3580 } 3581 } 3582 } 3583 sm_trigger_run(); 3584 } 3585 3586 static void sm_handle_random_result_ph3_div(void * arg){ 3587 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3588 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3589 if (connection == NULL) return; 3590 3591 // use 16 bit from random value as div 3592 setup->sm_local_div = big_endian_read_16(sm_random_data, 0); 3593 log_info_hex16("div", setup->sm_local_div); 3594 connection->sm_engine_state = SM_PH3_Y_GET_ENC; 3595 sm_trigger_run(); 3596 } 3597 3598 static void sm_handle_random_result_ph3_random(void * arg){ 3599 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3600 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3601 if (connection == NULL) return; 3602 3603 reverse_64(sm_random_data, setup->sm_local_rand); 3604 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 3605 setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u); 3606 // no db for authenticated flag hack: store flag in bit 4 of LSB 3607 setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u); 3608 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle); 3609 } 3610 static void sm_validate_er_ir(void){ 3611 // warn about default ER/IR 3612 bool warning = false; 3613 if (sm_ir_is_default()){ 3614 warning = true; 3615 log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues"); 3616 } 3617 if (sm_er_is_default()){ 3618 warning = true; 3619 log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure"); 3620 } 3621 if (warning) { 3622 log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys"); 3623 } 3624 } 3625 3626 static void sm_handle_random_result_ir(void *arg){ 3627 sm_persistent_keys_random_active = false; 3628 if (arg != NULL){ 3629 // key generated, store in tlv 3630 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u); 3631 log_info("Generated IR key. Store in TLV status: %d", status); 3632 UNUSED(status); 3633 } 3634 log_info_key("IR", sm_persistent_ir); 3635 dkg_state = DKG_CALC_IRK; 3636 3637 if (test_use_fixed_local_irk){ 3638 log_info_key("IRK", sm_persistent_irk); 3639 dkg_state = DKG_CALC_DHK; 3640 } 3641 3642 sm_trigger_run(); 3643 } 3644 3645 static void sm_handle_random_result_er(void *arg){ 3646 sm_persistent_keys_random_active = false; 3647 if (arg != 0){ 3648 // key generated, store in tlv 3649 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u); 3650 log_info("Generated ER key. Store in TLV status: %d", status); 3651 UNUSED(status); 3652 } 3653 log_info_key("ER", sm_persistent_er); 3654 3655 // try load ir 3656 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u); 3657 if (key_size == 16){ 3658 // ok, let's continue 3659 log_info("IR from TLV"); 3660 sm_handle_random_result_ir( NULL ); 3661 } else { 3662 // invalid, generate new random one 3663 sm_persistent_keys_random_active = true; 3664 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir); 3665 } 3666 } 3667 3668 static void sm_connection_init(sm_connection_t * sm_conn, hci_con_handle_t con_handle, uint8_t role, uint8_t addr_type, bd_addr_t address){ 3669 3670 // connection info 3671 sm_conn->sm_handle = con_handle; 3672 sm_conn->sm_role = role; 3673 sm_conn->sm_peer_addr_type = addr_type; 3674 memcpy(sm_conn->sm_peer_address, address, 6); 3675 3676 // security properties 3677 sm_conn->sm_connection_encrypted = 0; 3678 sm_conn->sm_connection_authenticated = 0; 3679 sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN; 3680 sm_conn->sm_le_db_index = -1; 3681 sm_conn->sm_reencryption_active = false; 3682 3683 // prepare CSRK lookup (does not involve setup) 3684 sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY; 3685 3686 sm_conn->sm_engine_state = SM_GENERAL_IDLE; 3687 } 3688 3689 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 3690 3691 UNUSED(channel); // ok: there is no channel 3692 UNUSED(size); // ok: fixed format HCI events 3693 3694 sm_connection_t * sm_conn; 3695 hci_con_handle_t con_handle; 3696 uint8_t status; 3697 bd_addr_t addr; 3698 3699 switch (packet_type) { 3700 3701 case HCI_EVENT_PACKET: 3702 switch (hci_event_packet_get_type(packet)) { 3703 3704 case BTSTACK_EVENT_STATE: 3705 switch (btstack_event_state_get_state(packet)){ 3706 case HCI_STATE_WORKING: 3707 log_info("HCI Working!"); 3708 // setup IR/ER with TLV 3709 btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context); 3710 if (sm_tlv_impl != NULL){ 3711 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u); 3712 if (key_size == 16){ 3713 // ok, let's continue 3714 log_info("ER from TLV"); 3715 sm_handle_random_result_er( NULL ); 3716 } else { 3717 // invalid, generate random one 3718 sm_persistent_keys_random_active = true; 3719 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er); 3720 } 3721 } else { 3722 sm_validate_er_ir(); 3723 dkg_state = DKG_CALC_IRK; 3724 3725 if (test_use_fixed_local_irk){ 3726 log_info_key("IRK", sm_persistent_irk); 3727 dkg_state = DKG_CALC_DHK; 3728 } 3729 } 3730 3731 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3732 // trigger ECC key generation 3733 if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){ 3734 sm_ec_generate_new_key(); 3735 } 3736 #endif 3737 3738 // restart random address updates after power cycle 3739 if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){ 3740 gap_random_address_set(sm_random_address); 3741 } else { 3742 gap_random_address_set_mode(gap_random_adress_type); 3743 } 3744 break; 3745 3746 case HCI_STATE_OFF: 3747 case HCI_STATE_HALTING: 3748 log_info("SM: reset state"); 3749 // stop random address update 3750 gap_random_address_update_stop(); 3751 // reset state 3752 sm_state_reset(); 3753 break; 3754 3755 default: 3756 break; 3757 } 3758 break; 3759 3760 #ifdef ENABLE_CLASSIC 3761 case HCI_EVENT_CONNECTION_COMPLETE: 3762 // ignore if connection failed 3763 if (hci_event_connection_complete_get_status(packet)) return; 3764 3765 con_handle = hci_event_connection_complete_get_connection_handle(packet); 3766 sm_conn = sm_get_connection_for_handle(con_handle); 3767 if (!sm_conn) break; 3768 3769 hci_event_connection_complete_get_bd_addr(packet, addr); 3770 sm_connection_init(sm_conn, 3771 con_handle, 3772 (uint8_t) gap_get_role(con_handle), 3773 BD_ADDR_TYPE_LE_PUBLIC, 3774 addr); 3775 // classic connection corresponds to public le address 3776 sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC; 3777 gap_local_bd_addr(sm_conn->sm_own_address); 3778 sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER; 3779 sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE; 3780 break; 3781 #endif 3782 3783 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3784 case HCI_EVENT_SIMPLE_PAIRING_COMPLETE: 3785 if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break; 3786 hci_event_simple_pairing_complete_get_bd_addr(packet, addr); 3787 sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3788 if (sm_conn == NULL) break; 3789 sm_conn->sm_pairing_requested = 1; 3790 break; 3791 #endif 3792 3793 case HCI_EVENT_LE_META: 3794 switch (packet[2]) { 3795 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 3796 // ignore if connection failed 3797 if (packet[3]) return; 3798 3799 con_handle = little_endian_read_16(packet, 4); 3800 sm_conn = sm_get_connection_for_handle(con_handle); 3801 if (!sm_conn) break; 3802 3803 hci_subevent_le_connection_complete_get_peer_address(packet, addr); 3804 sm_connection_init(sm_conn, 3805 con_handle, 3806 hci_subevent_le_connection_complete_get_role(packet), 3807 hci_subevent_le_connection_complete_get_peer_address_type(packet), 3808 addr); 3809 sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL; 3810 3811 // track our addr used for this connection and set state 3812 #ifdef ENABLE_LE_PERIPHERAL 3813 if (hci_subevent_le_connection_complete_get_role(packet) != 0){ 3814 // responder - use own address from advertisements 3815 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address); 3816 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3817 } 3818 #endif 3819 #ifdef ENABLE_LE_CENTRAL 3820 if (hci_subevent_le_connection_complete_get_role(packet) == 0){ 3821 // initiator - use own address from create connection 3822 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address); 3823 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3824 } 3825 #endif 3826 break; 3827 3828 case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST: 3829 con_handle = little_endian_read_16(packet, 3); 3830 sm_conn = sm_get_connection_for_handle(con_handle); 3831 if (!sm_conn) break; 3832 3833 log_info("LTK Request: state %u", sm_conn->sm_engine_state); 3834 if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){ 3835 sm_conn->sm_engine_state = SM_PH2_CALC_STK; 3836 break; 3837 } 3838 if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){ 3839 // PH2 SEND LTK as we need to exchange keys in PH3 3840 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 3841 break; 3842 } 3843 3844 // store rand and ediv 3845 reverse_64(&packet[5], sm_conn->sm_local_rand); 3846 sm_conn->sm_local_ediv = little_endian_read_16(packet, 13); 3847 3848 // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a 3849 // potentially stored LTK is from the master 3850 if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){ 3851 if (sm_reconstruct_ltk_without_le_device_db_entry){ 3852 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3853 break; 3854 } 3855 // additionally check if remote is in LE Device DB if requested 3856 switch(sm_conn->sm_irk_lookup_state){ 3857 case IRK_LOOKUP_FAILED: 3858 log_info("LTK Request: device not in device db"); 3859 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3860 break; 3861 case IRK_LOOKUP_SUCCEEDED: 3862 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3863 break; 3864 default: 3865 // wait for irk look doen 3866 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK; 3867 break; 3868 } 3869 break; 3870 } 3871 3872 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3873 sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST; 3874 #else 3875 log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported"); 3876 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3877 #endif 3878 break; 3879 3880 default: 3881 break; 3882 } 3883 break; 3884 3885 case HCI_EVENT_ENCRYPTION_CHANGE: 3886 case HCI_EVENT_ENCRYPTION_CHANGE_V2: 3887 con_handle = hci_event_encryption_change_get_connection_handle(packet); 3888 sm_conn = sm_get_connection_for_handle(con_handle); 3889 if (!sm_conn) break; 3890 3891 sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet); 3892 log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted, 3893 sm_conn->sm_actual_encryption_key_size); 3894 log_info("event handler, state %u", sm_conn->sm_engine_state); 3895 3896 switch (sm_conn->sm_engine_state){ 3897 3898 case SM_PH4_W4_CONNECTION_ENCRYPTED: 3899 // encryption change event concludes re-encryption for bonded devices (even if it fails) 3900 if (sm_conn->sm_connection_encrypted) { 3901 status = ERROR_CODE_SUCCESS; 3902 if (sm_conn->sm_role){ 3903 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3904 } else { 3905 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3906 } 3907 } else { 3908 status = hci_event_encryption_change_get_status(packet); 3909 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions 3910 // also, gap_reconnect_security_setup_active will return true 3911 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED; 3912 } 3913 3914 // emit re-encryption complete 3915 sm_reencryption_complete(sm_conn, status); 3916 3917 // notify client, if pairing was requested before 3918 if (sm_conn->sm_pairing_requested){ 3919 sm_conn->sm_pairing_requested = 0; 3920 sm_pairing_complete(sm_conn, status, 0); 3921 } 3922 3923 sm_done_for_handle(sm_conn->sm_handle); 3924 break; 3925 3926 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3927 if (!sm_conn->sm_connection_encrypted) break; 3928 sm_conn->sm_connection_sc = setup->sm_use_secure_connections; 3929 if (IS_RESPONDER(sm_conn->sm_role)){ 3930 // slave 3931 if (setup->sm_use_secure_connections){ 3932 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3933 } else { 3934 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph3_random, (void *)(uintptr_t) sm_conn->sm_handle); 3935 } 3936 } else { 3937 // master 3938 if (sm_key_distribution_all_received()){ 3939 // skip receiving keys as there are none 3940 sm_key_distribution_handle_all_received(sm_conn); 3941 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph3_random, (void *)(uintptr_t) sm_conn->sm_handle); 3942 } else { 3943 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3944 } 3945 } 3946 break; 3947 3948 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3949 case SM_BR_EDR_W4_ENCRYPTION_COMPLETE: 3950 // CTKD requires BR/EDR Secure Connection 3951 if (sm_conn->sm_connection_encrypted != 2) break; 3952 // prepare for pairing request 3953 if (IS_RESPONDER(sm_conn->sm_role)){ 3954 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST; 3955 } else if (sm_conn->sm_pairing_requested){ 3956 // check if remote supports fixed channels 3957 bool defer = true; 3958 const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 3959 if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE){ 3960 // check if remote supports SMP over BR/EDR 3961 if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){ 3962 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST; 3963 } else { 3964 defer = false; 3965 } 3966 } else { 3967 // wait for fixed channel info 3968 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK; 3969 } 3970 if (defer){ 3971 hci_dedicated_bonding_defer_disconnect(con_handle, true); 3972 } 3973 } 3974 break; 3975 #endif 3976 default: 3977 break; 3978 } 3979 break; 3980 3981 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE: 3982 con_handle = little_endian_read_16(packet, 3); 3983 sm_conn = sm_get_connection_for_handle(con_handle); 3984 if (!sm_conn) break; 3985 3986 log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size); 3987 log_info("event handler, state %u", sm_conn->sm_engine_state); 3988 // continue if part of initial pairing 3989 switch (sm_conn->sm_engine_state){ 3990 case SM_PH4_W4_CONNECTION_ENCRYPTED: 3991 if (sm_conn->sm_role){ 3992 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3993 } else { 3994 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3995 } 3996 sm_done_for_handle(sm_conn->sm_handle); 3997 break; 3998 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3999 if (IS_RESPONDER(sm_conn->sm_role)){ 4000 // slave 4001 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph3_random, (void *)(uintptr_t) sm_conn->sm_handle); 4002 } else { 4003 // master 4004 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 4005 } 4006 break; 4007 default: 4008 break; 4009 } 4010 break; 4011 4012 4013 case HCI_EVENT_DISCONNECTION_COMPLETE: 4014 con_handle = little_endian_read_16(packet, 3); 4015 sm_done_for_handle(con_handle); 4016 sm_conn = sm_get_connection_for_handle(con_handle); 4017 if (!sm_conn) break; 4018 4019 // pairing failed, if it was ongoing 4020 switch (sm_conn->sm_engine_state){ 4021 case SM_GENERAL_IDLE: 4022 case SM_INITIATOR_CONNECTED: 4023 case SM_RESPONDER_IDLE: 4024 break; 4025 default: 4026 sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4027 sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0); 4028 break; 4029 } 4030 4031 sm_conn->sm_engine_state = SM_GENERAL_IDLE; 4032 sm_conn->sm_handle = 0; 4033 break; 4034 4035 case HCI_EVENT_COMMAND_COMPLETE: 4036 if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) { 4037 // set local addr for le device db 4038 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr); 4039 le_device_db_set_local_bd_addr(addr); 4040 } 4041 break; 4042 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 4043 case L2CAP_EVENT_INFORMATION_RESPONSE: 4044 con_handle = l2cap_event_information_response_get_con_handle(packet); 4045 sm_conn = sm_get_connection_for_handle(con_handle); 4046 if (!sm_conn) break; 4047 if (sm_conn->sm_engine_state == SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK){ 4048 // check if remote supports SMP over BR/EDR 4049 const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 4050 if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){ 4051 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST; 4052 } else { 4053 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 4054 hci_dedicated_bonding_defer_disconnect(con_handle, false); 4055 } 4056 } 4057 break; 4058 #endif 4059 default: 4060 break; 4061 } 4062 break; 4063 default: 4064 break; 4065 } 4066 4067 sm_run(); 4068 } 4069 4070 static inline int sm_calc_actual_encryption_key_size(int other){ 4071 if (other < sm_min_encryption_key_size) return 0; 4072 if (other < sm_max_encryption_key_size) return other; 4073 return sm_max_encryption_key_size; 4074 } 4075 4076 4077 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4078 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){ 4079 switch (method){ 4080 case JUST_WORKS: 4081 case NUMERIC_COMPARISON: 4082 return 1; 4083 default: 4084 return 0; 4085 } 4086 } 4087 // responder 4088 4089 static int sm_passkey_used(stk_generation_method_t method){ 4090 switch (method){ 4091 case PK_RESP_INPUT: 4092 return 1; 4093 default: 4094 return 0; 4095 } 4096 } 4097 4098 static int sm_passkey_entry(stk_generation_method_t method){ 4099 switch (method){ 4100 case PK_RESP_INPUT: 4101 case PK_INIT_INPUT: 4102 case PK_BOTH_INPUT: 4103 return 1; 4104 default: 4105 return 0; 4106 } 4107 } 4108 4109 #endif 4110 4111 /** 4112 * @return ok 4113 */ 4114 static int sm_validate_stk_generation_method(void){ 4115 // check if STK generation method is acceptable by client 4116 switch (setup->sm_stk_generation_method){ 4117 case JUST_WORKS: 4118 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u; 4119 case PK_RESP_INPUT: 4120 case PK_INIT_INPUT: 4121 case PK_BOTH_INPUT: 4122 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u; 4123 case OOB: 4124 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u; 4125 case NUMERIC_COMPARISON: 4126 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u; 4127 default: 4128 return 0; 4129 } 4130 } 4131 4132 #ifdef ENABLE_LE_CENTRAL 4133 static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){ 4134 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4135 if (sm_sc_only_mode){ 4136 uint8_t auth_req = packet[1]; 4137 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){ 4138 sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS); 4139 return; 4140 } 4141 } 4142 #else 4143 UNUSED(packet); 4144 #endif 4145 4146 int have_ltk; 4147 uint8_t ltk[16]; 4148 4149 // IRK complete? 4150 switch (sm_conn->sm_irk_lookup_state){ 4151 case IRK_LOOKUP_FAILED: 4152 // start pairing 4153 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4154 break; 4155 case IRK_LOOKUP_SUCCEEDED: 4156 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4157 have_ltk = !sm_is_null_key(ltk); 4158 log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted); 4159 if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){ 4160 // start re-encrypt if we have LTK and the connection is not already encrypted 4161 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK; 4162 } else { 4163 // start pairing 4164 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4165 } 4166 break; 4167 default: 4168 // otherwise, store security request 4169 sm_conn->sm_security_request_received = 1; 4170 break; 4171 } 4172 } 4173 #endif 4174 4175 static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){ 4176 4177 // size of complete sm_pdu used to validate input 4178 static const uint8_t sm_pdu_size[] = { 4179 0, // 0x00 invalid opcode 4180 7, // 0x01 pairing request 4181 7, // 0x02 pairing response 4182 17, // 0x03 pairing confirm 4183 17, // 0x04 pairing random 4184 2, // 0x05 pairing failed 4185 17, // 0x06 encryption information 4186 11, // 0x07 master identification 4187 17, // 0x08 identification information 4188 8, // 0x09 identify address information 4189 17, // 0x0a signing information 4190 2, // 0x0b security request 4191 65, // 0x0c pairing public key 4192 17, // 0x0d pairing dhk check 4193 2, // 0x0e keypress notification 4194 }; 4195 4196 if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){ 4197 sm_run(); 4198 } 4199 4200 if (packet_type != SM_DATA_PACKET) return; 4201 if (size == 0u) return; 4202 4203 uint8_t sm_pdu_code = packet[0]; 4204 4205 // validate pdu size 4206 if (sm_pdu_code >= sizeof(sm_pdu_size)) return; 4207 if (sm_pdu_size[sm_pdu_code] != size) return; 4208 4209 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4210 if (!sm_conn) return; 4211 4212 if (sm_pdu_code == SM_CODE_PAIRING_FAILED){ 4213 sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE); 4214 sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]); 4215 sm_done_for_handle(con_handle); 4216 sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 4217 return; 4218 } 4219 4220 log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code); 4221 4222 int err; 4223 UNUSED(err); 4224 4225 if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){ 4226 uint8_t buffer[5]; 4227 buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION; 4228 buffer[1] = 3; 4229 little_endian_store_16(buffer, 2, con_handle); 4230 buffer[4] = packet[1]; 4231 sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer)); 4232 return; 4233 } 4234 4235 switch (sm_conn->sm_engine_state){ 4236 4237 // a sm timeout requires a new physical connection 4238 case SM_GENERAL_TIMEOUT: 4239 return; 4240 4241 #ifdef ENABLE_LE_CENTRAL 4242 4243 // Initiator 4244 case SM_INITIATOR_CONNECTED: 4245 if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){ 4246 sm_pdu_received_in_wrong_state(sm_conn); 4247 break; 4248 } 4249 sm_initiator_connected_handle_security_request(sm_conn, packet); 4250 break; 4251 4252 case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE: 4253 // Core 5, Vol 3, Part H, 2.4.6: 4254 // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request 4255 // without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup." 4256 if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){ 4257 log_info("Ignoring Security Request"); 4258 break; 4259 } 4260 4261 // all other pdus are incorrect 4262 if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){ 4263 sm_pdu_received_in_wrong_state(sm_conn); 4264 break; 4265 } 4266 4267 // store pairing request 4268 (void)memcpy(&setup->sm_s_pres, packet, 4269 sizeof(sm_pairing_packet_t)); 4270 err = sm_stk_generation_init(sm_conn); 4271 4272 #ifdef ENABLE_TESTING_SUPPORT 4273 if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){ 4274 log_info("testing_support: abort with pairing failure %u", test_pairing_failure); 4275 err = test_pairing_failure; 4276 } 4277 #endif 4278 4279 if (err != 0){ 4280 sm_pairing_error(sm_conn, err); 4281 break; 4282 } 4283 4284 // generate random number first, if we need to show passkey 4285 if (setup->sm_stk_generation_method == PK_RESP_INPUT){ 4286 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph2_tk, (void *)(uintptr_t) sm_conn->sm_handle); 4287 break; 4288 } 4289 4290 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4291 if (setup->sm_use_secure_connections){ 4292 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 4293 if (setup->sm_stk_generation_method == JUST_WORKS){ 4294 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4295 sm_trigger_user_response(sm_conn); 4296 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 4297 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4298 } 4299 } else { 4300 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4301 } 4302 break; 4303 } 4304 #endif 4305 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4306 sm_trigger_user_response(sm_conn); 4307 // response_idle == nothing <--> sm_trigger_user_response() did not require response 4308 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 4309 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) sm_conn->sm_handle); 4310 } 4311 break; 4312 4313 case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM: 4314 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4315 sm_pdu_received_in_wrong_state(sm_conn); 4316 break; 4317 } 4318 4319 // store s_confirm 4320 reverse_128(&packet[1], setup->sm_peer_confirm); 4321 4322 // abort if s_confirm matches m_confirm 4323 if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){ 4324 sm_pdu_received_in_wrong_state(sm_conn); 4325 break; 4326 } 4327 4328 #ifdef ENABLE_TESTING_SUPPORT 4329 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4330 log_info("testing_support: reset confirm value"); 4331 memset(setup->sm_peer_confirm, 0, 16); 4332 } 4333 #endif 4334 sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 4335 break; 4336 4337 case SM_INITIATOR_PH2_W4_PAIRING_RANDOM: 4338 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4339 sm_pdu_received_in_wrong_state(sm_conn); 4340 break;; 4341 } 4342 4343 // received random value 4344 reverse_128(&packet[1], setup->sm_peer_random); 4345 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 4346 break; 4347 4348 case SM_PH4_W4_CONNECTION_ENCRYPTED: 4349 // ignore Security Request, see SM_INITIATOR_PH1_W4_PAIRING_RESPONSE above 4350 if (sm_pdu_code != SM_CODE_SECURITY_REQUEST){ 4351 sm_pdu_received_in_wrong_state(sm_conn); 4352 } 4353 break; 4354 #endif 4355 4356 #ifdef ENABLE_LE_PERIPHERAL 4357 // Responder 4358 case SM_RESPONDER_IDLE: 4359 case SM_RESPONDER_SEND_SECURITY_REQUEST: 4360 case SM_RESPONDER_PH1_W4_PAIRING_REQUEST: 4361 if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){ 4362 sm_pdu_received_in_wrong_state(sm_conn); 4363 break;; 4364 } 4365 4366 // store pairing request 4367 (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t)); 4368 4369 // check if IRK completed 4370 switch (sm_conn->sm_irk_lookup_state){ 4371 case IRK_LOOKUP_SUCCEEDED: 4372 case IRK_LOOKUP_FAILED: 4373 sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED; 4374 break; 4375 default: 4376 sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK; 4377 break; 4378 } 4379 break; 4380 #endif 4381 4382 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4383 case SM_SC_W4_PUBLIC_KEY_COMMAND: 4384 if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){ 4385 sm_pdu_received_in_wrong_state(sm_conn); 4386 break; 4387 } 4388 4389 // store public key for DH Key calculation 4390 reverse_256(&packet[01], &setup->sm_peer_q[0]); 4391 reverse_256(&packet[33], &setup->sm_peer_q[32]); 4392 4393 // CVE-2020-26558: abort pairing if remote uses the same public key 4394 if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){ 4395 log_info("Remote PK matches ours"); 4396 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 4397 break; 4398 } 4399 4400 // validate public key 4401 err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q); 4402 if (err != 0){ 4403 log_info("sm: peer public key invalid %x", err); 4404 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 4405 break; 4406 } 4407 4408 // start calculating dhkey 4409 btstack_crypto_ecc_p256_calculate_dhkey(&sm_crypto_ecc_p256_request, setup->sm_peer_q, setup->sm_dhkey, sm_sc_dhkey_calculated, (void*)(uintptr_t) sm_conn->sm_handle); 4410 4411 4412 log_info("public key received, generation method %u", setup->sm_stk_generation_method); 4413 if (IS_RESPONDER(sm_conn->sm_role)){ 4414 // responder 4415 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4416 } else { 4417 // initiator 4418 // stk generation method 4419 // passkey entry: notify app to show passkey or to request passkey 4420 switch (setup->sm_stk_generation_method){ 4421 case JUST_WORKS: 4422 case NUMERIC_COMPARISON: 4423 sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION; 4424 break; 4425 case PK_RESP_INPUT: 4426 sm_sc_start_calculating_local_confirm(sm_conn); 4427 break; 4428 case PK_INIT_INPUT: 4429 case PK_BOTH_INPUT: 4430 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 4431 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 4432 break; 4433 } 4434 sm_sc_start_calculating_local_confirm(sm_conn); 4435 break; 4436 case OOB: 4437 // generate Nx 4438 log_info("Generate Na"); 4439 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_send_pairing_random, (void*)(uintptr_t) sm_conn->sm_handle); 4440 break; 4441 default: 4442 btstack_assert(false); 4443 break; 4444 } 4445 } 4446 break; 4447 4448 case SM_SC_W4_CONFIRMATION: 4449 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4450 sm_pdu_received_in_wrong_state(sm_conn); 4451 break; 4452 } 4453 // received confirm value 4454 reverse_128(&packet[1], setup->sm_peer_confirm); 4455 4456 #ifdef ENABLE_TESTING_SUPPORT 4457 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4458 log_info("testing_support: reset confirm value"); 4459 memset(setup->sm_peer_confirm, 0, 16); 4460 } 4461 #endif 4462 if (IS_RESPONDER(sm_conn->sm_role)){ 4463 // responder 4464 if (sm_passkey_used(setup->sm_stk_generation_method)){ 4465 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 4466 // still waiting for passkey 4467 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 4468 break; 4469 } 4470 } 4471 sm_sc_start_calculating_local_confirm(sm_conn); 4472 } else { 4473 // initiator 4474 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){ 4475 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_nonce, 16, &sm_handle_random_result_sc_next_send_pairing_random, (void*)(uintptr_t) sm_conn->sm_handle); 4476 } else { 4477 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 4478 } 4479 } 4480 break; 4481 4482 case SM_SC_W4_PAIRING_RANDOM: 4483 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4484 sm_pdu_received_in_wrong_state(sm_conn); 4485 break; 4486 } 4487 4488 // received random value 4489 reverse_128(&packet[1], setup->sm_peer_nonce); 4490 4491 // validate confirm value if Cb = f4(Pkb, Pka, Nb, z) 4492 // only check for JUST WORK/NC in initiator role OR passkey entry 4493 log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u", 4494 IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method), 4495 sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method)); 4496 if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)) 4497 || (sm_passkey_entry(setup->sm_stk_generation_method)) ) { 4498 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 4499 break; 4500 } 4501 4502 // OOB 4503 if (setup->sm_stk_generation_method == OOB){ 4504 4505 // setup local random, set to zero if remote did not receive our data 4506 log_info("Received nonce, setup local random ra/rb for dhkey check"); 4507 if (IS_RESPONDER(sm_conn->sm_role)){ 4508 if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){ 4509 log_info("Reset rb as A does not have OOB data"); 4510 memset(setup->sm_rb, 0, 16); 4511 } else { 4512 (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16); 4513 log_info("Use stored rb"); 4514 log_info_hexdump(setup->sm_rb, 16); 4515 } 4516 } else { 4517 if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){ 4518 log_info("Reset ra as B does not have OOB data"); 4519 memset(setup->sm_ra, 0, 16); 4520 } else { 4521 (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16); 4522 log_info("Use stored ra"); 4523 log_info_hexdump(setup->sm_ra, 16); 4524 } 4525 } 4526 4527 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received 4528 if (setup->sm_have_oob_data){ 4529 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 4530 break; 4531 } 4532 } 4533 4534 // TODO: we only get here for Responder role with JW/NC 4535 sm_sc_state_after_receiving_random(sm_conn); 4536 break; 4537 4538 case SM_SC_W2_CALCULATE_G2: 4539 case SM_SC_W4_CALCULATE_G2: 4540 case SM_SC_W4_CALCULATE_DHKEY: 4541 case SM_SC_W2_CALCULATE_F5_SALT: 4542 case SM_SC_W4_CALCULATE_F5_SALT: 4543 case SM_SC_W2_CALCULATE_F5_MACKEY: 4544 case SM_SC_W4_CALCULATE_F5_MACKEY: 4545 case SM_SC_W2_CALCULATE_F5_LTK: 4546 case SM_SC_W4_CALCULATE_F5_LTK: 4547 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 4548 case SM_SC_W4_DHKEY_CHECK_COMMAND: 4549 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 4550 case SM_SC_W4_USER_RESPONSE: 4551 if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){ 4552 sm_pdu_received_in_wrong_state(sm_conn); 4553 break; 4554 } 4555 // store DHKey Check 4556 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED; 4557 reverse_128(&packet[01], setup->sm_peer_dhkey_check); 4558 4559 // have we been only waiting for dhkey check command? 4560 if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){ 4561 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 4562 } 4563 break; 4564 #endif 4565 4566 #ifdef ENABLE_LE_PERIPHERAL 4567 case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM: 4568 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4569 sm_pdu_received_in_wrong_state(sm_conn); 4570 break; 4571 } 4572 4573 // received confirm value 4574 reverse_128(&packet[1], setup->sm_peer_confirm); 4575 4576 #ifdef ENABLE_TESTING_SUPPORT 4577 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4578 log_info("testing_support: reset confirm value"); 4579 memset(setup->sm_peer_confirm, 0, 16); 4580 } 4581 #endif 4582 // notify client to hide shown passkey 4583 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 4584 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address); 4585 } 4586 4587 // handle user cancel pairing? 4588 if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){ 4589 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED); 4590 break; 4591 } 4592 4593 // wait for user action? 4594 if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){ 4595 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4596 break; 4597 } 4598 4599 // calculate and send local_confirm 4600 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) sm_conn->sm_handle); 4601 break; 4602 4603 case SM_RESPONDER_PH2_W4_PAIRING_RANDOM: 4604 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4605 sm_pdu_received_in_wrong_state(sm_conn); 4606 break;; 4607 } 4608 4609 // received random value 4610 reverse_128(&packet[1], setup->sm_peer_random); 4611 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 4612 break; 4613 #endif 4614 4615 case SM_PH2_W4_CONNECTION_ENCRYPTED: 4616 case SM_PH3_RECEIVE_KEYS: 4617 switch(sm_pdu_code){ 4618 case SM_CODE_ENCRYPTION_INFORMATION: 4619 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 4620 reverse_128(&packet[1], setup->sm_peer_ltk); 4621 break; 4622 4623 case SM_CODE_MASTER_IDENTIFICATION: 4624 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 4625 setup->sm_peer_ediv = little_endian_read_16(packet, 1); 4626 reverse_64(&packet[3], setup->sm_peer_rand); 4627 break; 4628 4629 case SM_CODE_IDENTITY_INFORMATION: 4630 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 4631 reverse_128(&packet[1], setup->sm_peer_irk); 4632 break; 4633 4634 case SM_CODE_IDENTITY_ADDRESS_INFORMATION: 4635 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 4636 setup->sm_peer_addr_type = packet[1]; 4637 reverse_bd_addr(&packet[2], setup->sm_peer_address); 4638 break; 4639 4640 case SM_CODE_SIGNING_INFORMATION: 4641 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 4642 reverse_128(&packet[1], setup->sm_peer_csrk); 4643 break; 4644 default: 4645 // Unexpected PDU 4646 log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]); 4647 break; 4648 } 4649 // done with key distribution? 4650 if (sm_key_distribution_all_received()){ 4651 4652 sm_key_distribution_handle_all_received(sm_conn); 4653 4654 if (IS_RESPONDER(sm_conn->sm_role)){ 4655 sm_key_distribution_complete_responder(sm_conn); 4656 } else { 4657 if (setup->sm_use_secure_connections){ 4658 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 4659 } else { 4660 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph3_random, (void *)(uintptr_t) sm_conn->sm_handle); 4661 } 4662 } 4663 } 4664 break; 4665 4666 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 4667 case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE: 4668 4669 // dedicated bonding complete 4670 hci_dedicated_bonding_defer_disconnect(sm_conn->sm_handle, false); 4671 4672 if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){ 4673 sm_pdu_received_in_wrong_state(sm_conn); 4674 break; 4675 } 4676 // store pairing response 4677 (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t)); 4678 4679 // validate encryption key size 4680 sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres)); 4681 // SC Only mandates 128 bit key size 4682 if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) { 4683 sm_conn->sm_actual_encryption_key_size = 0; 4684 } 4685 if (sm_conn->sm_actual_encryption_key_size == 0){ 4686 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE); 4687 break; 4688 } 4689 4690 // prepare key exchange, LTK is derived locally 4691 sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY, 4692 sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY); 4693 4694 // skip receive if there are none 4695 if (sm_key_distribution_all_received()){ 4696 // distribute keys in run handles 'no keys to send' 4697 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 4698 } else { 4699 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS; 4700 } 4701 break; 4702 4703 case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST: 4704 if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){ 4705 sm_pdu_received_in_wrong_state(sm_conn); 4706 break; 4707 } 4708 // store pairing request 4709 (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t)); 4710 // validate encryption key size 4711 sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq)); 4712 // SC Only mandates 128 bit key size 4713 if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) { 4714 sm_conn->sm_actual_encryption_key_size = 0; 4715 } 4716 if (sm_conn->sm_actual_encryption_key_size == 0){ 4717 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE); 4718 break; 4719 } 4720 // trigger response 4721 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED; 4722 break; 4723 4724 case SM_BR_EDR_RECEIVE_KEYS: 4725 switch(sm_pdu_code){ 4726 case SM_CODE_IDENTITY_INFORMATION: 4727 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 4728 reverse_128(&packet[1], setup->sm_peer_irk); 4729 break; 4730 case SM_CODE_IDENTITY_ADDRESS_INFORMATION: 4731 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 4732 setup->sm_peer_addr_type = packet[1]; 4733 reverse_bd_addr(&packet[2], setup->sm_peer_address); 4734 break; 4735 case SM_CODE_SIGNING_INFORMATION: 4736 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 4737 reverse_128(&packet[1], setup->sm_peer_csrk); 4738 break; 4739 default: 4740 // Unexpected PDU 4741 log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]); 4742 break; 4743 } 4744 4745 // all keys received 4746 if (sm_key_distribution_all_received()){ 4747 if (IS_RESPONDER(sm_conn->sm_role)){ 4748 // responder -> keys exchanged, derive LE LTK 4749 sm_ctkd_start_from_br_edr(sm_conn); 4750 } else { 4751 // initiator -> send our keys if any 4752 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 4753 } 4754 } 4755 break; 4756 #endif 4757 4758 default: 4759 // Unexpected PDU 4760 log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state); 4761 sm_pdu_received_in_wrong_state(sm_conn); 4762 break; 4763 } 4764 4765 // try to send next pdu 4766 sm_trigger_run(); 4767 } 4768 4769 // Security Manager Client API 4770 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){ 4771 sm_get_oob_data = get_oob_data_callback; 4772 } 4773 4774 void sm_register_sc_oob_data_callback( int (*get_sc_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_sc_peer_confirm, uint8_t * oob_sc_peer_random)){ 4775 sm_get_sc_oob_data = get_sc_oob_data_callback; 4776 } 4777 4778 void sm_register_ltk_callback( bool (*get_ltk_callback)(hci_con_handle_t con_handle, uint8_t address_type, bd_addr_t addr, uint8_t * ltk)){ 4779 sm_get_ltk_callback = get_ltk_callback; 4780 } 4781 4782 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4783 btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler); 4784 } 4785 4786 void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4787 btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler); 4788 } 4789 4790 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){ 4791 sm_accepted_stk_generation_methods = accepted_stk_generation_methods; 4792 } 4793 4794 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){ 4795 sm_min_encryption_key_size = min_size; 4796 sm_max_encryption_key_size = max_size; 4797 } 4798 4799 void sm_set_authentication_requirements(uint8_t auth_req){ 4800 #ifndef ENABLE_LE_SECURE_CONNECTIONS 4801 if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){ 4802 log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag"); 4803 auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION; 4804 } 4805 #endif 4806 sm_auth_req = auth_req; 4807 } 4808 4809 void sm_set_io_capabilities(io_capability_t io_capability){ 4810 sm_io_capabilities = io_capability; 4811 } 4812 4813 #ifdef ENABLE_LE_PERIPHERAL 4814 void sm_set_request_security(int enable){ 4815 sm_slave_request_security = enable; 4816 } 4817 #endif 4818 4819 void sm_set_er(sm_key_t er){ 4820 (void)memcpy(sm_persistent_er, er, 16); 4821 } 4822 4823 void sm_set_ir(sm_key_t ir){ 4824 (void)memcpy(sm_persistent_ir, ir, 16); 4825 } 4826 4827 // Testing support only 4828 void sm_test_set_irk(sm_key_t irk){ 4829 (void)memcpy(sm_persistent_irk, irk, 16); 4830 dkg_state = DKG_CALC_DHK; 4831 test_use_fixed_local_irk = true; 4832 } 4833 4834 void sm_test_use_fixed_local_csrk(void){ 4835 test_use_fixed_local_csrk = true; 4836 } 4837 4838 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4839 static void sm_ec_generated(void * arg){ 4840 UNUSED(arg); 4841 ec_key_generation_state = EC_KEY_GENERATION_DONE; 4842 // trigger pairing if pending for ec key 4843 sm_trigger_run(); 4844 } 4845 static void sm_ec_generate_new_key(void){ 4846 log_info("sm: generate new ec key"); 4847 ec_key_generation_state = EC_KEY_GENERATION_ACTIVE; 4848 btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL); 4849 } 4850 #endif 4851 4852 #ifdef ENABLE_TESTING_SUPPORT 4853 void sm_test_set_pairing_failure(int reason){ 4854 test_pairing_failure = reason; 4855 } 4856 #endif 4857 4858 static void sm_state_reset(void) { 4859 #ifdef USE_CMAC_ENGINE 4860 sm_cmac_active = 0; 4861 #endif 4862 dkg_state = DKG_W4_WORKING; 4863 rau_state = RAU_IDLE; 4864 sm_aes128_state = SM_AES128_IDLE; 4865 sm_address_resolution_test = -1; // no private address to resolve yet 4866 sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE; 4867 sm_address_resolution_general_queue = NULL; 4868 sm_active_connection_handle = HCI_CON_HANDLE_INVALID; 4869 sm_persistent_keys_random_active = false; 4870 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4871 ec_key_generation_state = EC_KEY_GENERATION_IDLE; 4872 #endif 4873 } 4874 4875 void sm_init(void){ 4876 4877 if (sm_initialized) return; 4878 4879 // set default ER and IR values (should be unique - set by app or sm later using TLV) 4880 sm_er_ir_set_default(); 4881 4882 // defaults 4883 sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS 4884 | SM_STK_GENERATION_METHOD_OOB 4885 | SM_STK_GENERATION_METHOD_PASSKEY 4886 | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON; 4887 4888 sm_max_encryption_key_size = 16; 4889 sm_min_encryption_key_size = 7; 4890 4891 sm_fixed_passkey_in_display_role = 0xffffffffU; 4892 sm_reconstruct_ltk_without_le_device_db_entry = true; 4893 4894 gap_random_adress_update_period = 15 * 60 * 1000L; 4895 4896 test_use_fixed_local_csrk = false; 4897 4898 // other 4899 btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler); 4900 4901 // register for HCI Events 4902 hci_event_callback_registration.callback = &sm_event_packet_handler; 4903 hci_add_event_handler(&hci_event_callback_registration); 4904 4905 // register for L2CAP events 4906 l2cap_event_callback_registration.callback = &sm_event_packet_handler; 4907 l2cap_add_event_handler(&l2cap_event_callback_registration); 4908 4909 // 4910 btstack_crypto_init(); 4911 4912 // init le_device_db 4913 le_device_db_init(); 4914 4915 // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW 4916 l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 4917 #ifdef ENABLE_CLASSIC 4918 l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER); 4919 #endif 4920 4921 // state 4922 sm_state_reset(); 4923 4924 sm_initialized = true; 4925 } 4926 4927 void sm_deinit(void){ 4928 sm_initialized = false; 4929 btstack_run_loop_remove_timer(&sm_run_timer); 4930 } 4931 4932 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){ 4933 sm_fixed_passkey_in_display_role = passkey; 4934 } 4935 4936 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){ 4937 sm_reconstruct_ltk_without_le_device_db_entry = allow != 0; 4938 } 4939 4940 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 4941 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 4942 if (!hci_con) return NULL; 4943 return &hci_con->sm_connection; 4944 } 4945 4946 static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk){ 4947 hci_connection_t * hci_con = hci_connection_for_handle(connection->sm_handle); 4948 btstack_assert(hci_con != NULL); 4949 memcpy(hci_con->link_key, ltk, 16); 4950 hci_con->link_key_type = 1; 4951 } 4952 4953 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 4954 static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){ 4955 hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type); 4956 if (!hci_con) return NULL; 4957 return &hci_con->sm_connection; 4958 } 4959 #endif 4960 4961 // @deprecated: map onto sm_request_pairing 4962 void sm_send_security_request(hci_con_handle_t con_handle){ 4963 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4964 if (!sm_conn) return; 4965 if (!IS_RESPONDER(sm_conn->sm_role)) return; 4966 sm_request_pairing(con_handle); 4967 } 4968 4969 // request pairing 4970 void sm_request_pairing(hci_con_handle_t con_handle){ 4971 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4972 if (!sm_conn) return; // wrong connection 4973 4974 bool have_ltk; 4975 uint8_t ltk[16]; 4976 log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state); 4977 if (IS_RESPONDER(sm_conn->sm_role)){ 4978 switch (sm_conn->sm_engine_state){ 4979 case SM_GENERAL_IDLE: 4980 case SM_RESPONDER_IDLE: 4981 switch (sm_conn->sm_irk_lookup_state){ 4982 case IRK_LOOKUP_SUCCEEDED: 4983 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4984 have_ltk = !sm_is_null_key(ltk); 4985 log_info("have ltk %u", have_ltk); 4986 if (have_ltk){ 4987 sm_conn->sm_pairing_requested = 1; 4988 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 4989 sm_reencryption_started(sm_conn); 4990 break; 4991 } 4992 /* fall through */ 4993 4994 case IRK_LOOKUP_FAILED: 4995 sm_conn->sm_pairing_requested = 1; 4996 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 4997 sm_pairing_started(sm_conn); 4998 break; 4999 default: 5000 log_info("irk lookup pending"); 5001 sm_conn->sm_pairing_requested = 1; 5002 break; 5003 } 5004 break; 5005 default: 5006 break; 5007 } 5008 } else { 5009 // used as a trigger to start central/master/initiator security procedures 5010 switch (sm_conn->sm_engine_state){ 5011 case SM_INITIATOR_CONNECTED: 5012 switch (sm_conn->sm_irk_lookup_state){ 5013 case IRK_LOOKUP_SUCCEEDED: 5014 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 5015 have_ltk = !sm_is_null_key(ltk); 5016 log_info("have ltk %u", have_ltk); 5017 if (have_ltk){ 5018 sm_conn->sm_pairing_requested = 1; 5019 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK; 5020 break; 5021 } 5022 /* fall through */ 5023 5024 case IRK_LOOKUP_FAILED: 5025 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 5026 break; 5027 default: 5028 log_info("irk lookup pending"); 5029 sm_conn->sm_pairing_requested = 1; 5030 break; 5031 } 5032 break; 5033 case SM_GENERAL_REENCRYPTION_FAILED: 5034 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 5035 break; 5036 case SM_GENERAL_IDLE: 5037 sm_conn->sm_pairing_requested = 1; 5038 break; 5039 default: 5040 break; 5041 } 5042 } 5043 sm_trigger_run(); 5044 } 5045 5046 // called by client app on authorization request 5047 void sm_authorization_decline(hci_con_handle_t con_handle){ 5048 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5049 if (!sm_conn) return; // wrong connection 5050 sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED; 5051 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0); 5052 } 5053 5054 void sm_authorization_grant(hci_con_handle_t con_handle){ 5055 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5056 if (!sm_conn) return; // wrong connection 5057 sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED; 5058 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1); 5059 } 5060 5061 // GAP Bonding API 5062 5063 void sm_bonding_decline(hci_con_handle_t con_handle){ 5064 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5065 if (!sm_conn) return; // wrong connection 5066 setup->sm_user_response = SM_USER_RESPONSE_DECLINE; 5067 log_info("decline, state %u", sm_conn->sm_engine_state); 5068 switch(sm_conn->sm_engine_state){ 5069 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5070 case SM_SC_W4_USER_RESPONSE: 5071 case SM_SC_W4_CONFIRMATION: 5072 case SM_SC_W4_PUBLIC_KEY_COMMAND: 5073 #endif 5074 case SM_PH1_W4_USER_RESPONSE: 5075 switch (setup->sm_stk_generation_method){ 5076 case PK_RESP_INPUT: 5077 case PK_INIT_INPUT: 5078 case PK_BOTH_INPUT: 5079 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED); 5080 break; 5081 case NUMERIC_COMPARISON: 5082 sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED); 5083 break; 5084 case JUST_WORKS: 5085 case OOB: 5086 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 5087 break; 5088 default: 5089 btstack_assert(false); 5090 break; 5091 } 5092 break; 5093 default: 5094 break; 5095 } 5096 sm_trigger_run(); 5097 } 5098 5099 void sm_just_works_confirm(hci_con_handle_t con_handle){ 5100 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5101 if (!sm_conn) return; // wrong connection 5102 setup->sm_user_response = SM_USER_RESPONSE_CONFIRM; 5103 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 5104 if (setup->sm_use_secure_connections){ 5105 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 5106 } else { 5107 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) sm_conn->sm_handle); 5108 } 5109 } 5110 5111 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5112 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 5113 sm_sc_prepare_dhkey_check(sm_conn); 5114 } 5115 #endif 5116 5117 sm_trigger_run(); 5118 } 5119 5120 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){ 5121 // for now, it's the same 5122 sm_just_works_confirm(con_handle); 5123 } 5124 5125 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){ 5126 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5127 if (!sm_conn) return; // wrong connection 5128 sm_reset_tk(); 5129 big_endian_store_32(setup->sm_tk, 12, passkey); 5130 setup->sm_user_response = SM_USER_RESPONSE_PASSKEY; 5131 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 5132 btstack_crypto_random_generate(&sm_crypto_random_request, setup->sm_local_random, 16, &sm_handle_random_result_ph2_random, (void *)(uintptr_t) sm_conn->sm_handle); 5133 } 5134 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5135 (void)memcpy(setup->sm_ra, setup->sm_tk, 16); 5136 (void)memcpy(setup->sm_rb, setup->sm_tk, 16); 5137 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 5138 sm_sc_start_calculating_local_confirm(sm_conn); 5139 } 5140 #endif 5141 sm_trigger_run(); 5142 } 5143 5144 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){ 5145 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5146 if (!sm_conn) return; // wrong connection 5147 if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return; 5148 uint8_t num_actions = setup->sm_keypress_notification >> 5; 5149 uint8_t flags = setup->sm_keypress_notification & 0x1fu; 5150 switch (action){ 5151 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 5152 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 5153 flags |= (1u << action); 5154 break; 5155 case SM_KEYPRESS_PASSKEY_CLEARED: 5156 // clear counter, keypress & erased flags + set passkey cleared 5157 flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED); 5158 break; 5159 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 5160 if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){ 5161 // erase actions queued 5162 num_actions--; 5163 if (num_actions == 0u){ 5164 // clear counter, keypress & erased flags 5165 flags &= 0x19u; 5166 } 5167 break; 5168 } 5169 num_actions++; 5170 flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED); 5171 break; 5172 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 5173 if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){ 5174 // enter actions queued 5175 num_actions--; 5176 if (num_actions == 0u){ 5177 // clear counter, keypress & erased flags 5178 flags &= 0x19u; 5179 } 5180 break; 5181 } 5182 num_actions++; 5183 flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED); 5184 break; 5185 default: 5186 break; 5187 } 5188 setup->sm_keypress_notification = (num_actions << 5) | flags; 5189 sm_trigger_run(); 5190 } 5191 5192 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5193 static void sm_handle_random_result_oob(void * arg){ 5194 UNUSED(arg); 5195 sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM; 5196 sm_trigger_run(); 5197 } 5198 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){ 5199 5200 static btstack_crypto_random_t sm_crypto_random_oob_request; 5201 5202 if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5203 sm_sc_oob_callback = callback; 5204 sm_sc_oob_state = SM_SC_OOB_W4_RANDOM; 5205 btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL); 5206 return 0; 5207 } 5208 #endif 5209 5210 /** 5211 * @brief Get Identity Resolving state 5212 * @param con_handle 5213 * @return irk_lookup_state_t 5214 */ 5215 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){ 5216 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5217 if (!sm_conn) return IRK_LOOKUP_IDLE; 5218 return sm_conn->sm_irk_lookup_state; 5219 } 5220 5221 /** 5222 * @brief Identify device in LE Device DB 5223 * @param handle 5224 * @return index from le_device_db or -1 if not found/identified 5225 */ 5226 int sm_le_device_index(hci_con_handle_t con_handle ){ 5227 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5228 if (!sm_conn) return -1; 5229 return sm_conn->sm_le_db_index; 5230 } 5231 5232 uint8_t sm_get_ltk(hci_con_handle_t con_handle, sm_key_t ltk){ 5233 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 5234 if (hci_connection == NULL){ 5235 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5236 } 5237 if (hci_connection->link_key_type == 0){ 5238 return ERROR_CODE_PIN_OR_KEY_MISSING; 5239 } 5240 memcpy(ltk, hci_connection->link_key, 16); 5241 return ERROR_CODE_SUCCESS; 5242 } 5243 5244 static int gap_random_address_type_requires_updates(void){ 5245 switch (gap_random_adress_type){ 5246 case GAP_RANDOM_ADDRESS_TYPE_OFF: 5247 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 5248 return 0; 5249 default: 5250 return 1; 5251 } 5252 } 5253 5254 static uint8_t own_address_type(void){ 5255 switch (gap_random_adress_type){ 5256 case GAP_RANDOM_ADDRESS_TYPE_OFF: 5257 return BD_ADDR_TYPE_LE_PUBLIC; 5258 default: 5259 return BD_ADDR_TYPE_LE_RANDOM; 5260 } 5261 } 5262 5263 // GAP LE API 5264 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){ 5265 gap_random_address_update_stop(); 5266 gap_random_adress_type = random_address_type; 5267 hci_le_set_own_address_type(own_address_type()); 5268 if (!gap_random_address_type_requires_updates()) return; 5269 gap_random_address_update_start(); 5270 gap_random_address_trigger(); 5271 } 5272 5273 gap_random_address_type_t gap_random_address_get_mode(void){ 5274 return gap_random_adress_type; 5275 } 5276 5277 void gap_random_address_set_update_period(int period_ms){ 5278 gap_random_adress_update_period = period_ms; 5279 if (!gap_random_address_type_requires_updates()) return; 5280 gap_random_address_update_stop(); 5281 gap_random_address_update_start(); 5282 } 5283 5284 void gap_random_address_set(const bd_addr_t addr){ 5285 gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC); 5286 (void)memcpy(sm_random_address, addr, 6); 5287 // assert msb bits are set to '11' 5288 sm_random_address[0] |= 0xc0; 5289 hci_le_random_address_set(sm_random_address); 5290 } 5291 5292 #ifdef ENABLE_LE_PERIPHERAL 5293 /* 5294 * @brief Set Advertisement Paramters 5295 * @param adv_int_min 5296 * @param adv_int_max 5297 * @param adv_type 5298 * @param direct_address_type 5299 * @param direct_address 5300 * @param channel_map 5301 * @param filter_policy 5302 * 5303 * @note own_address_type is used from gap_random_address_set_mode 5304 */ 5305 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 5306 uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){ 5307 hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 5308 direct_address_typ, direct_address, channel_map, filter_policy); 5309 } 5310 #endif 5311 5312 int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){ 5313 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5314 // wrong connection 5315 if (!sm_conn) return 0; 5316 // already encrypted 5317 if (sm_conn->sm_connection_encrypted) return 0; 5318 // irk status? 5319 switch(sm_conn->sm_irk_lookup_state){ 5320 case IRK_LOOKUP_FAILED: 5321 // done, cannot setup encryption 5322 return 0; 5323 case IRK_LOOKUP_SUCCEEDED: 5324 break; 5325 default: 5326 // IR Lookup pending 5327 return 1; 5328 } 5329 // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure 5330 if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0; 5331 if (sm_conn->sm_role){ 5332 return sm_conn->sm_engine_state != SM_RESPONDER_IDLE; 5333 } else { 5334 return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED; 5335 } 5336 } 5337 5338 void sm_set_secure_connections_only_mode(bool enable){ 5339 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5340 sm_sc_only_mode = enable; 5341 #else 5342 // SC Only mode not possible without support for SC 5343 btstack_assert(enable == false); 5344 #endif 5345 } 5346 5347 const uint8_t * gap_get_persistent_irk(void){ 5348 return sm_persistent_irk; 5349 } 5350 5351 void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){ 5352 uint16_t i; 5353 for (i=0; i < le_device_db_max_count(); i++){ 5354 bd_addr_t entry_address; 5355 int entry_address_type = BD_ADDR_TYPE_UNKNOWN; 5356 le_device_db_info(i, &entry_address_type, entry_address, NULL); 5357 // skip unused entries 5358 if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue; 5359 if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){ 5360 sm_remove_le_device_db_entry(i); 5361 break; 5362 } 5363 } 5364 } 5365