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