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