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