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