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