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