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