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(void) { 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 le_device_db_remove(i); 1555 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 1556 // to remove an entry from the resolving list requires its identity address, which was already deleted 1557 // fully reload resolving list instead 1558 gap_load_resolving_list_from_le_device_db(); 1559 #endif 1560 } 1561 1562 static uint8_t sm_key_distribution_validate_received(sm_connection_t * sm_conn){ 1563 // if identity is provided, abort if we have bonding with same address but different irk 1564 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 1565 int index = sm_lookup_by_address(); 1566 if (index >= 0){ 1567 sm_key_t irk; 1568 le_device_db_info(index, NULL, NULL, irk); 1569 if (memcmp(irk, setup->sm_peer_irk, 16) != 0){ 1570 // IRK doesn't match, delete bonding information 1571 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); 1572 sm_remove_le_device_db_entry(index); 1573 } 1574 } 1575 } 1576 return 0; 1577 } 1578 1579 static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){ 1580 1581 // abort pairing if received keys are not valid 1582 uint8_t reason = sm_key_distribution_validate_received(sm_conn); 1583 if (reason != 0){ 1584 sm_pairing_error(sm_conn, reason); 1585 return; 1586 } 1587 1588 // only store pairing information if both sides are bondable, i.e., the bonadble flag is set 1589 bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) 1590 & sm_pairing_packet_get_auth_req(setup->sm_s_pres) 1591 & SM_AUTHREQ_BONDING ) != 0u; 1592 1593 if (bonding_enabled){ 1594 sm_store_bonding_information(sm_conn); 1595 } else { 1596 log_info("Ignoring received keys, bonding not enabled"); 1597 } 1598 } 1599 1600 static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){ 1601 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 1602 } 1603 1604 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1605 1606 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn); 1607 static int sm_passkey_used(stk_generation_method_t method); 1608 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method); 1609 1610 static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){ 1611 if (setup->sm_stk_generation_method == OOB){ 1612 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 1613 } else { 1614 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); 1615 } 1616 } 1617 1618 static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){ 1619 if (IS_RESPONDER(sm_conn->sm_role)){ 1620 // Responder 1621 if (setup->sm_stk_generation_method == OOB){ 1622 // generate Nb 1623 log_info("Generate Nb"); 1624 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); 1625 } else { 1626 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 1627 } 1628 } else { 1629 // Initiator role 1630 switch (setup->sm_stk_generation_method){ 1631 case JUST_WORKS: 1632 sm_sc_prepare_dhkey_check(sm_conn); 1633 break; 1634 1635 case NUMERIC_COMPARISON: 1636 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2; 1637 break; 1638 case PK_INIT_INPUT: 1639 case PK_RESP_INPUT: 1640 case PK_BOTH_INPUT: 1641 if (setup->sm_passkey_bit < 20u) { 1642 sm_sc_start_calculating_local_confirm(sm_conn); 1643 } else { 1644 sm_sc_prepare_dhkey_check(sm_conn); 1645 } 1646 break; 1647 case OOB: 1648 sm_sc_prepare_dhkey_check(sm_conn); 1649 break; 1650 default: 1651 btstack_assert(false); 1652 break; 1653 } 1654 } 1655 } 1656 1657 static void sm_sc_cmac_done(uint8_t * hash){ 1658 log_info("sm_sc_cmac_done: "); 1659 log_info_hexdump(hash, 16); 1660 1661 if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){ 1662 sm_sc_oob_state = SM_SC_OOB_IDLE; 1663 (*sm_sc_oob_callback)(hash, sm_sc_oob_random); 1664 return; 1665 } 1666 1667 sm_connection_t * sm_conn = sm_cmac_connection; 1668 sm_cmac_connection = NULL; 1669 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1670 link_key_type_t link_key_type; 1671 #endif 1672 1673 switch (sm_conn->sm_engine_state){ 1674 case SM_SC_W4_CMAC_FOR_CONFIRMATION: 1675 (void)memcpy(setup->sm_local_confirm, hash, 16); 1676 sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION; 1677 break; 1678 case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION: 1679 // check 1680 if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){ 1681 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED); 1682 break; 1683 } 1684 sm_sc_state_after_receiving_random(sm_conn); 1685 break; 1686 case SM_SC_W4_CALCULATE_G2: { 1687 uint32_t vab = big_endian_read_32(hash, 12) % 1000000; 1688 big_endian_store_32(setup->sm_tk, 12, vab); 1689 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 1690 sm_trigger_user_response(sm_conn); 1691 break; 1692 } 1693 case SM_SC_W4_CALCULATE_F5_SALT: 1694 (void)memcpy(setup->sm_t, hash, 16); 1695 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY; 1696 break; 1697 case SM_SC_W4_CALCULATE_F5_MACKEY: 1698 (void)memcpy(setup->sm_mackey, hash, 16); 1699 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK; 1700 break; 1701 case SM_SC_W4_CALCULATE_F5_LTK: 1702 // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk 1703 // Errata Service Release to the Bluetooth Specification: ESR09 1704 // E6405 – Cross transport key derivation from a key of size less than 128 bits 1705 // Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 1706 (void)memcpy(setup->sm_ltk, hash, 16); 1707 (void)memcpy(setup->sm_local_ltk, hash, 16); 1708 sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size); 1709 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK; 1710 break; 1711 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 1712 (void)memcpy(setup->sm_local_dhkey_check, hash, 16); 1713 if (IS_RESPONDER(sm_conn->sm_role)){ 1714 // responder 1715 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){ 1716 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 1717 } else { 1718 sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 1719 } 1720 } else { 1721 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1722 } 1723 break; 1724 case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 1725 if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){ 1726 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 1727 break; 1728 } 1729 if (IS_RESPONDER(sm_conn->sm_role)){ 1730 // responder 1731 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1732 } else { 1733 // initiator 1734 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 1735 } 1736 break; 1737 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 1738 case SM_SC_W4_CALCULATE_ILK: 1739 (void)memcpy(setup->sm_t, hash, 16); 1740 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY; 1741 break; 1742 case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY: 1743 reverse_128(hash, setup->sm_t); 1744 link_key_type = sm_conn->sm_connection_authenticated ? 1745 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256; 1746 log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type); 1747 gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type); 1748 if (IS_RESPONDER(sm_conn->sm_role)){ 1749 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 1750 } else { 1751 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 1752 } 1753 sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0); 1754 sm_done_for_handle(sm_conn->sm_handle); 1755 break; 1756 case SM_BR_EDR_W4_CALCULATE_ILK: 1757 (void)memcpy(setup->sm_t, hash, 16); 1758 sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK; 1759 break; 1760 case SM_BR_EDR_W4_CALCULATE_LE_LTK: 1761 log_info("Derived LE LTK from BR/EDR Link Key"); 1762 log_info_key("Link Key", hash); 1763 (void)memcpy(setup->sm_ltk, hash, 16); 1764 sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size); 1765 sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256; 1766 sm_store_bonding_information(sm_conn); 1767 sm_done_for_handle(sm_conn->sm_handle); 1768 break; 1769 #endif 1770 default: 1771 log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state); 1772 break; 1773 } 1774 sm_trigger_run(); 1775 } 1776 1777 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){ 1778 const uint16_t message_len = 65; 1779 sm_cmac_connection = sm_conn; 1780 (void)memcpy(sm_cmac_sc_buffer, u, 32); 1781 (void)memcpy(sm_cmac_sc_buffer + 32, v, 32); 1782 sm_cmac_sc_buffer[64] = z; 1783 log_info("f4 key"); 1784 log_info_hexdump(x, 16); 1785 log_info("f4 message"); 1786 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1787 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1788 } 1789 1790 static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 }; 1791 static const uint8_t f5_length[] = { 0x01, 0x00}; 1792 1793 static void f5_calculate_salt(sm_connection_t * sm_conn){ 1794 1795 static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE}; 1796 1797 log_info("f5_calculate_salt"); 1798 // calculate salt for f5 1799 const uint16_t message_len = 32; 1800 sm_cmac_connection = sm_conn; 1801 (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len); 1802 sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1803 } 1804 1805 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){ 1806 const uint16_t message_len = 53; 1807 sm_cmac_connection = sm_conn; 1808 1809 // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey 1810 sm_cmac_sc_buffer[0] = 0; 1811 (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4); 1812 (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16); 1813 (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16); 1814 (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7); 1815 (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7); 1816 (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2); 1817 log_info("f5 key"); 1818 log_info_hexdump(t, 16); 1819 log_info("f5 message for MacKey"); 1820 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1821 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1822 } 1823 1824 static void f5_calculate_mackey(sm_connection_t * sm_conn){ 1825 sm_key56_t bd_addr_master, bd_addr_slave; 1826 bd_addr_master[0] = setup->sm_m_addr_type; 1827 bd_addr_slave[0] = setup->sm_s_addr_type; 1828 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1829 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1830 if (IS_RESPONDER(sm_conn->sm_role)){ 1831 // responder 1832 f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave); 1833 } else { 1834 // initiator 1835 f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave); 1836 } 1837 } 1838 1839 // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused 1840 static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){ 1841 const uint16_t message_len = 53; 1842 sm_cmac_connection = sm_conn; 1843 sm_cmac_sc_buffer[0] = 1; 1844 // 1..52 setup before 1845 log_info("f5 key"); 1846 log_info_hexdump(t, 16); 1847 log_info("f5 message for LTK"); 1848 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1849 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1850 } 1851 1852 static void f5_calculate_ltk(sm_connection_t * sm_conn){ 1853 f5_ltk(sm_conn, setup->sm_t); 1854 } 1855 1856 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){ 1857 (void)memcpy(sm_cmac_sc_buffer, n1, 16); 1858 (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16); 1859 (void)memcpy(sm_cmac_sc_buffer + 32, r, 16); 1860 (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3); 1861 (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7); 1862 (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7); 1863 } 1864 1865 static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){ 1866 const uint16_t message_len = 65; 1867 sm_cmac_connection = sm_conn; 1868 log_info("f6 key"); 1869 log_info_hexdump(w, 16); 1870 log_info("f6 message"); 1871 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1872 sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1873 } 1874 1875 // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32 1876 // - U is 256 bits 1877 // - V is 256 bits 1878 // - X is 128 bits 1879 // - Y is 128 bits 1880 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){ 1881 const uint16_t message_len = 80; 1882 sm_cmac_connection = sm_conn; 1883 (void)memcpy(sm_cmac_sc_buffer, u, 32); 1884 (void)memcpy(sm_cmac_sc_buffer + 32, v, 32); 1885 (void)memcpy(sm_cmac_sc_buffer + 64, y, 16); 1886 log_info("g2 key"); 1887 log_info_hexdump(x, 16); 1888 log_info("g2 message"); 1889 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1890 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1891 } 1892 1893 static void g2_calculate(sm_connection_t * sm_conn) { 1894 // calc Va if numeric comparison 1895 if (IS_RESPONDER(sm_conn->sm_role)){ 1896 // responder 1897 g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);; 1898 } else { 1899 // initiator 1900 g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce); 1901 } 1902 } 1903 1904 static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){ 1905 uint8_t z = 0; 1906 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1907 // some form of passkey 1908 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1909 z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u); 1910 setup->sm_passkey_bit++; 1911 } 1912 f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z); 1913 } 1914 1915 static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){ 1916 // OOB 1917 if (setup->sm_stk_generation_method == OOB){ 1918 if (IS_RESPONDER(sm_conn->sm_role)){ 1919 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0); 1920 } else { 1921 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0); 1922 } 1923 return; 1924 } 1925 1926 uint8_t z = 0; 1927 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1928 // some form of passkey 1929 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1930 // sm_passkey_bit was increased before sending confirm value 1931 z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u); 1932 } 1933 f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z); 1934 } 1935 1936 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){ 1937 log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0); 1938 1939 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){ 1940 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1941 return; 1942 } else { 1943 sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY; 1944 } 1945 } 1946 1947 static void sm_sc_dhkey_calculated(void * arg){ 1948 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 1949 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 1950 if (sm_conn == NULL) return; 1951 1952 log_info("dhkey"); 1953 log_info_hexdump(&setup->sm_dhkey[0], 32); 1954 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED; 1955 // trigger next step 1956 if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){ 1957 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1958 } 1959 sm_trigger_run(); 1960 } 1961 1962 static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){ 1963 // calculate DHKCheck 1964 sm_key56_t bd_addr_master, bd_addr_slave; 1965 bd_addr_master[0] = setup->sm_m_addr_type; 1966 bd_addr_slave[0] = setup->sm_s_addr_type; 1967 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1968 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1969 uint8_t iocap_a[3]; 1970 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1971 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1972 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 1973 uint8_t iocap_b[3]; 1974 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 1975 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 1976 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 1977 if (IS_RESPONDER(sm_conn->sm_role)){ 1978 // responder 1979 f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 1980 f6_engine(sm_conn, setup->sm_mackey); 1981 } else { 1982 // initiator 1983 f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 1984 f6_engine(sm_conn, setup->sm_mackey); 1985 } 1986 } 1987 1988 static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){ 1989 // validate E = f6() 1990 sm_key56_t bd_addr_master, bd_addr_slave; 1991 bd_addr_master[0] = setup->sm_m_addr_type; 1992 bd_addr_slave[0] = setup->sm_s_addr_type; 1993 (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1994 (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1995 1996 uint8_t iocap_a[3]; 1997 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1998 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1999 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 2000 uint8_t iocap_b[3]; 2001 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 2002 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 2003 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 2004 if (IS_RESPONDER(sm_conn->sm_role)){ 2005 // responder 2006 f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 2007 f6_engine(sm_conn, setup->sm_mackey); 2008 } else { 2009 // initiator 2010 f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 2011 f6_engine(sm_conn, setup->sm_mackey); 2012 } 2013 } 2014 2015 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2016 2017 // 2018 // Link Key Conversion Function h6 2019 // 2020 // h6(W, keyID) = AES-CMAC_W(keyID) 2021 // - W is 128 bits 2022 // - keyID is 32 bits 2023 static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){ 2024 const uint16_t message_len = 4; 2025 sm_cmac_connection = sm_conn; 2026 big_endian_store_32(sm_cmac_sc_buffer, 0, key_id); 2027 log_info("h6 key"); 2028 log_info_hexdump(w, 16); 2029 log_info("h6 message"); 2030 log_info_hexdump(sm_cmac_sc_buffer, message_len); 2031 sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 2032 } 2033 // 2034 // Link Key Conversion Function h7 2035 // 2036 // h7(SALT, W) = AES-CMAC_SALT(W) 2037 // - SALT is 128 bits 2038 // - W is 128 bits 2039 static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) { 2040 const uint16_t message_len = 16; 2041 sm_cmac_connection = sm_conn; 2042 log_info("h7 key"); 2043 log_info_hexdump(salt, 16); 2044 log_info("h7 message"); 2045 log_info_hexdump(w, 16); 2046 sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done); 2047 } 2048 2049 // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated) 2050 // Errata Service Release to the Bluetooth Specification: ESR09 2051 // E6405 – Cross transport key derivation from a key of size less than 128 bits 2052 // "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 2053 2054 static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){ 2055 h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031); // "tmp1" 2056 } 2057 2058 static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){ 2059 h6_engine(sm_conn, setup->sm_link_key, 0x746D7032); // "tmp2" 2060 } 2061 2062 static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){ 2063 h6_engine(sm_conn, setup->sm_t, 0x6c656272); // "lebr" 2064 } 2065 2066 static void h6_calculate_le_ltk(sm_connection_t * sm_conn){ 2067 h6_engine(sm_conn, setup->sm_t, 0x62726C65); // "brle" 2068 } 2069 2070 static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){ 2071 const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31}; // "tmp1" 2072 h7_engine(sm_conn, salt, setup->sm_local_ltk); 2073 } 2074 2075 static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){ 2076 const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32}; // "tmp2" 2077 h7_engine(sm_conn, salt, setup->sm_link_key); 2078 } 2079 2080 static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){ 2081 hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle); 2082 btstack_assert(hci_connection != NULL); 2083 reverse_128(hci_connection->link_key, setup->sm_link_key); 2084 setup->sm_link_key_type = hci_connection->link_key_type; 2085 } 2086 2087 static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){ 2088 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; 2089 connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6; 2090 } 2091 2092 #endif 2093 2094 #endif 2095 2096 // key management legacy connections: 2097 // - potentially two different LTKs based on direction. each device stores LTK provided by peer 2098 // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect) 2099 // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder 2100 // - responder reconnects: responder uses LTK receveived from master 2101 2102 // key management secure connections: 2103 // - both devices store same LTK from ECDH key exchange. 2104 2105 #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL) 2106 static void sm_load_security_info(sm_connection_t * sm_connection){ 2107 int encryption_key_size; 2108 int authenticated; 2109 int authorized; 2110 int secure_connection; 2111 2112 // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled 2113 le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk, 2114 &encryption_key_size, &authenticated, &authorized, &secure_connection); 2115 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); 2116 sm_connection->sm_actual_encryption_key_size = encryption_key_size; 2117 sm_connection->sm_connection_authenticated = authenticated; 2118 sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN; 2119 sm_connection->sm_connection_sc = secure_connection; 2120 } 2121 #endif 2122 2123 #ifdef ENABLE_LE_PERIPHERAL 2124 static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){ 2125 (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8); 2126 setup->sm_local_ediv = sm_connection->sm_local_ediv; 2127 // re-establish used key encryption size 2128 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 2129 sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u; 2130 // no db for authenticated flag hack: flag is stored in bit 4 of LSB 2131 sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u; 2132 // Legacy paring -> not SC 2133 sm_connection->sm_connection_sc = 0; 2134 log_info("sm: received ltk request with key size %u, authenticated %u", 2135 sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated); 2136 } 2137 #endif 2138 2139 // distributed key generation 2140 static bool sm_run_dpkg(void){ 2141 switch (dkg_state){ 2142 case DKG_CALC_IRK: 2143 // already busy? 2144 if (sm_aes128_state == SM_AES128_IDLE) { 2145 log_info("DKG_CALC_IRK started"); 2146 // IRK = d1(IR, 1, 0) 2147 sm_d1_d_prime(1, 0, sm_aes128_plaintext); // plaintext = d1 prime 2148 sm_aes128_state = SM_AES128_ACTIVE; 2149 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_irk, sm_handle_encryption_result_dkg_irk, NULL); 2150 return true; 2151 } 2152 break; 2153 case DKG_CALC_DHK: 2154 // already busy? 2155 if (sm_aes128_state == SM_AES128_IDLE) { 2156 log_info("DKG_CALC_DHK started"); 2157 // DHK = d1(IR, 3, 0) 2158 sm_d1_d_prime(3, 0, sm_aes128_plaintext); // plaintext = d1 prime 2159 sm_aes128_state = SM_AES128_ACTIVE; 2160 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_dhk, sm_handle_encryption_result_dkg_dhk, NULL); 2161 return true; 2162 } 2163 break; 2164 default: 2165 break; 2166 } 2167 return false; 2168 } 2169 2170 // random address updates 2171 static bool sm_run_rau(void){ 2172 switch (rau_state){ 2173 case RAU_GET_RANDOM: 2174 rau_state = RAU_W4_RANDOM; 2175 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL); 2176 return true; 2177 case RAU_GET_ENC: 2178 // already busy? 2179 if (sm_aes128_state == SM_AES128_IDLE) { 2180 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext); 2181 sm_aes128_state = SM_AES128_ACTIVE; 2182 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL); 2183 return true; 2184 } 2185 break; 2186 default: 2187 break; 2188 } 2189 return false; 2190 } 2191 2192 // CSRK Lookup 2193 static bool sm_run_csrk(void){ 2194 btstack_linked_list_iterator_t it; 2195 2196 // -- if csrk lookup ready, find connection that require csrk lookup 2197 if (sm_address_resolution_idle()){ 2198 hci_connections_get_iterator(&it); 2199 while(btstack_linked_list_iterator_has_next(&it)){ 2200 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2201 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2202 if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){ 2203 // and start lookup 2204 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); 2205 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED; 2206 break; 2207 } 2208 } 2209 } 2210 2211 // -- if csrk lookup ready, resolved addresses for received addresses 2212 if (sm_address_resolution_idle()) { 2213 if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){ 2214 sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue; 2215 btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry); 2216 sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL); 2217 btstack_memory_sm_lookup_entry_free(entry); 2218 } 2219 } 2220 2221 // -- Continue with device lookup by public or resolvable private address 2222 if (!sm_address_resolution_idle()){ 2223 while (sm_address_resolution_test < le_device_db_max_count()){ 2224 int addr_type = BD_ADDR_TYPE_UNKNOWN; 2225 bd_addr_t addr; 2226 sm_key_t irk; 2227 le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk); 2228 2229 // skip unused entries 2230 if (addr_type == BD_ADDR_TYPE_UNKNOWN){ 2231 sm_address_resolution_test++; 2232 continue; 2233 } 2234 2235 log_info("LE Device Lookup: device %u of %u", sm_address_resolution_test, le_device_db_max_count()); 2236 2237 if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){ 2238 log_info("LE Device Lookup: found by { addr_type, address} "); 2239 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED); 2240 break; 2241 } 2242 2243 // if connection type is public, it must be a different one 2244 if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){ 2245 sm_address_resolution_test++; 2246 continue; 2247 } 2248 2249 // skip AH if no IRK 2250 if (sm_is_null_key(irk)){ 2251 sm_address_resolution_test++; 2252 continue; 2253 } 2254 2255 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2256 2257 log_info("LE Device Lookup: calculate AH"); 2258 log_info_key("IRK", irk); 2259 2260 (void)memcpy(sm_aes128_key, irk, 16); 2261 sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext); 2262 sm_address_resolution_ah_calculation_active = 1; 2263 sm_aes128_state = SM_AES128_ACTIVE; 2264 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL); 2265 return true; 2266 } 2267 2268 if (sm_address_resolution_test >= le_device_db_max_count()){ 2269 log_info("LE Device Lookup: not found"); 2270 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED); 2271 } 2272 } 2273 return false; 2274 } 2275 2276 // SC OOB 2277 static bool sm_run_oob(void){ 2278 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2279 switch (sm_sc_oob_state){ 2280 case SM_SC_OOB_W2_CALC_CONFIRM: 2281 if (!sm_cmac_ready()) break; 2282 sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM; 2283 f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0); 2284 return true; 2285 default: 2286 break; 2287 } 2288 #endif 2289 return false; 2290 } 2291 2292 static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){ 2293 l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size); 2294 } 2295 2296 // handle basic actions that don't requires the full context 2297 static bool sm_run_basic(void){ 2298 btstack_linked_list_iterator_t it; 2299 hci_connections_get_iterator(&it); 2300 while(btstack_linked_list_iterator_has_next(&it)){ 2301 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2302 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2303 switch(sm_connection->sm_engine_state){ 2304 2305 // general 2306 case SM_GENERAL_SEND_PAIRING_FAILED: { 2307 uint8_t buffer[2]; 2308 buffer[0] = SM_CODE_PAIRING_FAILED; 2309 buffer[1] = sm_connection->sm_pairing_failed_reason; 2310 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 2311 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer)); 2312 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason); 2313 sm_done_for_handle(sm_connection->sm_handle); 2314 break; 2315 } 2316 2317 // responder side 2318 case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY: 2319 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 2320 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 2321 return true; 2322 2323 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2324 case SM_SC_RECEIVED_LTK_REQUEST: 2325 switch (sm_connection->sm_irk_lookup_state){ 2326 case IRK_LOOKUP_FAILED: 2327 log_info("LTK Request: IRK Lookup Failed)"); 2328 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 2329 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 2330 return true; 2331 default: 2332 break; 2333 } 2334 break; 2335 #endif 2336 default: 2337 break; 2338 } 2339 } 2340 return false; 2341 } 2342 2343 static void sm_run_activate_connection(void){ 2344 // Find connections that requires setup context and make active if no other is locked 2345 btstack_linked_list_iterator_t it; 2346 hci_connections_get_iterator(&it); 2347 while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){ 2348 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2349 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2350 // - if no connection locked and we're ready/waiting for setup context, fetch it and start 2351 bool done = true; 2352 int err; 2353 UNUSED(err); 2354 2355 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2356 // assert ec key is ready 2357 if ( (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED) 2358 || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST) 2359 || (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){ 2360 if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){ 2361 sm_ec_generate_new_key(); 2362 } 2363 if (ec_key_generation_state != EC_KEY_GENERATION_DONE){ 2364 continue; 2365 } 2366 } 2367 #endif 2368 2369 switch (sm_connection->sm_engine_state) { 2370 #ifdef ENABLE_LE_PERIPHERAL 2371 case SM_RESPONDER_SEND_SECURITY_REQUEST: 2372 case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED: 2373 case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST: 2374 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2375 case SM_SC_RECEIVED_LTK_REQUEST: 2376 #endif 2377 #endif 2378 #ifdef ENABLE_LE_CENTRAL 2379 case SM_INITIATOR_PH4_HAS_LTK: 2380 case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST: 2381 #endif 2382 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2383 case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED: 2384 case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST: 2385 #endif 2386 // just lock context 2387 break; 2388 default: 2389 done = false; 2390 break; 2391 } 2392 if (done){ 2393 sm_active_connection_handle = sm_connection->sm_handle; 2394 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); 2395 } 2396 } 2397 } 2398 2399 static void sm_run_send_keypress_notification(sm_connection_t * connection){ 2400 int i; 2401 uint8_t flags = setup->sm_keypress_notification & 0x1fu; 2402 uint8_t num_actions = setup->sm_keypress_notification >> 5; 2403 uint8_t action = 0; 2404 for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){ 2405 if (flags & (1u<<i)){ 2406 bool clear_flag = true; 2407 switch (i){ 2408 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 2409 case SM_KEYPRESS_PASSKEY_CLEARED: 2410 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 2411 default: 2412 break; 2413 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 2414 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 2415 num_actions--; 2416 clear_flag = num_actions == 0u; 2417 break; 2418 } 2419 if (clear_flag){ 2420 flags &= ~(1<<i); 2421 } 2422 action = i; 2423 break; 2424 } 2425 } 2426 setup->sm_keypress_notification = (num_actions << 5) | flags; 2427 2428 // send keypress notification 2429 uint8_t buffer[2]; 2430 buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION; 2431 buffer[1] = action; 2432 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2433 2434 // try 2435 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid); 2436 } 2437 2438 static void sm_run_distribute_keys(sm_connection_t * connection){ 2439 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){ 2440 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2441 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2442 uint8_t buffer[17]; 2443 buffer[0] = SM_CODE_ENCRYPTION_INFORMATION; 2444 reverse_128(setup->sm_ltk, &buffer[1]); 2445 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2446 sm_timeout_reset(connection); 2447 return; 2448 } 2449 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){ 2450 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2451 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2452 uint8_t buffer[11]; 2453 buffer[0] = SM_CODE_MASTER_IDENTIFICATION; 2454 little_endian_store_16(buffer, 1, setup->sm_local_ediv); 2455 reverse_64(setup->sm_local_rand, &buffer[3]); 2456 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2457 sm_timeout_reset(connection); 2458 return; 2459 } 2460 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 2461 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2462 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2463 uint8_t buffer[17]; 2464 buffer[0] = SM_CODE_IDENTITY_INFORMATION; 2465 reverse_128(sm_persistent_irk, &buffer[1]); 2466 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2467 sm_timeout_reset(connection); 2468 return; 2469 } 2470 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){ 2471 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2472 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2473 bd_addr_t local_address; 2474 uint8_t buffer[8]; 2475 buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION; 2476 switch (gap_random_address_get_mode()){ 2477 case GAP_RANDOM_ADDRESS_TYPE_OFF: 2478 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 2479 // public or static random 2480 gap_le_get_own_address(&buffer[1], local_address); 2481 break; 2482 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 2483 case GAP_RANDOM_ADDRESS_RESOLVABLE: 2484 // fallback to public 2485 gap_local_bd_addr(local_address); 2486 buffer[1] = 0; 2487 break; 2488 default: 2489 btstack_assert(false); 2490 break; 2491 } 2492 reverse_bd_addr(local_address, &buffer[2]); 2493 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2494 sm_timeout_reset(connection); 2495 return; 2496 } 2497 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 2498 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2499 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2500 2501 #ifdef ENABLE_LE_SIGNED_WRITE 2502 // hack to reproduce test runs 2503 if (test_use_fixed_local_csrk){ 2504 memset(setup->sm_local_csrk, 0xcc, 16); 2505 } 2506 2507 // store local CSRK 2508 if (setup->sm_le_device_index >= 0){ 2509 log_info("sm: store local CSRK"); 2510 le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk); 2511 le_device_db_local_counter_set(setup->sm_le_device_index, 0); 2512 } 2513 #endif 2514 2515 uint8_t buffer[17]; 2516 buffer[0] = SM_CODE_SIGNING_INFORMATION; 2517 reverse_128(setup->sm_local_csrk, &buffer[1]); 2518 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2519 sm_timeout_reset(connection); 2520 return; 2521 } 2522 btstack_assert(false); 2523 } 2524 2525 static bool sm_ctkd_from_le(sm_connection_t *sm_connection) { 2526 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 2527 // requirements to derive link key from LE: 2528 // - use secure connections 2529 if (setup->sm_use_secure_connections == 0) return false; 2530 // - bonding needs to be enabled: 2531 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; 2532 if (!bonding_enabled) return false; 2533 // - need identity address / public addr 2534 bool have_identity_address_info = ((setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION) != 0) || (setup->sm_peer_addr_type == 0); 2535 if (!have_identity_address_info) return false; 2536 // - 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) 2537 // this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all. 2538 // If SC is authenticated, we consider it safe to overwrite a stored key. 2539 // 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. 2540 uint8_t link_key[16]; 2541 link_key_type_t link_key_type; 2542 bool have_link_key = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type); 2543 bool link_key_authenticated = gap_authenticated_for_link_key_type(link_key_type); 2544 bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0; 2545 if (have_link_key && link_key_authenticated && !derived_key_authenticated) { 2546 return false; 2547 } 2548 // get started (all of the above are true) 2549 return true; 2550 #else 2551 UNUSED(sm_connection); 2552 return false; 2553 #endif 2554 } 2555 2556 static void sm_key_distribution_complete_responder(sm_connection_t * connection){ 2557 if (sm_ctkd_from_le(connection)){ 2558 bool use_h7 = (sm_pairing_packet_get_auth_req(setup->sm_m_preq) & sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_CT2) != 0; 2559 connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6; 2560 } else { 2561 connection->sm_engine_state = SM_RESPONDER_IDLE; 2562 sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0); 2563 sm_done_for_handle(connection->sm_handle); 2564 } 2565 } 2566 2567 static void sm_key_distribution_complete_initiator(sm_connection_t * connection){ 2568 if (sm_ctkd_from_le(connection)){ 2569 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; 2570 connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6; 2571 } else { 2572 sm_master_pairing_success(connection); 2573 } 2574 } 2575 2576 static void sm_run(void){ 2577 2578 // assert that stack has already bootet 2579 if (hci_get_state() != HCI_STATE_WORKING) return; 2580 2581 // assert that we can send at least commands 2582 if (!hci_can_send_command_packet_now()) return; 2583 2584 // pause until IR/ER are ready 2585 if (sm_persistent_keys_random_active) return; 2586 2587 bool done; 2588 2589 // 2590 // non-connection related behaviour 2591 // 2592 2593 done = sm_run_dpkg(); 2594 if (done) return; 2595 2596 done = sm_run_rau(); 2597 if (done) return; 2598 2599 done = sm_run_csrk(); 2600 if (done) return; 2601 2602 done = sm_run_oob(); 2603 if (done) return; 2604 2605 // assert that we can send at least commands - cmd might have been sent by crypto engine 2606 if (!hci_can_send_command_packet_now()) return; 2607 2608 // handle basic actions that don't requires the full context 2609 done = sm_run_basic(); 2610 if (done) return; 2611 2612 // 2613 // active connection handling 2614 // -- use loop to handle next connection if lock on setup context is released 2615 2616 while (true) { 2617 2618 sm_run_activate_connection(); 2619 2620 if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return; 2621 2622 // 2623 // active connection handling 2624 // 2625 2626 sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle); 2627 if (!connection) { 2628 log_info("no connection for handle 0x%04x", sm_active_connection_handle); 2629 return; 2630 } 2631 2632 // assert that we could send a SM PDU - not needed for all of the following 2633 if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) { 2634 log_info("cannot send now, requesting can send now event"); 2635 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid); 2636 return; 2637 } 2638 2639 // send keypress notifications 2640 if (setup->sm_keypress_notification){ 2641 sm_run_send_keypress_notification(connection); 2642 return; 2643 } 2644 2645 int key_distribution_flags; 2646 UNUSED(key_distribution_flags); 2647 #ifdef ENABLE_LE_PERIPHERAL 2648 int err; 2649 bool have_ltk; 2650 uint8_t ltk[16]; 2651 #endif 2652 2653 log_info("sm_run: state %u", connection->sm_engine_state); 2654 if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) { 2655 log_info("sm_run // cannot send"); 2656 } 2657 switch (connection->sm_engine_state){ 2658 2659 // secure connections, initiator + responding states 2660 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2661 case SM_SC_W2_CMAC_FOR_CONFIRMATION: 2662 if (!sm_cmac_ready()) break; 2663 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION; 2664 sm_sc_calculate_local_confirm(connection); 2665 break; 2666 case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION: 2667 if (!sm_cmac_ready()) break; 2668 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION; 2669 sm_sc_calculate_remote_confirm(connection); 2670 break; 2671 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 2672 if (!sm_cmac_ready()) break; 2673 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK; 2674 sm_sc_calculate_f6_for_dhkey_check(connection); 2675 break; 2676 case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 2677 if (!sm_cmac_ready()) break; 2678 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 2679 sm_sc_calculate_f6_to_verify_dhkey_check(connection); 2680 break; 2681 case SM_SC_W2_CALCULATE_F5_SALT: 2682 if (!sm_cmac_ready()) break; 2683 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT; 2684 f5_calculate_salt(connection); 2685 break; 2686 case SM_SC_W2_CALCULATE_F5_MACKEY: 2687 if (!sm_cmac_ready()) break; 2688 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY; 2689 f5_calculate_mackey(connection); 2690 break; 2691 case SM_SC_W2_CALCULATE_F5_LTK: 2692 if (!sm_cmac_ready()) break; 2693 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK; 2694 f5_calculate_ltk(connection); 2695 break; 2696 case SM_SC_W2_CALCULATE_G2: 2697 if (!sm_cmac_ready()) break; 2698 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2; 2699 g2_calculate(connection); 2700 break; 2701 #endif 2702 2703 #ifdef ENABLE_LE_CENTRAL 2704 // initiator side 2705 2706 case SM_INITIATOR_PH4_HAS_LTK: { 2707 sm_reset_setup(); 2708 sm_load_security_info(connection); 2709 sm_reencryption_started(connection); 2710 2711 sm_key_t peer_ltk_flipped; 2712 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped); 2713 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED; 2714 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv); 2715 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0); 2716 uint32_t rand_low = big_endian_read_32(setup->sm_peer_rand, 4); 2717 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped); 2718 return; 2719 } 2720 2721 case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST: 2722 sm_reset_setup(); 2723 sm_init_setup(connection); 2724 sm_timeout_start(connection); 2725 sm_pairing_started(connection); 2726 2727 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST); 2728 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE; 2729 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t)); 2730 sm_timeout_reset(connection); 2731 break; 2732 #endif 2733 2734 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2735 2736 case SM_SC_SEND_PUBLIC_KEY_COMMAND: { 2737 bool trigger_user_response = false; 2738 bool trigger_start_calculating_local_confirm = false; 2739 uint8_t buffer[65]; 2740 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY; 2741 // 2742 reverse_256(&ec_q[0], &buffer[1]); 2743 reverse_256(&ec_q[32], &buffer[33]); 2744 2745 #ifdef ENABLE_TESTING_SUPPORT 2746 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){ 2747 log_info("testing_support: invalidating public key"); 2748 // flip single bit of public key coordinate 2749 buffer[1] ^= 1; 2750 } 2751 #endif 2752 2753 // stk generation method 2754 // passkey entry: notify app to show passkey or to request passkey 2755 switch (setup->sm_stk_generation_method){ 2756 case JUST_WORKS: 2757 case NUMERIC_COMPARISON: 2758 if (IS_RESPONDER(connection->sm_role)){ 2759 // responder 2760 trigger_start_calculating_local_confirm = true; 2761 connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE; 2762 } else { 2763 // initiator 2764 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2765 } 2766 break; 2767 case PK_INIT_INPUT: 2768 case PK_RESP_INPUT: 2769 case PK_BOTH_INPUT: 2770 // use random TK for display 2771 (void)memcpy(setup->sm_ra, setup->sm_tk, 16); 2772 (void)memcpy(setup->sm_rb, setup->sm_tk, 16); 2773 setup->sm_passkey_bit = 0; 2774 2775 if (IS_RESPONDER(connection->sm_role)){ 2776 // responder 2777 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2778 } else { 2779 // initiator 2780 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2781 } 2782 trigger_user_response = true; 2783 break; 2784 case OOB: 2785 if (IS_RESPONDER(connection->sm_role)){ 2786 // responder 2787 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2788 } else { 2789 // initiator 2790 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2791 } 2792 break; 2793 default: 2794 btstack_assert(false); 2795 break; 2796 } 2797 2798 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2799 sm_timeout_reset(connection); 2800 2801 // trigger user response and calc confirm after sending pdu 2802 if (trigger_user_response){ 2803 sm_trigger_user_response(connection); 2804 } 2805 if (trigger_start_calculating_local_confirm){ 2806 sm_sc_start_calculating_local_confirm(connection); 2807 } 2808 break; 2809 } 2810 case SM_SC_SEND_CONFIRMATION: { 2811 uint8_t buffer[17]; 2812 buffer[0] = SM_CODE_PAIRING_CONFIRM; 2813 reverse_128(setup->sm_local_confirm, &buffer[1]); 2814 if (IS_RESPONDER(connection->sm_role)){ 2815 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2816 } else { 2817 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2818 } 2819 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2820 sm_timeout_reset(connection); 2821 break; 2822 } 2823 case SM_SC_SEND_PAIRING_RANDOM: { 2824 uint8_t buffer[17]; 2825 buffer[0] = SM_CODE_PAIRING_RANDOM; 2826 reverse_128(setup->sm_local_nonce, &buffer[1]); 2827 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit); 2828 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){ 2829 log_info("SM_SC_SEND_PAIRING_RANDOM A"); 2830 if (IS_RESPONDER(connection->sm_role)){ 2831 // responder 2832 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2833 } else { 2834 // initiator 2835 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2836 } 2837 } else { 2838 log_info("SM_SC_SEND_PAIRING_RANDOM B"); 2839 if (IS_RESPONDER(connection->sm_role)){ 2840 // responder 2841 if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){ 2842 log_info("SM_SC_SEND_PAIRING_RANDOM B1"); 2843 connection->sm_engine_state = SM_SC_W2_CALCULATE_G2; 2844 } else { 2845 log_info("SM_SC_SEND_PAIRING_RANDOM B2"); 2846 sm_sc_prepare_dhkey_check(connection); 2847 } 2848 } else { 2849 // initiator 2850 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2851 } 2852 } 2853 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2854 sm_timeout_reset(connection); 2855 break; 2856 } 2857 case SM_SC_SEND_DHKEY_CHECK_COMMAND: { 2858 uint8_t buffer[17]; 2859 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK; 2860 reverse_128(setup->sm_local_dhkey_check, &buffer[1]); 2861 2862 if (IS_RESPONDER(connection->sm_role)){ 2863 connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC; 2864 } else { 2865 connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 2866 } 2867 2868 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 2869 sm_timeout_reset(connection); 2870 break; 2871 } 2872 2873 #endif 2874 2875 #ifdef ENABLE_LE_PERIPHERAL 2876 2877 case SM_RESPONDER_SEND_SECURITY_REQUEST: { 2878 const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req}; 2879 connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST; 2880 sm_send_connectionless(connection, (uint8_t *) buffer, sizeof(buffer)); 2881 sm_timeout_start(connection); 2882 break; 2883 } 2884 2885 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2886 case SM_SC_RECEIVED_LTK_REQUEST: 2887 switch (connection->sm_irk_lookup_state){ 2888 case IRK_LOOKUP_SUCCEEDED: 2889 // assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null 2890 // start using context by loading security info 2891 sm_reset_setup(); 2892 sm_load_security_info(connection); 2893 if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){ 2894 (void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16); 2895 connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 2896 sm_reencryption_started(connection); 2897 sm_trigger_run(); 2898 break; 2899 } 2900 log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)"); 2901 connection->sm_engine_state = SM_RESPONDER_IDLE; 2902 hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle); 2903 return; 2904 default: 2905 // just wait until IRK lookup is completed 2906 break; 2907 } 2908 break; 2909 #endif /* ENABLE_LE_SECURE_CONNECTIONS */ 2910 2911 case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED: 2912 sm_reset_setup(); 2913 2914 // handle Pairing Request with LTK available 2915 switch (connection->sm_irk_lookup_state) { 2916 case IRK_LOOKUP_SUCCEEDED: 2917 le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 2918 have_ltk = !sm_is_null_key(ltk); 2919 if (have_ltk){ 2920 log_info("pairing request but LTK available"); 2921 // emit re-encryption start/fail sequence 2922 sm_reencryption_started(connection); 2923 sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING); 2924 } 2925 break; 2926 default: 2927 break; 2928 } 2929 2930 sm_init_setup(connection); 2931 sm_pairing_started(connection); 2932 2933 // recover pairing request 2934 (void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t)); 2935 err = sm_stk_generation_init(connection); 2936 2937 #ifdef ENABLE_TESTING_SUPPORT 2938 if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){ 2939 log_info("testing_support: respond with pairing failure %u", test_pairing_failure); 2940 err = test_pairing_failure; 2941 } 2942 #endif 2943 if (err != 0){ 2944 sm_pairing_error(connection, err); 2945 sm_trigger_run(); 2946 break; 2947 } 2948 2949 sm_timeout_start(connection); 2950 2951 // generate random number first, if we need to show passkey, otherwise send response 2952 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 2953 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph2_tk, (void *)(uintptr_t) connection->sm_handle); 2954 break; 2955 } 2956 2957 /* fall through */ 2958 2959 case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE: 2960 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE); 2961 2962 // start with initiator key dist flags 2963 key_distribution_flags = sm_key_distribution_flags_for_auth_req(); 2964 2965 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2966 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection 2967 if (setup->sm_use_secure_connections){ 2968 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY; 2969 } 2970 #endif 2971 // setup in response 2972 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); 2973 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); 2974 2975 // update key distribution after ENC was dropped 2976 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)); 2977 2978 if (setup->sm_use_secure_connections){ 2979 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2980 } else { 2981 connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM; 2982 } 2983 2984 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t)); 2985 sm_timeout_reset(connection); 2986 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 2987 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){ 2988 sm_trigger_user_response(connection); 2989 } 2990 return; 2991 #endif 2992 2993 case SM_PH2_SEND_PAIRING_RANDOM: { 2994 uint8_t buffer[17]; 2995 buffer[0] = SM_CODE_PAIRING_RANDOM; 2996 reverse_128(setup->sm_local_random, &buffer[1]); 2997 if (IS_RESPONDER(connection->sm_role)){ 2998 connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST; 2999 } else { 3000 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM; 3001 } 3002 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 3003 sm_timeout_reset(connection); 3004 break; 3005 } 3006 3007 case SM_PH2_C1_GET_ENC_A: 3008 // already busy? 3009 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3010 // calculate confirm using aes128 engine - step 1 3011 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); 3012 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A; 3013 sm_aes128_state = SM_AES128_ACTIVE; 3014 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); 3015 break; 3016 3017 case SM_PH2_C1_GET_ENC_C: 3018 // already busy? 3019 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3020 // calculate m_confirm using aes128 engine - step 1 3021 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); 3022 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C; 3023 sm_aes128_state = SM_AES128_ACTIVE; 3024 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); 3025 break; 3026 3027 case SM_PH2_CALC_STK: 3028 // already busy? 3029 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3030 // calculate STK 3031 if (IS_RESPONDER(connection->sm_role)){ 3032 sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext); 3033 } else { 3034 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 3035 } 3036 connection->sm_engine_state = SM_PH2_W4_STK; 3037 sm_aes128_state = SM_AES128_ACTIVE; 3038 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); 3039 break; 3040 3041 case SM_PH3_Y_GET_ENC: 3042 // already busy? 3043 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3044 // PH3B2 - calculate Y from - enc 3045 3046 // dm helper (was sm_dm_r_prime) 3047 // r' = padding || r 3048 // r - 64 bit value 3049 memset(&sm_aes128_plaintext[0], 0, 8); 3050 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 3051 3052 // Y = dm(DHK, Rand) 3053 connection->sm_engine_state = SM_PH3_Y_W4_ENC; 3054 sm_aes128_state = SM_AES128_ACTIVE; 3055 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); 3056 break; 3057 3058 case SM_PH2_C1_SEND_PAIRING_CONFIRM: { 3059 uint8_t buffer[17]; 3060 buffer[0] = SM_CODE_PAIRING_CONFIRM; 3061 reverse_128(setup->sm_local_confirm, &buffer[1]); 3062 if (IS_RESPONDER(connection->sm_role)){ 3063 connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM; 3064 } else { 3065 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM; 3066 } 3067 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer)); 3068 sm_timeout_reset(connection); 3069 return; 3070 } 3071 #ifdef ENABLE_LE_PERIPHERAL 3072 case SM_RESPONDER_PH2_SEND_LTK_REPLY: { 3073 sm_key_t stk_flipped; 3074 reverse_128(setup->sm_ltk, stk_flipped); 3075 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 3076 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped); 3077 return; 3078 } 3079 case SM_RESPONDER_PH4_SEND_LTK_REPLY: { 3080 // allow to override LTK 3081 if (sm_get_ltk_callback != NULL){ 3082 (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk); 3083 } 3084 sm_key_t ltk_flipped; 3085 reverse_128(setup->sm_ltk, ltk_flipped); 3086 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED; 3087 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped); 3088 return; 3089 } 3090 3091 case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST: 3092 // already busy? 3093 if (sm_aes128_state == SM_AES128_ACTIVE) break; 3094 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv); 3095 3096 sm_reset_setup(); 3097 sm_start_calculating_ltk_from_ediv_and_rand(connection); 3098 3099 sm_reencryption_started(connection); 3100 3101 // dm helper (was sm_dm_r_prime) 3102 // r' = padding || r 3103 // r - 64 bit value 3104 memset(&sm_aes128_plaintext[0], 0, 8); 3105 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 3106 3107 // Y = dm(DHK, Rand) 3108 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC; 3109 sm_aes128_state = SM_AES128_ACTIVE; 3110 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); 3111 return; 3112 #endif 3113 #ifdef ENABLE_LE_CENTRAL 3114 case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: { 3115 sm_key_t stk_flipped; 3116 reverse_128(setup->sm_ltk, stk_flipped); 3117 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 3118 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped); 3119 return; 3120 } 3121 #endif 3122 3123 case SM_PH3_DISTRIBUTE_KEYS: 3124 // send next key 3125 if (setup->sm_key_distribution_send_set != 0){ 3126 sm_run_distribute_keys(connection); 3127 } 3128 3129 // more to send? 3130 if (setup->sm_key_distribution_send_set != 0){ 3131 return; 3132 } 3133 3134 // keys are sent 3135 if (IS_RESPONDER(connection->sm_role)){ 3136 // slave -> receive master keys if any 3137 if (sm_key_distribution_all_received()){ 3138 sm_key_distribution_handle_all_received(connection); 3139 sm_key_distribution_complete_responder(connection); 3140 // start CTKD right away 3141 continue; 3142 } else { 3143 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3144 } 3145 } else { 3146 sm_master_pairing_success(connection); 3147 } 3148 break; 3149 3150 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3151 case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST: 3152 // fill in sm setup (lite version of sm_init_setup) 3153 sm_reset_setup(); 3154 setup->sm_peer_addr_type = connection->sm_peer_addr_type; 3155 setup->sm_m_addr_type = connection->sm_peer_addr_type; 3156 setup->sm_s_addr_type = connection->sm_own_addr_type; 3157 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6); 3158 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6); 3159 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6); 3160 setup->sm_use_secure_connections = true; 3161 sm_ctkd_fetch_br_edr_link_key(connection); 3162 3163 // Enc Key and IRK if requested 3164 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY; 3165 #ifdef ENABLE_LE_SIGNED_WRITE 3166 // Plus signing key if supported 3167 key_distribution_flags |= SM_KEYDIST_ID_KEY; 3168 #endif 3169 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST); 3170 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0); 3171 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0); 3172 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2); 3173 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size); 3174 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags); 3175 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags); 3176 3177 // set state and send pairing response 3178 sm_timeout_start(connection); 3179 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE; 3180 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t)); 3181 break; 3182 3183 case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED: 3184 // fill in sm setup (lite version of sm_init_setup) 3185 sm_reset_setup(); 3186 setup->sm_peer_addr_type = connection->sm_peer_addr_type; 3187 setup->sm_m_addr_type = connection->sm_peer_addr_type; 3188 setup->sm_s_addr_type = connection->sm_own_addr_type; 3189 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6); 3190 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6); 3191 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6); 3192 setup->sm_use_secure_connections = true; 3193 sm_ctkd_fetch_br_edr_link_key(connection); 3194 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t)); 3195 3196 // Enc Key and IRK if requested 3197 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY; 3198 #ifdef ENABLE_LE_SIGNED_WRITE 3199 // Plus signing key if supported 3200 key_distribution_flags |= SM_KEYDIST_ID_KEY; 3201 #endif 3202 // drop flags not requested by initiator 3203 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq); 3204 3205 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use: 3206 // - the IO Capability field, 3207 // - the OOB data flag field, and 3208 // - all bits in the Auth Req field except the CT2 bit. 3209 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE); 3210 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0); 3211 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0); 3212 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2); 3213 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size); 3214 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags); 3215 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags); 3216 3217 // configure key distribution, LTK is derived locally 3218 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY; 3219 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags); 3220 3221 // set state and send pairing response 3222 sm_timeout_start(connection); 3223 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 3224 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t)); 3225 break; 3226 case SM_BR_EDR_DISTRIBUTE_KEYS: 3227 if (setup->sm_key_distribution_send_set != 0) { 3228 sm_run_distribute_keys(connection); 3229 return; 3230 } 3231 // keys are sent 3232 if (IS_RESPONDER(connection->sm_role)) { 3233 // responder -> receive master keys if there are any 3234 if (!sm_key_distribution_all_received()){ 3235 connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS; 3236 break; 3237 } 3238 } 3239 // otherwise start CTKD right away (responder and no keys to receive / initiator) 3240 sm_ctkd_start_from_br_edr(connection); 3241 continue; 3242 case SM_SC_W2_CALCULATE_ILK_USING_H6: 3243 if (!sm_cmac_ready()) break; 3244 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK; 3245 h6_calculate_ilk_from_le_ltk(connection); 3246 break; 3247 case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY: 3248 if (!sm_cmac_ready()) break; 3249 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY; 3250 h6_calculate_br_edr_link_key(connection); 3251 break; 3252 case SM_SC_W2_CALCULATE_ILK_USING_H7: 3253 if (!sm_cmac_ready()) break; 3254 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK; 3255 h7_calculate_ilk_from_le_ltk(connection); 3256 break; 3257 case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6: 3258 if (!sm_cmac_ready()) break; 3259 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK; 3260 h6_calculate_ilk_from_br_edr(connection); 3261 break; 3262 case SM_BR_EDR_W2_CALCULATE_LE_LTK: 3263 if (!sm_cmac_ready()) break; 3264 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK; 3265 h6_calculate_le_ltk(connection); 3266 break; 3267 case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7: 3268 if (!sm_cmac_ready()) break; 3269 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK; 3270 h7_calculate_ilk_from_br_edr(connection); 3271 break; 3272 #endif 3273 3274 default: 3275 break; 3276 } 3277 3278 // check again if active connection was released 3279 if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break; 3280 } 3281 } 3282 3283 // sm_aes128_state stays active 3284 static void sm_handle_encryption_result_enc_a(void *arg){ 3285 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3286 sm_aes128_state = SM_AES128_IDLE; 3287 3288 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3289 if (connection == NULL) return; 3290 3291 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 3292 sm_aes128_state = SM_AES128_ACTIVE; 3293 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); 3294 } 3295 3296 static void sm_handle_encryption_result_enc_b(void *arg){ 3297 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3298 sm_aes128_state = SM_AES128_IDLE; 3299 3300 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3301 if (connection == NULL) return; 3302 3303 log_info_key("c1!", setup->sm_local_confirm); 3304 connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM; 3305 sm_trigger_run(); 3306 } 3307 3308 // sm_aes128_state stays active 3309 static void sm_handle_encryption_result_enc_c(void *arg){ 3310 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3311 sm_aes128_state = SM_AES128_IDLE; 3312 3313 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3314 if (connection == NULL) return; 3315 3316 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 3317 sm_aes128_state = SM_AES128_ACTIVE; 3318 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); 3319 } 3320 3321 static void sm_handle_encryption_result_enc_d(void * arg){ 3322 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3323 sm_aes128_state = SM_AES128_IDLE; 3324 3325 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3326 if (connection == NULL) return; 3327 3328 log_info_key("c1!", sm_aes128_ciphertext); 3329 if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){ 3330 sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED); 3331 sm_trigger_run(); 3332 return; 3333 } 3334 if (IS_RESPONDER(connection->sm_role)){ 3335 connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 3336 sm_trigger_run(); 3337 } else { 3338 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 3339 sm_aes128_state = SM_AES128_ACTIVE; 3340 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); 3341 } 3342 } 3343 3344 static void sm_handle_encryption_result_enc_stk(void *arg){ 3345 sm_aes128_state = SM_AES128_IDLE; 3346 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3347 3348 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3349 if (connection == NULL) return; 3350 3351 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 3352 log_info_key("stk", setup->sm_ltk); 3353 if (IS_RESPONDER(connection->sm_role)){ 3354 connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 3355 } else { 3356 connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 3357 } 3358 sm_trigger_run(); 3359 } 3360 3361 // sm_aes128_state stays active 3362 static void sm_handle_encryption_result_enc_ph3_y(void *arg){ 3363 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3364 sm_aes128_state = SM_AES128_IDLE; 3365 3366 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3367 if (connection == NULL) return; 3368 3369 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 3370 log_info_hex16("y", setup->sm_local_y); 3371 // PH3B3 - calculate EDIV 3372 setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div; 3373 log_info_hex16("ediv", setup->sm_local_ediv); 3374 // PH3B4 - calculate LTK - enc 3375 // LTK = d1(ER, DIV, 0)) 3376 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 3377 sm_aes128_state = SM_AES128_ACTIVE; 3378 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); 3379 } 3380 3381 #ifdef ENABLE_LE_PERIPHERAL 3382 // sm_aes128_state stays active 3383 static void sm_handle_encryption_result_enc_ph4_y(void *arg){ 3384 sm_aes128_state = SM_AES128_IDLE; 3385 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3386 3387 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3388 if (connection == NULL) return; 3389 3390 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 3391 log_info_hex16("y", setup->sm_local_y); 3392 3393 // PH3B3 - calculate DIV 3394 setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv; 3395 log_info_hex16("ediv", setup->sm_local_ediv); 3396 // PH3B4 - calculate LTK - enc 3397 // LTK = d1(ER, DIV, 0)) 3398 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 3399 sm_aes128_state = SM_AES128_ACTIVE; 3400 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); 3401 } 3402 #endif 3403 3404 // sm_aes128_state stays active 3405 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){ 3406 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3407 sm_aes128_state = SM_AES128_IDLE; 3408 3409 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3410 if (connection == NULL) return; 3411 3412 log_info_key("ltk", setup->sm_ltk); 3413 // calc CSRK next 3414 sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext); 3415 sm_aes128_state = SM_AES128_ACTIVE; 3416 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); 3417 } 3418 3419 static void sm_handle_encryption_result_enc_csrk(void *arg){ 3420 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3421 sm_aes128_state = SM_AES128_IDLE; 3422 3423 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3424 if (connection == NULL) return; 3425 3426 sm_aes128_state = SM_AES128_IDLE; 3427 log_info_key("csrk", setup->sm_local_csrk); 3428 if (setup->sm_key_distribution_send_set){ 3429 connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3430 } else { 3431 // no keys to send, just continue 3432 if (IS_RESPONDER(connection->sm_role)){ 3433 if (sm_key_distribution_all_received()){ 3434 sm_key_distribution_handle_all_received(connection); 3435 sm_key_distribution_complete_responder(connection); 3436 } else { 3437 // slave -> receive master keys 3438 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3439 } 3440 } else { 3441 sm_key_distribution_complete_initiator(connection); 3442 } 3443 } 3444 sm_trigger_run(); 3445 } 3446 3447 #ifdef ENABLE_LE_PERIPHERAL 3448 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){ 3449 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3450 sm_aes128_state = SM_AES128_IDLE; 3451 3452 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3453 if (connection == NULL) return; 3454 3455 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 3456 log_info_key("ltk", setup->sm_ltk); 3457 connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 3458 sm_trigger_run(); 3459 } 3460 #endif 3461 3462 static void sm_handle_encryption_result_address_resolution(void *arg){ 3463 UNUSED(arg); 3464 sm_aes128_state = SM_AES128_IDLE; 3465 3466 sm_address_resolution_ah_calculation_active = 0; 3467 // compare calulated address against connecting device 3468 uint8_t * hash = &sm_aes128_ciphertext[13]; 3469 if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){ 3470 log_info("LE Device Lookup: matched resolvable private address"); 3471 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED); 3472 sm_trigger_run(); 3473 return; 3474 } 3475 // no match, try next 3476 sm_address_resolution_test++; 3477 sm_trigger_run(); 3478 } 3479 3480 static void sm_handle_encryption_result_dkg_irk(void *arg){ 3481 UNUSED(arg); 3482 sm_aes128_state = SM_AES128_IDLE; 3483 3484 log_info_key("irk", sm_persistent_irk); 3485 dkg_state = DKG_CALC_DHK; 3486 sm_trigger_run(); 3487 } 3488 3489 static void sm_handle_encryption_result_dkg_dhk(void *arg){ 3490 UNUSED(arg); 3491 sm_aes128_state = SM_AES128_IDLE; 3492 3493 log_info_key("dhk", sm_persistent_dhk); 3494 dkg_state = DKG_READY; 3495 sm_trigger_run(); 3496 } 3497 3498 static void sm_handle_encryption_result_rau(void *arg){ 3499 UNUSED(arg); 3500 sm_aes128_state = SM_AES128_IDLE; 3501 3502 (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3); 3503 rau_state = RAU_IDLE; 3504 hci_le_random_address_set(sm_random_address); 3505 3506 sm_trigger_run(); 3507 } 3508 3509 static void sm_handle_random_result_rau(void * arg){ 3510 UNUSED(arg); 3511 // non-resolvable vs. resolvable 3512 switch (gap_random_adress_type){ 3513 case GAP_RANDOM_ADDRESS_RESOLVABLE: 3514 // resolvable: use random as prand and calc address hash 3515 // "The two most significant bits of prand shall be equal to ‘0’ and ‘1" 3516 sm_random_address[0u] &= 0x3fu; 3517 sm_random_address[0u] |= 0x40u; 3518 rau_state = RAU_GET_ENC; 3519 break; 3520 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 3521 default: 3522 // "The two most significant bits of the address shall be equal to ‘0’"" 3523 sm_random_address[0u] &= 0x3fu; 3524 rau_state = RAU_IDLE; 3525 hci_le_random_address_set(sm_random_address); 3526 break; 3527 } 3528 sm_trigger_run(); 3529 } 3530 3531 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3532 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){ 3533 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3534 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3535 if (connection == NULL) return; 3536 3537 connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 3538 sm_trigger_run(); 3539 } 3540 3541 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){ 3542 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3543 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3544 if (connection == NULL) return; 3545 3546 connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 3547 sm_trigger_run(); 3548 } 3549 #endif 3550 3551 static void sm_handle_random_result_ph2_random(void * arg){ 3552 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3553 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3554 if (connection == NULL) return; 3555 3556 connection->sm_engine_state = SM_PH2_C1_GET_ENC_A; 3557 sm_trigger_run(); 3558 } 3559 3560 static void sm_handle_random_result_ph2_tk(void * arg){ 3561 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3562 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3563 if (connection == NULL) return; 3564 3565 sm_reset_tk(); 3566 uint32_t tk; 3567 if (sm_fixed_passkey_in_display_role == 0xffffffffU){ 3568 // map random to 0-999999 without speding much cycles on a modulus operation 3569 tk = little_endian_read_32(sm_random_data,0); 3570 tk = tk & 0xfffff; // 1048575 3571 if (tk >= 999999u){ 3572 tk = tk - 999999u; 3573 } 3574 } else { 3575 // override with pre-defined passkey 3576 tk = sm_fixed_passkey_in_display_role; 3577 } 3578 big_endian_store_32(setup->sm_tk, 12, tk); 3579 if (IS_RESPONDER(connection->sm_role)){ 3580 connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE; 3581 } else { 3582 if (setup->sm_use_secure_connections){ 3583 connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 3584 } else { 3585 connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 3586 sm_trigger_user_response(connection); 3587 // response_idle == nothing <--> sm_trigger_user_response() did not require response 3588 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 3589 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); 3590 } 3591 } 3592 } 3593 sm_trigger_run(); 3594 } 3595 3596 static void sm_handle_random_result_ph3_div(void * arg){ 3597 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3598 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3599 if (connection == NULL) return; 3600 3601 // use 16 bit from random value as div 3602 setup->sm_local_div = big_endian_read_16(sm_random_data, 0); 3603 log_info_hex16("div", setup->sm_local_div); 3604 connection->sm_engine_state = SM_PH3_Y_GET_ENC; 3605 sm_trigger_run(); 3606 } 3607 3608 static void sm_handle_random_result_ph3_random(void * arg){ 3609 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3610 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3611 if (connection == NULL) return; 3612 3613 reverse_64(sm_random_data, setup->sm_local_rand); 3614 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 3615 setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u); 3616 // no db for authenticated flag hack: store flag in bit 4 of LSB 3617 setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u); 3618 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle); 3619 } 3620 static void sm_validate_er_ir(void){ 3621 // warn about default ER/IR 3622 bool warning = false; 3623 if (sm_ir_is_default()){ 3624 warning = true; 3625 log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues"); 3626 } 3627 if (sm_er_is_default()){ 3628 warning = true; 3629 log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure"); 3630 } 3631 if (warning) { 3632 log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys"); 3633 } 3634 } 3635 3636 static void sm_handle_random_result_ir(void *arg){ 3637 sm_persistent_keys_random_active = false; 3638 if (arg != NULL){ 3639 // key generated, store in tlv 3640 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u); 3641 log_info("Generated IR key. Store in TLV status: %d", status); 3642 UNUSED(status); 3643 } 3644 log_info_key("IR", sm_persistent_ir); 3645 dkg_state = DKG_CALC_IRK; 3646 3647 if (test_use_fixed_local_irk){ 3648 log_info_key("IRK", sm_persistent_irk); 3649 dkg_state = DKG_CALC_DHK; 3650 } 3651 3652 sm_trigger_run(); 3653 } 3654 3655 static void sm_handle_random_result_er(void *arg){ 3656 sm_persistent_keys_random_active = false; 3657 if (arg != 0){ 3658 // key generated, store in tlv 3659 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u); 3660 log_info("Generated ER key. Store in TLV status: %d", status); 3661 UNUSED(status); 3662 } 3663 log_info_key("ER", sm_persistent_er); 3664 3665 // try load ir 3666 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u); 3667 if (key_size == 16){ 3668 // ok, let's continue 3669 log_info("IR from TLV"); 3670 sm_handle_random_result_ir( NULL ); 3671 } else { 3672 // invalid, generate new random one 3673 sm_persistent_keys_random_active = true; 3674 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir); 3675 } 3676 } 3677 3678 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){ 3679 3680 // connection info 3681 sm_conn->sm_handle = con_handle; 3682 sm_conn->sm_role = role; 3683 sm_conn->sm_peer_addr_type = addr_type; 3684 memcpy(sm_conn->sm_peer_address, address, 6); 3685 3686 // security properties 3687 sm_conn->sm_connection_encrypted = 0; 3688 sm_conn->sm_connection_authenticated = 0; 3689 sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN; 3690 sm_conn->sm_le_db_index = -1; 3691 sm_conn->sm_reencryption_active = false; 3692 3693 // prepare CSRK lookup (does not involve setup) 3694 sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY; 3695 3696 sm_conn->sm_engine_state = SM_GENERAL_IDLE; 3697 } 3698 3699 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 3700 3701 UNUSED(channel); // ok: there is no channel 3702 UNUSED(size); // ok: fixed format HCI events 3703 3704 sm_connection_t * sm_conn; 3705 hci_con_handle_t con_handle; 3706 uint8_t status; 3707 bd_addr_t addr; 3708 3709 switch (packet_type) { 3710 3711 case HCI_EVENT_PACKET: 3712 switch (hci_event_packet_get_type(packet)) { 3713 3714 case BTSTACK_EVENT_STATE: 3715 switch (btstack_event_state_get_state(packet)){ 3716 case HCI_STATE_WORKING: 3717 log_info("HCI Working!"); 3718 // setup IR/ER with TLV 3719 btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context); 3720 if (sm_tlv_impl != NULL){ 3721 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u); 3722 if (key_size == 16){ 3723 // ok, let's continue 3724 log_info("ER from TLV"); 3725 sm_handle_random_result_er( NULL ); 3726 } else { 3727 // invalid, generate random one 3728 sm_persistent_keys_random_active = true; 3729 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er); 3730 } 3731 } else { 3732 sm_validate_er_ir(); 3733 dkg_state = DKG_CALC_IRK; 3734 3735 if (test_use_fixed_local_irk){ 3736 log_info_key("IRK", sm_persistent_irk); 3737 dkg_state = DKG_CALC_DHK; 3738 } 3739 } 3740 3741 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3742 // trigger ECC key generation 3743 if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){ 3744 sm_ec_generate_new_key(); 3745 } 3746 #endif 3747 3748 // restart random address updates after power cycle 3749 if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){ 3750 gap_random_address_set(sm_random_address); 3751 } else { 3752 gap_random_address_set_mode(gap_random_adress_type); 3753 } 3754 break; 3755 3756 case HCI_STATE_OFF: 3757 case HCI_STATE_HALTING: 3758 log_info("SM: reset state"); 3759 // stop random address update 3760 gap_random_address_update_stop(); 3761 // reset state 3762 sm_state_reset(); 3763 break; 3764 3765 default: 3766 break; 3767 } 3768 break; 3769 3770 #ifdef ENABLE_CLASSIC 3771 case HCI_EVENT_CONNECTION_COMPLETE: 3772 // ignore if connection failed 3773 if (hci_event_connection_complete_get_status(packet)) return; 3774 3775 con_handle = hci_event_connection_complete_get_connection_handle(packet); 3776 sm_conn = sm_get_connection_for_handle(con_handle); 3777 if (!sm_conn) break; 3778 3779 hci_event_connection_complete_get_bd_addr(packet, addr); 3780 sm_connection_init(sm_conn, 3781 con_handle, 3782 (uint8_t) gap_get_role(con_handle), 3783 BD_ADDR_TYPE_LE_PUBLIC, 3784 addr); 3785 // classic connection corresponds to public le address 3786 sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC; 3787 gap_local_bd_addr(sm_conn->sm_own_address); 3788 sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER; 3789 sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE; 3790 break; 3791 #endif 3792 3793 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3794 case HCI_EVENT_SIMPLE_PAIRING_COMPLETE: 3795 if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break; 3796 hci_event_simple_pairing_complete_get_bd_addr(packet, addr); 3797 sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3798 if (sm_conn == NULL) break; 3799 sm_conn->sm_pairing_requested = 1; 3800 break; 3801 #endif 3802 3803 case HCI_EVENT_LE_META: 3804 switch (packet[2]) { 3805 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 3806 // ignore if connection failed 3807 if (packet[3]) return; 3808 3809 con_handle = little_endian_read_16(packet, 4); 3810 sm_conn = sm_get_connection_for_handle(con_handle); 3811 if (!sm_conn) break; 3812 3813 hci_subevent_le_connection_complete_get_peer_address(packet, addr); 3814 sm_connection_init(sm_conn, 3815 con_handle, 3816 hci_subevent_le_connection_complete_get_role(packet), 3817 hci_subevent_le_connection_complete_get_peer_address_type(packet), 3818 addr); 3819 sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL; 3820 3821 // track our addr used for this connection and set state 3822 #ifdef ENABLE_LE_PERIPHERAL 3823 if (hci_subevent_le_connection_complete_get_role(packet) != 0){ 3824 // responder - use own address from advertisements 3825 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address); 3826 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3827 } 3828 #endif 3829 #ifdef ENABLE_LE_CENTRAL 3830 if (hci_subevent_le_connection_complete_get_role(packet) == 0){ 3831 // initiator - use own address from create connection 3832 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address); 3833 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3834 } 3835 #endif 3836 break; 3837 3838 case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST: 3839 con_handle = little_endian_read_16(packet, 3); 3840 sm_conn = sm_get_connection_for_handle(con_handle); 3841 if (!sm_conn) break; 3842 3843 log_info("LTK Request: state %u", sm_conn->sm_engine_state); 3844 if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){ 3845 sm_conn->sm_engine_state = SM_PH2_CALC_STK; 3846 break; 3847 } 3848 if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){ 3849 // PH2 SEND LTK as we need to exchange keys in PH3 3850 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 3851 break; 3852 } 3853 3854 // store rand and ediv 3855 reverse_64(&packet[5], sm_conn->sm_local_rand); 3856 sm_conn->sm_local_ediv = little_endian_read_16(packet, 13); 3857 3858 // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a 3859 // potentially stored LTK is from the master 3860 if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){ 3861 if (sm_reconstruct_ltk_without_le_device_db_entry){ 3862 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3863 break; 3864 } 3865 // additionally check if remote is in LE Device DB if requested 3866 switch(sm_conn->sm_irk_lookup_state){ 3867 case IRK_LOOKUP_FAILED: 3868 log_info("LTK Request: device not in device db"); 3869 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3870 break; 3871 case IRK_LOOKUP_SUCCEEDED: 3872 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3873 break; 3874 default: 3875 // wait for irk look doen 3876 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK; 3877 break; 3878 } 3879 break; 3880 } 3881 3882 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3883 sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST; 3884 #else 3885 log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported"); 3886 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3887 #endif 3888 break; 3889 3890 default: 3891 break; 3892 } 3893 break; 3894 3895 case HCI_EVENT_ENCRYPTION_CHANGE: 3896 case HCI_EVENT_ENCRYPTION_CHANGE_V2: 3897 con_handle = hci_event_encryption_change_get_connection_handle(packet); 3898 sm_conn = sm_get_connection_for_handle(con_handle); 3899 if (!sm_conn) break; 3900 3901 sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet); 3902 log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted, 3903 sm_conn->sm_actual_encryption_key_size); 3904 log_info("event handler, state %u", sm_conn->sm_engine_state); 3905 3906 switch (sm_conn->sm_engine_state){ 3907 3908 case SM_PH4_W4_CONNECTION_ENCRYPTED: 3909 // encryption change event concludes re-encryption for bonded devices (even if it fails) 3910 if (sm_conn->sm_connection_encrypted) { 3911 status = ERROR_CODE_SUCCESS; 3912 if (sm_conn->sm_role){ 3913 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3914 } else { 3915 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3916 } 3917 } else { 3918 status = hci_event_encryption_change_get_status(packet); 3919 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions 3920 // also, gap_reconnect_security_setup_active will return true 3921 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED; 3922 } 3923 3924 // emit re-encryption complete 3925 sm_reencryption_complete(sm_conn, status); 3926 3927 // notify client, if pairing was requested before 3928 if (sm_conn->sm_pairing_requested){ 3929 sm_conn->sm_pairing_requested = 0; 3930 sm_pairing_complete(sm_conn, status, 0); 3931 } 3932 3933 sm_done_for_handle(sm_conn->sm_handle); 3934 break; 3935 3936 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3937 if (!sm_conn->sm_connection_encrypted) break; 3938 sm_conn->sm_connection_sc = setup->sm_use_secure_connections; 3939 if (IS_RESPONDER(sm_conn->sm_role)){ 3940 // slave 3941 if (setup->sm_use_secure_connections){ 3942 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3943 } else { 3944 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); 3945 } 3946 } else { 3947 // master 3948 if (sm_key_distribution_all_received()){ 3949 // skip receiving keys as there are none 3950 sm_key_distribution_handle_all_received(sm_conn); 3951 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); 3952 } else { 3953 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3954 } 3955 } 3956 break; 3957 3958 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 3959 case SM_BR_EDR_W4_ENCRYPTION_COMPLETE: 3960 if (sm_conn->sm_connection_encrypted != 2) break; 3961 // prepare for pairing request 3962 if (IS_RESPONDER(sm_conn->sm_role)){ 3963 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST; 3964 } else if (sm_conn->sm_pairing_requested){ 3965 // only send LE pairing request after BR/EDR SSP 3966 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST; 3967 } 3968 break; 3969 #endif 3970 default: 3971 break; 3972 } 3973 break; 3974 3975 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE: 3976 con_handle = little_endian_read_16(packet, 3); 3977 sm_conn = sm_get_connection_for_handle(con_handle); 3978 if (!sm_conn) break; 3979 3980 log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size); 3981 log_info("event handler, state %u", sm_conn->sm_engine_state); 3982 // continue if part of initial pairing 3983 switch (sm_conn->sm_engine_state){ 3984 case SM_PH4_W4_CONNECTION_ENCRYPTED: 3985 if (sm_conn->sm_role){ 3986 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3987 } else { 3988 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3989 } 3990 sm_done_for_handle(sm_conn->sm_handle); 3991 break; 3992 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3993 if (IS_RESPONDER(sm_conn->sm_role)){ 3994 // slave 3995 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); 3996 } else { 3997 // master 3998 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3999 } 4000 break; 4001 default: 4002 break; 4003 } 4004 break; 4005 4006 4007 case HCI_EVENT_DISCONNECTION_COMPLETE: 4008 con_handle = little_endian_read_16(packet, 3); 4009 sm_done_for_handle(con_handle); 4010 sm_conn = sm_get_connection_for_handle(con_handle); 4011 if (!sm_conn) break; 4012 4013 // pairing failed, if it was ongoing 4014 switch (sm_conn->sm_engine_state){ 4015 case SM_GENERAL_IDLE: 4016 case SM_INITIATOR_CONNECTED: 4017 case SM_RESPONDER_IDLE: 4018 break; 4019 default: 4020 sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4021 sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0); 4022 break; 4023 } 4024 4025 sm_conn->sm_engine_state = SM_GENERAL_IDLE; 4026 sm_conn->sm_handle = 0; 4027 break; 4028 4029 case HCI_EVENT_COMMAND_COMPLETE: 4030 if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) { 4031 // set local addr for le device db 4032 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr); 4033 le_device_db_set_local_bd_addr(addr); 4034 } 4035 break; 4036 default: 4037 break; 4038 } 4039 break; 4040 default: 4041 break; 4042 } 4043 4044 sm_run(); 4045 } 4046 4047 static inline int sm_calc_actual_encryption_key_size(int other){ 4048 if (other < sm_min_encryption_key_size) return 0; 4049 if (other < sm_max_encryption_key_size) return other; 4050 return sm_max_encryption_key_size; 4051 } 4052 4053 4054 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4055 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){ 4056 switch (method){ 4057 case JUST_WORKS: 4058 case NUMERIC_COMPARISON: 4059 return 1; 4060 default: 4061 return 0; 4062 } 4063 } 4064 // responder 4065 4066 static int sm_passkey_used(stk_generation_method_t method){ 4067 switch (method){ 4068 case PK_RESP_INPUT: 4069 return 1; 4070 default: 4071 return 0; 4072 } 4073 } 4074 4075 static int sm_passkey_entry(stk_generation_method_t method){ 4076 switch (method){ 4077 case PK_RESP_INPUT: 4078 case PK_INIT_INPUT: 4079 case PK_BOTH_INPUT: 4080 return 1; 4081 default: 4082 return 0; 4083 } 4084 } 4085 4086 #endif 4087 4088 /** 4089 * @return ok 4090 */ 4091 static int sm_validate_stk_generation_method(void){ 4092 // check if STK generation method is acceptable by client 4093 switch (setup->sm_stk_generation_method){ 4094 case JUST_WORKS: 4095 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u; 4096 case PK_RESP_INPUT: 4097 case PK_INIT_INPUT: 4098 case PK_BOTH_INPUT: 4099 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u; 4100 case OOB: 4101 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u; 4102 case NUMERIC_COMPARISON: 4103 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u; 4104 default: 4105 return 0; 4106 } 4107 } 4108 4109 #ifdef ENABLE_LE_CENTRAL 4110 static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){ 4111 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4112 if (sm_sc_only_mode){ 4113 uint8_t auth_req = packet[1]; 4114 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){ 4115 sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS); 4116 return; 4117 } 4118 } 4119 #else 4120 UNUSED(packet); 4121 #endif 4122 4123 int have_ltk; 4124 uint8_t ltk[16]; 4125 4126 // IRK complete? 4127 switch (sm_conn->sm_irk_lookup_state){ 4128 case IRK_LOOKUP_FAILED: 4129 // start pairing 4130 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4131 break; 4132 case IRK_LOOKUP_SUCCEEDED: 4133 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4134 have_ltk = !sm_is_null_key(ltk); 4135 log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted); 4136 if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){ 4137 // start re-encrypt if we have LTK and the connection is not already encrypted 4138 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK; 4139 } else { 4140 // start pairing 4141 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4142 } 4143 break; 4144 default: 4145 // otherwise, store security request 4146 sm_conn->sm_security_request_received = 1; 4147 break; 4148 } 4149 } 4150 #endif 4151 4152 static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){ 4153 4154 // size of complete sm_pdu used to validate input 4155 static const uint8_t sm_pdu_size[] = { 4156 0, // 0x00 invalid opcode 4157 7, // 0x01 pairing request 4158 7, // 0x02 pairing response 4159 17, // 0x03 pairing confirm 4160 17, // 0x04 pairing random 4161 2, // 0x05 pairing failed 4162 17, // 0x06 encryption information 4163 11, // 0x07 master identification 4164 17, // 0x08 identification information 4165 8, // 0x09 identify address information 4166 17, // 0x0a signing information 4167 2, // 0x0b security request 4168 65, // 0x0c pairing public key 4169 17, // 0x0d pairing dhk check 4170 2, // 0x0e keypress notification 4171 }; 4172 4173 if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){ 4174 sm_run(); 4175 } 4176 4177 if (packet_type != SM_DATA_PACKET) return; 4178 if (size == 0u) return; 4179 4180 uint8_t sm_pdu_code = packet[0]; 4181 4182 // validate pdu size 4183 if (sm_pdu_code >= sizeof(sm_pdu_size)) return; 4184 if (sm_pdu_size[sm_pdu_code] != size) return; 4185 4186 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4187 if (!sm_conn) return; 4188 4189 if (sm_pdu_code == SM_CODE_PAIRING_FAILED){ 4190 sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE); 4191 sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]); 4192 sm_done_for_handle(con_handle); 4193 sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 4194 return; 4195 } 4196 4197 log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code); 4198 4199 int err; 4200 UNUSED(err); 4201 4202 if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){ 4203 uint8_t buffer[5]; 4204 buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION; 4205 buffer[1] = 3; 4206 little_endian_store_16(buffer, 2, con_handle); 4207 buffer[4] = packet[1]; 4208 sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer)); 4209 return; 4210 } 4211 4212 switch (sm_conn->sm_engine_state){ 4213 4214 // a sm timeout requires a new physical connection 4215 case SM_GENERAL_TIMEOUT: 4216 return; 4217 4218 #ifdef ENABLE_LE_CENTRAL 4219 4220 // Initiator 4221 case SM_INITIATOR_CONNECTED: 4222 if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){ 4223 sm_pdu_received_in_wrong_state(sm_conn); 4224 break; 4225 } 4226 sm_initiator_connected_handle_security_request(sm_conn, packet); 4227 break; 4228 4229 case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE: 4230 // Core 5, Vol 3, Part H, 2.4.6: 4231 // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request 4232 // without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup." 4233 if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){ 4234 log_info("Ignoring Security Request"); 4235 break; 4236 } 4237 4238 // all other pdus are incorrect 4239 if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){ 4240 sm_pdu_received_in_wrong_state(sm_conn); 4241 break; 4242 } 4243 4244 // store pairing request 4245 (void)memcpy(&setup->sm_s_pres, packet, 4246 sizeof(sm_pairing_packet_t)); 4247 err = sm_stk_generation_init(sm_conn); 4248 4249 #ifdef ENABLE_TESTING_SUPPORT 4250 if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){ 4251 log_info("testing_support: abort with pairing failure %u", test_pairing_failure); 4252 err = test_pairing_failure; 4253 } 4254 #endif 4255 4256 if (err != 0){ 4257 sm_pairing_error(sm_conn, err); 4258 break; 4259 } 4260 4261 // generate random number first, if we need to show passkey 4262 if (setup->sm_stk_generation_method == PK_RESP_INPUT){ 4263 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); 4264 break; 4265 } 4266 4267 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4268 if (setup->sm_use_secure_connections){ 4269 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 4270 if (setup->sm_stk_generation_method == JUST_WORKS){ 4271 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4272 sm_trigger_user_response(sm_conn); 4273 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 4274 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4275 } 4276 } else { 4277 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4278 } 4279 break; 4280 } 4281 #endif 4282 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4283 sm_trigger_user_response(sm_conn); 4284 // response_idle == nothing <--> sm_trigger_user_response() did not require response 4285 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 4286 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); 4287 } 4288 break; 4289 4290 case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM: 4291 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4292 sm_pdu_received_in_wrong_state(sm_conn); 4293 break; 4294 } 4295 4296 // store s_confirm 4297 reverse_128(&packet[1], setup->sm_peer_confirm); 4298 4299 // abort if s_confirm matches m_confirm 4300 if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){ 4301 sm_pdu_received_in_wrong_state(sm_conn); 4302 break; 4303 } 4304 4305 #ifdef ENABLE_TESTING_SUPPORT 4306 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4307 log_info("testing_support: reset confirm value"); 4308 memset(setup->sm_peer_confirm, 0, 16); 4309 } 4310 #endif 4311 sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 4312 break; 4313 4314 case SM_INITIATOR_PH2_W4_PAIRING_RANDOM: 4315 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4316 sm_pdu_received_in_wrong_state(sm_conn); 4317 break;; 4318 } 4319 4320 // received random value 4321 reverse_128(&packet[1], setup->sm_peer_random); 4322 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 4323 break; 4324 #endif 4325 4326 #ifdef ENABLE_LE_PERIPHERAL 4327 // Responder 4328 case SM_RESPONDER_IDLE: 4329 case SM_RESPONDER_SEND_SECURITY_REQUEST: 4330 case SM_RESPONDER_PH1_W4_PAIRING_REQUEST: 4331 if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){ 4332 sm_pdu_received_in_wrong_state(sm_conn); 4333 break;; 4334 } 4335 4336 // store pairing request 4337 (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t)); 4338 4339 // check if IRK completed 4340 switch (sm_conn->sm_irk_lookup_state){ 4341 case IRK_LOOKUP_SUCCEEDED: 4342 case IRK_LOOKUP_FAILED: 4343 sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED; 4344 break; 4345 default: 4346 sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK; 4347 break; 4348 } 4349 break; 4350 #endif 4351 4352 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4353 case SM_SC_W4_PUBLIC_KEY_COMMAND: 4354 if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){ 4355 sm_pdu_received_in_wrong_state(sm_conn); 4356 break; 4357 } 4358 4359 // store public key for DH Key calculation 4360 reverse_256(&packet[01], &setup->sm_peer_q[0]); 4361 reverse_256(&packet[33], &setup->sm_peer_q[32]); 4362 4363 // CVE-2020-26558: abort pairing if remote uses the same public key 4364 if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){ 4365 log_info("Remote PK matches ours"); 4366 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 4367 break; 4368 } 4369 4370 // validate public key 4371 err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q); 4372 if (err != 0){ 4373 log_info("sm: peer public key invalid %x", err); 4374 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 4375 break; 4376 } 4377 4378 // start calculating dhkey 4379 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); 4380 4381 4382 log_info("public key received, generation method %u", setup->sm_stk_generation_method); 4383 if (IS_RESPONDER(sm_conn->sm_role)){ 4384 // responder 4385 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4386 } else { 4387 // initiator 4388 // stk generation method 4389 // passkey entry: notify app to show passkey or to request passkey 4390 switch (setup->sm_stk_generation_method){ 4391 case JUST_WORKS: 4392 case NUMERIC_COMPARISON: 4393 sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION; 4394 break; 4395 case PK_RESP_INPUT: 4396 sm_sc_start_calculating_local_confirm(sm_conn); 4397 break; 4398 case PK_INIT_INPUT: 4399 case PK_BOTH_INPUT: 4400 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 4401 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 4402 break; 4403 } 4404 sm_sc_start_calculating_local_confirm(sm_conn); 4405 break; 4406 case OOB: 4407 // generate Nx 4408 log_info("Generate Na"); 4409 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); 4410 break; 4411 default: 4412 btstack_assert(false); 4413 break; 4414 } 4415 } 4416 break; 4417 4418 case SM_SC_W4_CONFIRMATION: 4419 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4420 sm_pdu_received_in_wrong_state(sm_conn); 4421 break; 4422 } 4423 // received confirm value 4424 reverse_128(&packet[1], setup->sm_peer_confirm); 4425 4426 #ifdef ENABLE_TESTING_SUPPORT 4427 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4428 log_info("testing_support: reset confirm value"); 4429 memset(setup->sm_peer_confirm, 0, 16); 4430 } 4431 #endif 4432 if (IS_RESPONDER(sm_conn->sm_role)){ 4433 // responder 4434 if (sm_passkey_used(setup->sm_stk_generation_method)){ 4435 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 4436 // still waiting for passkey 4437 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 4438 break; 4439 } 4440 } 4441 sm_sc_start_calculating_local_confirm(sm_conn); 4442 } else { 4443 // initiator 4444 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){ 4445 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); 4446 } else { 4447 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 4448 } 4449 } 4450 break; 4451 4452 case SM_SC_W4_PAIRING_RANDOM: 4453 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4454 sm_pdu_received_in_wrong_state(sm_conn); 4455 break; 4456 } 4457 4458 // received random value 4459 reverse_128(&packet[1], setup->sm_peer_nonce); 4460 4461 // validate confirm value if Cb = f4(Pkb, Pka, Nb, z) 4462 // only check for JUST WORK/NC in initiator role OR passkey entry 4463 log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u", 4464 IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method), 4465 sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method)); 4466 if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)) 4467 || (sm_passkey_entry(setup->sm_stk_generation_method)) ) { 4468 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 4469 break; 4470 } 4471 4472 // OOB 4473 if (setup->sm_stk_generation_method == OOB){ 4474 4475 // setup local random, set to zero if remote did not receive our data 4476 log_info("Received nonce, setup local random ra/rb for dhkey check"); 4477 if (IS_RESPONDER(sm_conn->sm_role)){ 4478 if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){ 4479 log_info("Reset rb as A does not have OOB data"); 4480 memset(setup->sm_rb, 0, 16); 4481 } else { 4482 (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16); 4483 log_info("Use stored rb"); 4484 log_info_hexdump(setup->sm_rb, 16); 4485 } 4486 } else { 4487 if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){ 4488 log_info("Reset ra as B does not have OOB data"); 4489 memset(setup->sm_ra, 0, 16); 4490 } else { 4491 (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16); 4492 log_info("Use stored ra"); 4493 log_info_hexdump(setup->sm_ra, 16); 4494 } 4495 } 4496 4497 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received 4498 if (setup->sm_have_oob_data){ 4499 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 4500 break; 4501 } 4502 } 4503 4504 // TODO: we only get here for Responder role with JW/NC 4505 sm_sc_state_after_receiving_random(sm_conn); 4506 break; 4507 4508 case SM_SC_W2_CALCULATE_G2: 4509 case SM_SC_W4_CALCULATE_G2: 4510 case SM_SC_W4_CALCULATE_DHKEY: 4511 case SM_SC_W2_CALCULATE_F5_SALT: 4512 case SM_SC_W4_CALCULATE_F5_SALT: 4513 case SM_SC_W2_CALCULATE_F5_MACKEY: 4514 case SM_SC_W4_CALCULATE_F5_MACKEY: 4515 case SM_SC_W2_CALCULATE_F5_LTK: 4516 case SM_SC_W4_CALCULATE_F5_LTK: 4517 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 4518 case SM_SC_W4_DHKEY_CHECK_COMMAND: 4519 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 4520 case SM_SC_W4_USER_RESPONSE: 4521 if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){ 4522 sm_pdu_received_in_wrong_state(sm_conn); 4523 break; 4524 } 4525 // store DHKey Check 4526 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED; 4527 reverse_128(&packet[01], setup->sm_peer_dhkey_check); 4528 4529 // have we been only waiting for dhkey check command? 4530 if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){ 4531 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 4532 } 4533 break; 4534 #endif 4535 4536 #ifdef ENABLE_LE_PERIPHERAL 4537 case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM: 4538 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 4539 sm_pdu_received_in_wrong_state(sm_conn); 4540 break; 4541 } 4542 4543 // received confirm value 4544 reverse_128(&packet[1], setup->sm_peer_confirm); 4545 4546 #ifdef ENABLE_TESTING_SUPPORT 4547 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 4548 log_info("testing_support: reset confirm value"); 4549 memset(setup->sm_peer_confirm, 0, 16); 4550 } 4551 #endif 4552 // notify client to hide shown passkey 4553 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 4554 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address); 4555 } 4556 4557 // handle user cancel pairing? 4558 if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){ 4559 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED); 4560 break; 4561 } 4562 4563 // wait for user action? 4564 if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){ 4565 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 4566 break; 4567 } 4568 4569 // calculate and send local_confirm 4570 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); 4571 break; 4572 4573 case SM_RESPONDER_PH2_W4_PAIRING_RANDOM: 4574 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 4575 sm_pdu_received_in_wrong_state(sm_conn); 4576 break;; 4577 } 4578 4579 // received random value 4580 reverse_128(&packet[1], setup->sm_peer_random); 4581 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 4582 break; 4583 #endif 4584 4585 case SM_PH2_W4_CONNECTION_ENCRYPTED: 4586 case SM_PH3_RECEIVE_KEYS: 4587 switch(sm_pdu_code){ 4588 case SM_CODE_ENCRYPTION_INFORMATION: 4589 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 4590 reverse_128(&packet[1], setup->sm_peer_ltk); 4591 break; 4592 4593 case SM_CODE_MASTER_IDENTIFICATION: 4594 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 4595 setup->sm_peer_ediv = little_endian_read_16(packet, 1); 4596 reverse_64(&packet[3], setup->sm_peer_rand); 4597 break; 4598 4599 case SM_CODE_IDENTITY_INFORMATION: 4600 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 4601 reverse_128(&packet[1], setup->sm_peer_irk); 4602 break; 4603 4604 case SM_CODE_IDENTITY_ADDRESS_INFORMATION: 4605 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 4606 setup->sm_peer_addr_type = packet[1]; 4607 reverse_bd_addr(&packet[2], setup->sm_peer_address); 4608 break; 4609 4610 case SM_CODE_SIGNING_INFORMATION: 4611 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 4612 reverse_128(&packet[1], setup->sm_peer_csrk); 4613 break; 4614 default: 4615 // Unexpected PDU 4616 log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]); 4617 break; 4618 } 4619 // done with key distribution? 4620 if (sm_key_distribution_all_received()){ 4621 4622 sm_key_distribution_handle_all_received(sm_conn); 4623 4624 if (IS_RESPONDER(sm_conn->sm_role)){ 4625 sm_key_distribution_complete_responder(sm_conn); 4626 } else { 4627 if (setup->sm_use_secure_connections){ 4628 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 4629 } else { 4630 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); 4631 } 4632 } 4633 } 4634 break; 4635 4636 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 4637 case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE: 4638 if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){ 4639 sm_pdu_received_in_wrong_state(sm_conn); 4640 break; 4641 } 4642 // store pairing response 4643 (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t)); 4644 4645 // validate encryption key size 4646 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)); 4647 // SC Only mandates 128 bit key size 4648 if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) { 4649 sm_conn->sm_actual_encryption_key_size = 0; 4650 } 4651 if (sm_conn->sm_actual_encryption_key_size == 0){ 4652 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE); 4653 break; 4654 } 4655 4656 // prepare key exchange, LTK is derived locally 4657 sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY, 4658 sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY); 4659 4660 // skip receive if there are none 4661 if (sm_key_distribution_all_received()){ 4662 // distribute keys in run handles 'no keys to send' 4663 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 4664 } else { 4665 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS; 4666 } 4667 break; 4668 4669 case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST: 4670 if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){ 4671 sm_pdu_received_in_wrong_state(sm_conn); 4672 break; 4673 } 4674 // store pairing request 4675 (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t)); 4676 // validate encryption key size 4677 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)); 4678 // SC Only mandates 128 bit key size 4679 if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) { 4680 sm_conn->sm_actual_encryption_key_size = 0; 4681 } 4682 if (sm_conn->sm_actual_encryption_key_size == 0){ 4683 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE); 4684 break; 4685 } 4686 // trigger response 4687 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED; 4688 break; 4689 4690 case SM_BR_EDR_RECEIVE_KEYS: 4691 switch(sm_pdu_code){ 4692 case SM_CODE_IDENTITY_INFORMATION: 4693 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 4694 reverse_128(&packet[1], setup->sm_peer_irk); 4695 break; 4696 case SM_CODE_IDENTITY_ADDRESS_INFORMATION: 4697 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 4698 setup->sm_peer_addr_type = packet[1]; 4699 reverse_bd_addr(&packet[2], setup->sm_peer_address); 4700 break; 4701 case SM_CODE_SIGNING_INFORMATION: 4702 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 4703 reverse_128(&packet[1], setup->sm_peer_csrk); 4704 break; 4705 default: 4706 // Unexpected PDU 4707 log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]); 4708 break; 4709 } 4710 4711 // all keys received 4712 if (sm_key_distribution_all_received()){ 4713 if (IS_RESPONDER(sm_conn->sm_role)){ 4714 // responder -> keys exchanged, derive LE LTK 4715 sm_ctkd_start_from_br_edr(sm_conn); 4716 } else { 4717 // initiator -> send our keys if any 4718 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS; 4719 } 4720 } 4721 break; 4722 #endif 4723 4724 default: 4725 // Unexpected PDU 4726 log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state); 4727 sm_pdu_received_in_wrong_state(sm_conn); 4728 break; 4729 } 4730 4731 // try to send next pdu 4732 sm_trigger_run(); 4733 } 4734 4735 // Security Manager Client API 4736 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){ 4737 sm_get_oob_data = get_oob_data_callback; 4738 } 4739 4740 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)){ 4741 sm_get_sc_oob_data = get_sc_oob_data_callback; 4742 } 4743 4744 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)){ 4745 sm_get_ltk_callback = get_ltk_callback; 4746 } 4747 4748 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4749 btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler); 4750 } 4751 4752 void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4753 btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler); 4754 } 4755 4756 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){ 4757 sm_accepted_stk_generation_methods = accepted_stk_generation_methods; 4758 } 4759 4760 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){ 4761 sm_min_encryption_key_size = min_size; 4762 sm_max_encryption_key_size = max_size; 4763 } 4764 4765 void sm_set_authentication_requirements(uint8_t auth_req){ 4766 #ifndef ENABLE_LE_SECURE_CONNECTIONS 4767 if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){ 4768 log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag"); 4769 auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION; 4770 } 4771 #endif 4772 sm_auth_req = auth_req; 4773 } 4774 4775 void sm_set_io_capabilities(io_capability_t io_capability){ 4776 sm_io_capabilities = io_capability; 4777 } 4778 4779 #ifdef ENABLE_LE_PERIPHERAL 4780 void sm_set_request_security(int enable){ 4781 sm_slave_request_security = enable; 4782 } 4783 #endif 4784 4785 void sm_set_er(sm_key_t er){ 4786 (void)memcpy(sm_persistent_er, er, 16); 4787 } 4788 4789 void sm_set_ir(sm_key_t ir){ 4790 (void)memcpy(sm_persistent_ir, ir, 16); 4791 } 4792 4793 // Testing support only 4794 void sm_test_set_irk(sm_key_t irk){ 4795 (void)memcpy(sm_persistent_irk, irk, 16); 4796 dkg_state = DKG_CALC_DHK; 4797 test_use_fixed_local_irk = true; 4798 } 4799 4800 void sm_test_use_fixed_local_csrk(void){ 4801 test_use_fixed_local_csrk = true; 4802 } 4803 4804 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4805 static void sm_ec_generated(void * arg){ 4806 UNUSED(arg); 4807 ec_key_generation_state = EC_KEY_GENERATION_DONE; 4808 // trigger pairing if pending for ec key 4809 sm_trigger_run(); 4810 } 4811 static void sm_ec_generate_new_key(void){ 4812 log_info("sm: generate new ec key"); 4813 ec_key_generation_state = EC_KEY_GENERATION_ACTIVE; 4814 btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL); 4815 } 4816 #endif 4817 4818 #ifdef ENABLE_TESTING_SUPPORT 4819 void sm_test_set_pairing_failure(int reason){ 4820 test_pairing_failure = reason; 4821 } 4822 #endif 4823 4824 static void sm_state_reset(void) { 4825 #ifdef USE_CMAC_ENGINE 4826 sm_cmac_active = 0; 4827 #endif 4828 dkg_state = DKG_W4_WORKING; 4829 rau_state = RAU_IDLE; 4830 sm_aes128_state = SM_AES128_IDLE; 4831 sm_address_resolution_test = -1; // no private address to resolve yet 4832 sm_address_resolution_ah_calculation_active = 0; 4833 sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE; 4834 sm_address_resolution_general_queue = NULL; 4835 sm_active_connection_handle = HCI_CON_HANDLE_INVALID; 4836 sm_persistent_keys_random_active = false; 4837 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4838 ec_key_generation_state = EC_KEY_GENERATION_IDLE; 4839 #endif 4840 } 4841 4842 void sm_init(void){ 4843 4844 if (sm_initialized) return; 4845 4846 // set default ER and IR values (should be unique - set by app or sm later using TLV) 4847 sm_er_ir_set_default(); 4848 4849 // defaults 4850 sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS 4851 | SM_STK_GENERATION_METHOD_OOB 4852 | SM_STK_GENERATION_METHOD_PASSKEY 4853 | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON; 4854 4855 sm_max_encryption_key_size = 16; 4856 sm_min_encryption_key_size = 7; 4857 4858 sm_fixed_passkey_in_display_role = 0xffffffffU; 4859 sm_reconstruct_ltk_without_le_device_db_entry = true; 4860 4861 gap_random_adress_update_period = 15 * 60 * 1000L; 4862 4863 test_use_fixed_local_csrk = false; 4864 4865 // other 4866 btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler); 4867 4868 // register for HCI Events from HCI 4869 hci_event_callback_registration.callback = &sm_event_packet_handler; 4870 hci_add_event_handler(&hci_event_callback_registration); 4871 4872 // 4873 btstack_crypto_init(); 4874 4875 // init le_device_db 4876 le_device_db_init(); 4877 4878 // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW 4879 l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 4880 #ifdef ENABLE_CLASSIC 4881 l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER); 4882 #endif 4883 4884 // state 4885 sm_state_reset(); 4886 4887 sm_initialized = true; 4888 } 4889 4890 void sm_deinit(void){ 4891 sm_initialized = false; 4892 btstack_run_loop_remove_timer(&sm_run_timer); 4893 } 4894 4895 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){ 4896 sm_fixed_passkey_in_display_role = passkey; 4897 } 4898 4899 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){ 4900 sm_reconstruct_ltk_without_le_device_db_entry = allow != 0; 4901 } 4902 4903 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 4904 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 4905 if (!hci_con) return NULL; 4906 return &hci_con->sm_connection; 4907 } 4908 4909 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION 4910 static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){ 4911 hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type); 4912 if (!hci_con) return NULL; 4913 return &hci_con->sm_connection; 4914 } 4915 #endif 4916 4917 // @deprecated: map onto sm_request_pairing 4918 void sm_send_security_request(hci_con_handle_t con_handle){ 4919 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4920 if (!sm_conn) return; 4921 if (!IS_RESPONDER(sm_conn->sm_role)) return; 4922 sm_request_pairing(con_handle); 4923 } 4924 4925 // request pairing 4926 void sm_request_pairing(hci_con_handle_t con_handle){ 4927 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4928 if (!sm_conn) return; // wrong connection 4929 4930 bool have_ltk; 4931 uint8_t ltk[16]; 4932 log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state); 4933 if (IS_RESPONDER(sm_conn->sm_role)){ 4934 switch (sm_conn->sm_engine_state){ 4935 case SM_GENERAL_IDLE: 4936 case SM_RESPONDER_IDLE: 4937 switch (sm_conn->sm_irk_lookup_state){ 4938 case IRK_LOOKUP_SUCCEEDED: 4939 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4940 have_ltk = !sm_is_null_key(ltk); 4941 log_info("have ltk %u", have_ltk); 4942 if (have_ltk){ 4943 sm_conn->sm_pairing_requested = 1; 4944 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 4945 sm_reencryption_started(sm_conn); 4946 break; 4947 } 4948 /* fall through */ 4949 4950 case IRK_LOOKUP_FAILED: 4951 sm_conn->sm_pairing_requested = 1; 4952 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 4953 sm_pairing_started(sm_conn); 4954 break; 4955 default: 4956 log_info("irk lookup pending"); 4957 sm_conn->sm_pairing_requested = 1; 4958 break; 4959 } 4960 break; 4961 default: 4962 break; 4963 } 4964 } else { 4965 // used as a trigger to start central/master/initiator security procedures 4966 switch (sm_conn->sm_engine_state){ 4967 case SM_INITIATOR_CONNECTED: 4968 switch (sm_conn->sm_irk_lookup_state){ 4969 case IRK_LOOKUP_SUCCEEDED: 4970 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4971 have_ltk = !sm_is_null_key(ltk); 4972 log_info("have ltk %u", have_ltk); 4973 if (have_ltk){ 4974 sm_conn->sm_pairing_requested = 1; 4975 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK; 4976 break; 4977 } 4978 /* fall through */ 4979 4980 case IRK_LOOKUP_FAILED: 4981 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4982 break; 4983 default: 4984 log_info("irk lookup pending"); 4985 sm_conn->sm_pairing_requested = 1; 4986 break; 4987 } 4988 break; 4989 case SM_GENERAL_REENCRYPTION_FAILED: 4990 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4991 break; 4992 case SM_GENERAL_IDLE: 4993 sm_conn->sm_pairing_requested = 1; 4994 break; 4995 default: 4996 break; 4997 } 4998 } 4999 sm_trigger_run(); 5000 } 5001 5002 // called by client app on authorization request 5003 void sm_authorization_decline(hci_con_handle_t con_handle){ 5004 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5005 if (!sm_conn) return; // wrong connection 5006 sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED; 5007 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0); 5008 } 5009 5010 void sm_authorization_grant(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 sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED; 5014 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1); 5015 } 5016 5017 // GAP Bonding API 5018 5019 void sm_bonding_decline(hci_con_handle_t con_handle){ 5020 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5021 if (!sm_conn) return; // wrong connection 5022 setup->sm_user_response = SM_USER_RESPONSE_DECLINE; 5023 log_info("decline, state %u", sm_conn->sm_engine_state); 5024 switch(sm_conn->sm_engine_state){ 5025 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5026 case SM_SC_W4_USER_RESPONSE: 5027 case SM_SC_W4_CONFIRMATION: 5028 case SM_SC_W4_PUBLIC_KEY_COMMAND: 5029 #endif 5030 case SM_PH1_W4_USER_RESPONSE: 5031 switch (setup->sm_stk_generation_method){ 5032 case PK_RESP_INPUT: 5033 case PK_INIT_INPUT: 5034 case PK_BOTH_INPUT: 5035 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED); 5036 break; 5037 case NUMERIC_COMPARISON: 5038 sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED); 5039 break; 5040 case JUST_WORKS: 5041 case OOB: 5042 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 5043 break; 5044 default: 5045 btstack_assert(false); 5046 break; 5047 } 5048 break; 5049 default: 5050 break; 5051 } 5052 sm_trigger_run(); 5053 } 5054 5055 void sm_just_works_confirm(hci_con_handle_t con_handle){ 5056 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5057 if (!sm_conn) return; // wrong connection 5058 setup->sm_user_response = SM_USER_RESPONSE_CONFIRM; 5059 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 5060 if (setup->sm_use_secure_connections){ 5061 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 5062 } else { 5063 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); 5064 } 5065 } 5066 5067 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5068 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 5069 sm_sc_prepare_dhkey_check(sm_conn); 5070 } 5071 #endif 5072 5073 sm_trigger_run(); 5074 } 5075 5076 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){ 5077 // for now, it's the same 5078 sm_just_works_confirm(con_handle); 5079 } 5080 5081 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){ 5082 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5083 if (!sm_conn) return; // wrong connection 5084 sm_reset_tk(); 5085 big_endian_store_32(setup->sm_tk, 12, passkey); 5086 setup->sm_user_response = SM_USER_RESPONSE_PASSKEY; 5087 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 5088 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); 5089 } 5090 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5091 (void)memcpy(setup->sm_ra, setup->sm_tk, 16); 5092 (void)memcpy(setup->sm_rb, setup->sm_tk, 16); 5093 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 5094 sm_sc_start_calculating_local_confirm(sm_conn); 5095 } 5096 #endif 5097 sm_trigger_run(); 5098 } 5099 5100 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){ 5101 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5102 if (!sm_conn) return; // wrong connection 5103 if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return; 5104 uint8_t num_actions = setup->sm_keypress_notification >> 5; 5105 uint8_t flags = setup->sm_keypress_notification & 0x1fu; 5106 switch (action){ 5107 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 5108 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 5109 flags |= (1u << action); 5110 break; 5111 case SM_KEYPRESS_PASSKEY_CLEARED: 5112 // clear counter, keypress & erased flags + set passkey cleared 5113 flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED); 5114 break; 5115 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 5116 if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){ 5117 // erase actions queued 5118 num_actions--; 5119 if (num_actions == 0u){ 5120 // clear counter, keypress & erased flags 5121 flags &= 0x19u; 5122 } 5123 break; 5124 } 5125 num_actions++; 5126 flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED); 5127 break; 5128 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 5129 if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){ 5130 // enter actions queued 5131 num_actions--; 5132 if (num_actions == 0u){ 5133 // clear counter, keypress & erased flags 5134 flags &= 0x19u; 5135 } 5136 break; 5137 } 5138 num_actions++; 5139 flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED); 5140 break; 5141 default: 5142 break; 5143 } 5144 setup->sm_keypress_notification = (num_actions << 5) | flags; 5145 sm_trigger_run(); 5146 } 5147 5148 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5149 static void sm_handle_random_result_oob(void * arg){ 5150 UNUSED(arg); 5151 sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM; 5152 sm_trigger_run(); 5153 } 5154 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){ 5155 5156 static btstack_crypto_random_t sm_crypto_random_oob_request; 5157 5158 if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 5159 sm_sc_oob_callback = callback; 5160 sm_sc_oob_state = SM_SC_OOB_W4_RANDOM; 5161 btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL); 5162 return 0; 5163 } 5164 #endif 5165 5166 /** 5167 * @brief Get Identity Resolving state 5168 * @param con_handle 5169 * @return irk_lookup_state_t 5170 */ 5171 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){ 5172 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5173 if (!sm_conn) return IRK_LOOKUP_IDLE; 5174 return sm_conn->sm_irk_lookup_state; 5175 } 5176 5177 /** 5178 * @brief Identify device in LE Device DB 5179 * @param handle 5180 * @return index from le_device_db or -1 if not found/identified 5181 */ 5182 int sm_le_device_index(hci_con_handle_t con_handle ){ 5183 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5184 if (!sm_conn) return -1; 5185 return sm_conn->sm_le_db_index; 5186 } 5187 5188 static int gap_random_address_type_requires_updates(void){ 5189 switch (gap_random_adress_type){ 5190 case GAP_RANDOM_ADDRESS_TYPE_OFF: 5191 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 5192 return 0; 5193 default: 5194 return 1; 5195 } 5196 } 5197 5198 static uint8_t own_address_type(void){ 5199 switch (gap_random_adress_type){ 5200 case GAP_RANDOM_ADDRESS_TYPE_OFF: 5201 return BD_ADDR_TYPE_LE_PUBLIC; 5202 default: 5203 return BD_ADDR_TYPE_LE_RANDOM; 5204 } 5205 } 5206 5207 // GAP LE API 5208 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){ 5209 gap_random_address_update_stop(); 5210 gap_random_adress_type = random_address_type; 5211 hci_le_set_own_address_type(own_address_type()); 5212 if (!gap_random_address_type_requires_updates()) return; 5213 gap_random_address_update_start(); 5214 gap_random_address_trigger(); 5215 } 5216 5217 gap_random_address_type_t gap_random_address_get_mode(void){ 5218 return gap_random_adress_type; 5219 } 5220 5221 void gap_random_address_set_update_period(int period_ms){ 5222 gap_random_adress_update_period = period_ms; 5223 if (!gap_random_address_type_requires_updates()) return; 5224 gap_random_address_update_stop(); 5225 gap_random_address_update_start(); 5226 } 5227 5228 void gap_random_address_set(const bd_addr_t addr){ 5229 gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC); 5230 (void)memcpy(sm_random_address, addr, 6); 5231 hci_le_random_address_set(addr); 5232 } 5233 5234 #ifdef ENABLE_LE_PERIPHERAL 5235 /* 5236 * @brief Set Advertisement Paramters 5237 * @param adv_int_min 5238 * @param adv_int_max 5239 * @param adv_type 5240 * @param direct_address_type 5241 * @param direct_address 5242 * @param channel_map 5243 * @param filter_policy 5244 * 5245 * @note own_address_type is used from gap_random_address_set_mode 5246 */ 5247 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 5248 uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){ 5249 hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 5250 direct_address_typ, direct_address, channel_map, filter_policy); 5251 } 5252 #endif 5253 5254 int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){ 5255 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 5256 // wrong connection 5257 if (!sm_conn) return 0; 5258 // already encrypted 5259 if (sm_conn->sm_connection_encrypted) return 0; 5260 // irk status? 5261 switch(sm_conn->sm_irk_lookup_state){ 5262 case IRK_LOOKUP_FAILED: 5263 // done, cannot setup encryption 5264 return 0; 5265 case IRK_LOOKUP_SUCCEEDED: 5266 break; 5267 default: 5268 // IR Lookup pending 5269 return 1; 5270 } 5271 // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure 5272 if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0; 5273 if (sm_conn->sm_role){ 5274 return sm_conn->sm_engine_state != SM_RESPONDER_IDLE; 5275 } else { 5276 return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED; 5277 } 5278 } 5279 5280 void sm_set_secure_connections_only_mode(bool enable){ 5281 #ifdef ENABLE_LE_SECURE_CONNECTIONS 5282 sm_sc_only_mode = enable; 5283 #else 5284 // SC Only mode not possible without support for SC 5285 btstack_assert(enable == false); 5286 #endif 5287 } 5288 5289 const uint8_t * gap_get_persistent_irk(void){ 5290 return sm_persistent_irk; 5291 } 5292 5293 void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){ 5294 uint16_t i; 5295 for (i=0; i < le_device_db_max_count(); i++){ 5296 bd_addr_t entry_address; 5297 int entry_address_type = BD_ADDR_TYPE_UNKNOWN; 5298 le_device_db_info(i, &entry_address_type, entry_address, NULL); 5299 // skip unused entries 5300 if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue; 5301 if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){ 5302 sm_remove_le_device_db_entry(i); 5303 break; 5304 } 5305 } 5306 } 5307