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