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