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