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