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