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