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