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 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 memcpy(&p2[4], ia, 6); 665 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 memcpy(&r_prime[8], &r2[8], 8); 680 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 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 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 int sm_key_distribution_flags_for_auth_req(void){ 1019 1020 int flags = SM_KEYDIST_ID_KEY; 1021 if (sm_auth_req & SM_AUTHREQ_BONDING){ 1022 // encryption and signing information only if bonding requested 1023 flags |= SM_KEYDIST_ENC_KEY; 1024 #ifdef ENABLE_LE_SIGNED_WRITE 1025 flags |= SM_KEYDIST_SIGN; 1026 #endif 1027 } 1028 return flags; 1029 } 1030 1031 static void sm_reset_setup(void){ 1032 // fill in sm setup 1033 setup->sm_state_vars = 0; 1034 setup->sm_keypress_notification = 0; 1035 sm_reset_tk(); 1036 } 1037 1038 static void sm_init_setup(sm_connection_t * sm_conn){ 1039 1040 // fill in sm setup 1041 setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type; 1042 memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6); 1043 1044 // query client for Legacy Pairing OOB data 1045 setup->sm_have_oob_data = 0; 1046 if (sm_get_oob_data) { 1047 setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk); 1048 } 1049 1050 // if available and SC supported, also ask for SC OOB Data 1051 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1052 memset(setup->sm_ra, 0, 16); 1053 memset(setup->sm_rb, 0, 16); 1054 if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){ 1055 if (sm_get_sc_oob_data){ 1056 if (IS_RESPONDER(sm_conn->sm_role)){ 1057 setup->sm_have_oob_data = (*sm_get_sc_oob_data)( 1058 sm_conn->sm_peer_addr_type, 1059 sm_conn->sm_peer_address, 1060 setup->sm_peer_confirm, 1061 setup->sm_ra); 1062 } else { 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_rb); 1068 } 1069 } else { 1070 setup->sm_have_oob_data = 0; 1071 } 1072 } 1073 #endif 1074 1075 sm_pairing_packet_t * local_packet; 1076 if (IS_RESPONDER(sm_conn->sm_role)){ 1077 // slave 1078 local_packet = &setup->sm_s_pres; 1079 gap_le_get_own_address(&setup->sm_s_addr_type, setup->sm_s_address); 1080 setup->sm_m_addr_type = sm_conn->sm_peer_addr_type; 1081 memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6); 1082 } else { 1083 // master 1084 local_packet = &setup->sm_m_preq; 1085 gap_le_get_own_address(&setup->sm_m_addr_type, setup->sm_m_address); 1086 setup->sm_s_addr_type = sm_conn->sm_peer_addr_type; 1087 memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6); 1088 1089 int key_distribution_flags = sm_key_distribution_flags_for_auth_req(); 1090 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags); 1091 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags); 1092 } 1093 1094 uint8_t auth_req = sm_auth_req; 1095 sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities); 1096 sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data); 1097 sm_pairing_packet_set_auth_req(*local_packet, auth_req); 1098 sm_pairing_packet_set_max_encryption_key_size(*local_packet, sm_max_encryption_key_size); 1099 } 1100 1101 static int sm_stk_generation_init(sm_connection_t * sm_conn){ 1102 1103 sm_pairing_packet_t * remote_packet; 1104 int remote_key_request; 1105 if (IS_RESPONDER(sm_conn->sm_role)){ 1106 // slave / responder 1107 remote_packet = &setup->sm_m_preq; 1108 remote_key_request = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq); 1109 } else { 1110 // master / initiator 1111 remote_packet = &setup->sm_s_pres; 1112 remote_key_request = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres); 1113 } 1114 1115 // check key size 1116 sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet)); 1117 if (sm_conn->sm_actual_encryption_key_size == 0) return SM_REASON_ENCRYPTION_KEY_SIZE; 1118 1119 // decide on STK generation method / SC 1120 sm_setup_tk(); 1121 log_info("SMP: generation method %u", setup->sm_stk_generation_method); 1122 1123 // check if STK generation method is acceptable by client 1124 if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS; 1125 1126 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1127 // LTK (= encyrption information & master identification) only used exchanged for LE Legacy Connection 1128 if (setup->sm_use_secure_connections){ 1129 remote_key_request &= ~SM_KEYDIST_ENC_KEY; 1130 } 1131 #endif 1132 1133 // identical to responder 1134 sm_setup_key_distribution(remote_key_request); 1135 1136 // JUST WORKS doens't provide authentication 1137 sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1; 1138 1139 return 0; 1140 } 1141 1142 static void sm_address_resolution_handle_event(address_resolution_event_t event){ 1143 1144 // cache and reset context 1145 int matched_device_id = sm_address_resolution_test; 1146 address_resolution_mode_t mode = sm_address_resolution_mode; 1147 void * context = sm_address_resolution_context; 1148 1149 // reset context 1150 sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE; 1151 sm_address_resolution_context = NULL; 1152 sm_address_resolution_test = -1; 1153 hci_con_handle_t con_handle = 0; 1154 1155 sm_connection_t * sm_connection; 1156 #ifdef ENABLE_LE_CENTRAL 1157 sm_key_t ltk; 1158 int have_ltk; 1159 int pairing_need; 1160 #endif 1161 switch (mode){ 1162 case ADDRESS_RESOLUTION_GENERAL: 1163 break; 1164 case ADDRESS_RESOLUTION_FOR_CONNECTION: 1165 sm_connection = (sm_connection_t *) context; 1166 con_handle = sm_connection->sm_handle; 1167 switch (event){ 1168 case ADDRESS_RESOLUTION_SUCEEDED: 1169 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED; 1170 sm_connection->sm_le_db_index = matched_device_id; 1171 log_info("ADDRESS_RESOLUTION_SUCEEDED, index %d", sm_connection->sm_le_db_index); 1172 if (sm_connection->sm_role) { 1173 // LTK request received before, IRK required -> start LTK calculation 1174 if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){ 1175 sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 1176 } 1177 break; 1178 } 1179 #ifdef ENABLE_LE_CENTRAL 1180 le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 1181 have_ltk = !sm_is_null_key(ltk); 1182 pairing_need = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received; 1183 log_info("central: pairing request local %u, remote %u => action %u. have_ltk %u", 1184 sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, pairing_need, have_ltk); 1185 // reset requests 1186 sm_connection->sm_security_request_received = 0; 1187 sm_connection->sm_pairing_requested = 0; 1188 1189 // have ltk -> start encryption 1190 // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request 1191 // "When a bond has been created between two devices, any reconnection should result in the local device 1192 // enabling or requesting encryption with the remote device before initiating any service request." 1193 if (have_ltk){ 1194 #ifdef ENABLE_LE_CENTRAL_AUTO_ENCRYPTION 1195 sm_connection->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK; 1196 break; 1197 #else 1198 log_info("central: defer enabling encryption for bonded device"); 1199 #endif 1200 } 1201 // pairint_request -> send pairing request 1202 if (pairing_need){ 1203 sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 1204 break; 1205 } 1206 #endif 1207 break; 1208 case ADDRESS_RESOLUTION_FAILED: 1209 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED; 1210 if (sm_connection->sm_role) { 1211 // LTK request received before, IRK required -> negative LTK reply 1212 if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){ 1213 sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 1214 } 1215 break; 1216 } 1217 #ifdef ENABLE_LE_CENTRAL 1218 if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break; 1219 sm_connection->sm_security_request_received = 0; 1220 sm_connection->sm_pairing_requested = 0; 1221 sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 1222 #endif 1223 break; 1224 } 1225 break; 1226 default: 1227 break; 1228 } 1229 1230 switch (event){ 1231 case ADDRESS_RESOLUTION_SUCEEDED: 1232 sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id); 1233 break; 1234 case ADDRESS_RESOLUTION_FAILED: 1235 sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address); 1236 break; 1237 } 1238 } 1239 1240 static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){ 1241 1242 int le_db_index = -1; 1243 1244 // only store pairing information if both sides are bondable, i.e., the bonadble flag is set 1245 int bonding_enabed = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq) 1246 & sm_pairing_packet_get_auth_req(setup->sm_s_pres) 1247 & SM_AUTHREQ_BONDING ) != 0; 1248 1249 if (bonding_enabed){ 1250 1251 // lookup device based on IRK 1252 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 1253 int i; 1254 for (i=0; i < le_device_db_max_count(); i++){ 1255 sm_key_t irk; 1256 bd_addr_t address; 1257 int address_type = BD_ADDR_TYPE_UNKNOWN; 1258 le_device_db_info(i, &address_type, address, irk); 1259 // skip unused entries 1260 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue; 1261 // compare IRK 1262 if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue; 1263 1264 log_info("sm: device found for IRK, updating"); 1265 le_db_index = i; 1266 break; 1267 } 1268 } else { 1269 // assert IRK is set to zero 1270 memset(setup->sm_peer_irk, 0, 16); 1271 } 1272 1273 // if not found, lookup via public address if possible 1274 log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address)); 1275 if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){ 1276 int i; 1277 for (i=0; i < le_device_db_max_count(); i++){ 1278 bd_addr_t address; 1279 int address_type = BD_ADDR_TYPE_UNKNOWN; 1280 le_device_db_info(i, &address_type, address, NULL); 1281 // skip unused entries 1282 if (address_type == BD_ADDR_TYPE_UNKNOWN) continue; 1283 log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address)); 1284 if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){ 1285 log_info("sm: device found for public address, updating"); 1286 le_db_index = i; 1287 break; 1288 } 1289 } 1290 } 1291 1292 // if not found, add to db 1293 if (le_db_index < 0) { 1294 le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk); 1295 } 1296 1297 if (le_db_index >= 0){ 1298 1299 sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index); 1300 sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED; 1301 1302 #ifdef ENABLE_LE_SIGNED_WRITE 1303 // store local CSRK 1304 setup->sm_le_device_index = le_db_index; 1305 if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 1306 log_info("sm: store local CSRK"); 1307 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk); 1308 le_device_db_local_counter_set(le_db_index, 0); 1309 } 1310 1311 // store remote CSRK 1312 if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 1313 log_info("sm: store remote CSRK"); 1314 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk); 1315 le_device_db_remote_counter_set(le_db_index, 0); 1316 } 1317 #endif 1318 // store encryption information for secure connections: LTK generated by ECDH 1319 if (setup->sm_use_secure_connections){ 1320 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated); 1321 uint8_t zero_rand[8]; 1322 memset(zero_rand, 0, 8); 1323 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size, 1324 sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1); 1325 } 1326 1327 // store encryption information for legacy pairing: peer LTK, EDIV, RAND 1328 else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION) 1329 && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){ 1330 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated); 1331 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk, 1332 sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0); 1333 1334 } 1335 } 1336 } else { 1337 log_info("Ignoring received keys, bonding not enabled"); 1338 } 1339 1340 // keep le_db_index 1341 sm_conn->sm_le_db_index = le_db_index; 1342 } 1343 1344 static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){ 1345 setup->sm_pairing_failed_reason = reason; 1346 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 1347 } 1348 1349 static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){ 1350 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 1351 } 1352 1353 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1354 1355 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn); 1356 static int sm_passkey_used(stk_generation_method_t method); 1357 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method); 1358 1359 static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){ 1360 if (setup->sm_stk_generation_method == OOB){ 1361 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 1362 } else { 1363 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); 1364 } 1365 } 1366 1367 static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){ 1368 if (IS_RESPONDER(sm_conn->sm_role)){ 1369 // Responder 1370 if (setup->sm_stk_generation_method == OOB){ 1371 // generate Nb 1372 log_info("Generate Nb"); 1373 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); 1374 } else { 1375 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 1376 } 1377 } else { 1378 // Initiator role 1379 switch (setup->sm_stk_generation_method){ 1380 case JUST_WORKS: 1381 sm_sc_prepare_dhkey_check(sm_conn); 1382 break; 1383 1384 case NUMERIC_COMPARISON: 1385 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2; 1386 break; 1387 case PK_INIT_INPUT: 1388 case PK_RESP_INPUT: 1389 case PK_BOTH_INPUT: 1390 if (setup->sm_passkey_bit < 20) { 1391 sm_sc_start_calculating_local_confirm(sm_conn); 1392 } else { 1393 sm_sc_prepare_dhkey_check(sm_conn); 1394 } 1395 break; 1396 case OOB: 1397 sm_sc_prepare_dhkey_check(sm_conn); 1398 break; 1399 } 1400 } 1401 } 1402 1403 static void sm_sc_cmac_done(uint8_t * hash){ 1404 log_info("sm_sc_cmac_done: "); 1405 log_info_hexdump(hash, 16); 1406 1407 if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){ 1408 sm_sc_oob_state = SM_SC_OOB_IDLE; 1409 (*sm_sc_oob_callback)(hash, sm_sc_oob_random); 1410 return; 1411 } 1412 1413 sm_connection_t * sm_conn = sm_cmac_connection; 1414 sm_cmac_connection = NULL; 1415 #ifdef ENABLE_CLASSIC 1416 link_key_type_t link_key_type; 1417 #endif 1418 1419 switch (sm_conn->sm_engine_state){ 1420 case SM_SC_W4_CMAC_FOR_CONFIRMATION: 1421 memcpy(setup->sm_local_confirm, hash, 16); 1422 sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION; 1423 break; 1424 case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION: 1425 // check 1426 if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){ 1427 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED); 1428 break; 1429 } 1430 sm_sc_state_after_receiving_random(sm_conn); 1431 break; 1432 case SM_SC_W4_CALCULATE_G2: { 1433 uint32_t vab = big_endian_read_32(hash, 12) % 1000000; 1434 big_endian_store_32(setup->sm_tk, 12, vab); 1435 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 1436 sm_trigger_user_response(sm_conn); 1437 break; 1438 } 1439 case SM_SC_W4_CALCULATE_F5_SALT: 1440 memcpy(setup->sm_t, hash, 16); 1441 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY; 1442 break; 1443 case SM_SC_W4_CALCULATE_F5_MACKEY: 1444 memcpy(setup->sm_mackey, hash, 16); 1445 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK; 1446 break; 1447 case SM_SC_W4_CALCULATE_F5_LTK: 1448 // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk 1449 // Errata Service Release to the Bluetooth Specification: ESR09 1450 // E6405 – Cross transport key derivation from a key of size less than 128 bits 1451 // Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 1452 memcpy(setup->sm_ltk, hash, 16); 1453 memcpy(setup->sm_local_ltk, hash, 16); 1454 sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size); 1455 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK; 1456 break; 1457 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 1458 memcpy(setup->sm_local_dhkey_check, hash, 16); 1459 if (IS_RESPONDER(sm_conn->sm_role)){ 1460 // responder 1461 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){ 1462 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 1463 } else { 1464 sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 1465 } 1466 } else { 1467 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1468 } 1469 break; 1470 case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 1471 if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){ 1472 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 1473 break; 1474 } 1475 if (IS_RESPONDER(sm_conn->sm_role)){ 1476 // responder 1477 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND; 1478 } else { 1479 // initiator 1480 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 1481 } 1482 break; 1483 case SM_SC_W4_CALCULATE_H6_ILK: 1484 memcpy(setup->sm_t, hash, 16); 1485 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_H6_BR_EDR_LINK_KEY; 1486 break; 1487 case SM_SC_W4_CALCULATE_H6_BR_EDR_LINK_KEY: 1488 #ifdef ENABLE_CLASSIC 1489 reverse_128(hash, setup->sm_t); 1490 link_key_type = sm_conn->sm_connection_authenticated ? 1491 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256; 1492 log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type); 1493 if (IS_RESPONDER(sm_conn->sm_role)){ 1494 gap_store_link_key_for_bd_addr(setup->sm_m_address, setup->sm_t, link_key_type); 1495 } else { 1496 gap_store_link_key_for_bd_addr(setup->sm_s_address, setup->sm_t, link_key_type); 1497 } 1498 #endif 1499 if (IS_RESPONDER(sm_conn->sm_role)){ 1500 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 1501 } else { 1502 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 1503 } 1504 sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0); 1505 sm_done_for_handle(sm_conn->sm_handle); 1506 break; 1507 default: 1508 log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state); 1509 break; 1510 } 1511 sm_run(); 1512 } 1513 1514 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){ 1515 const uint16_t message_len = 65; 1516 sm_cmac_connection = sm_conn; 1517 memcpy(sm_cmac_sc_buffer, u, 32); 1518 memcpy(sm_cmac_sc_buffer+32, v, 32); 1519 sm_cmac_sc_buffer[64] = z; 1520 log_info("f4 key"); 1521 log_info_hexdump(x, 16); 1522 log_info("f4 message"); 1523 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1524 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1525 } 1526 1527 static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE}; 1528 static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 }; 1529 static const uint8_t f5_length[] = { 0x01, 0x00}; 1530 1531 static void f5_calculate_salt(sm_connection_t * sm_conn){ 1532 log_info("f5_calculate_salt"); 1533 // calculate salt for f5 1534 const uint16_t message_len = 32; 1535 sm_cmac_connection = sm_conn; 1536 memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len); 1537 sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1538 } 1539 1540 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){ 1541 const uint16_t message_len = 53; 1542 sm_cmac_connection = sm_conn; 1543 1544 // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey 1545 sm_cmac_sc_buffer[0] = 0; 1546 memcpy(sm_cmac_sc_buffer+01, f5_key_id, 4); 1547 memcpy(sm_cmac_sc_buffer+05, n1, 16); 1548 memcpy(sm_cmac_sc_buffer+21, n2, 16); 1549 memcpy(sm_cmac_sc_buffer+37, a1, 7); 1550 memcpy(sm_cmac_sc_buffer+44, a2, 7); 1551 memcpy(sm_cmac_sc_buffer+51, f5_length, 2); 1552 log_info("f5 key"); 1553 log_info_hexdump(t, 16); 1554 log_info("f5 message for MacKey"); 1555 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1556 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1557 } 1558 1559 static void f5_calculate_mackey(sm_connection_t * sm_conn){ 1560 sm_key56_t bd_addr_master, bd_addr_slave; 1561 bd_addr_master[0] = setup->sm_m_addr_type; 1562 bd_addr_slave[0] = setup->sm_s_addr_type; 1563 memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1564 memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1565 if (IS_RESPONDER(sm_conn->sm_role)){ 1566 // responder 1567 f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave); 1568 } else { 1569 // initiator 1570 f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave); 1571 } 1572 } 1573 1574 // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused 1575 static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){ 1576 const uint16_t message_len = 53; 1577 sm_cmac_connection = sm_conn; 1578 sm_cmac_sc_buffer[0] = 1; 1579 // 1..52 setup before 1580 log_info("f5 key"); 1581 log_info_hexdump(t, 16); 1582 log_info("f5 message for LTK"); 1583 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1584 sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1585 } 1586 1587 static void f5_calculate_ltk(sm_connection_t * sm_conn){ 1588 f5_ltk(sm_conn, setup->sm_t); 1589 } 1590 1591 static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w, 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){ 1592 const uint16_t message_len = 65; 1593 sm_cmac_connection = sm_conn; 1594 memcpy(sm_cmac_sc_buffer, n1, 16); 1595 memcpy(sm_cmac_sc_buffer+16, n2, 16); 1596 memcpy(sm_cmac_sc_buffer+32, r, 16); 1597 memcpy(sm_cmac_sc_buffer+48, io_cap, 3); 1598 memcpy(sm_cmac_sc_buffer+51, a1, 7); 1599 memcpy(sm_cmac_sc_buffer+58, a2, 7); 1600 log_info("f6 key"); 1601 log_info_hexdump(w, 16); 1602 log_info("f6 message"); 1603 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1604 sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1605 } 1606 1607 // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32 1608 // - U is 256 bits 1609 // - V is 256 bits 1610 // - X is 128 bits 1611 // - Y is 128 bits 1612 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){ 1613 const uint16_t message_len = 80; 1614 sm_cmac_connection = sm_conn; 1615 memcpy(sm_cmac_sc_buffer, u, 32); 1616 memcpy(sm_cmac_sc_buffer+32, v, 32); 1617 memcpy(sm_cmac_sc_buffer+64, y, 16); 1618 log_info("g2 key"); 1619 log_info_hexdump(x, 16); 1620 log_info("g2 message"); 1621 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1622 sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1623 } 1624 1625 static void g2_calculate(sm_connection_t * sm_conn) { 1626 // calc Va if numeric comparison 1627 if (IS_RESPONDER(sm_conn->sm_role)){ 1628 // responder 1629 g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);; 1630 } else { 1631 // initiator 1632 g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce); 1633 } 1634 } 1635 1636 static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){ 1637 uint8_t z = 0; 1638 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1639 // some form of passkey 1640 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1641 z = 0x80 | ((pk >> setup->sm_passkey_bit) & 1); 1642 setup->sm_passkey_bit++; 1643 } 1644 f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z); 1645 } 1646 1647 static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){ 1648 // OOB 1649 if (setup->sm_stk_generation_method == OOB){ 1650 if (IS_RESPONDER(sm_conn->sm_role)){ 1651 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0); 1652 } else { 1653 f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0); 1654 } 1655 return; 1656 } 1657 1658 uint8_t z = 0; 1659 if (sm_passkey_entry(setup->sm_stk_generation_method)){ 1660 // some form of passkey 1661 uint32_t pk = big_endian_read_32(setup->sm_tk, 12); 1662 // sm_passkey_bit was increased before sending confirm value 1663 z = 0x80 | ((pk >> (setup->sm_passkey_bit-1)) & 1); 1664 } 1665 f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z); 1666 } 1667 1668 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){ 1669 log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0); 1670 1671 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){ 1672 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1673 return; 1674 } else { 1675 sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY; 1676 } 1677 } 1678 1679 static void sm_sc_dhkey_calculated(void * arg){ 1680 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 1681 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 1682 if (sm_conn == NULL) return; 1683 1684 log_info("dhkey"); 1685 log_info_hexdump(&setup->sm_dhkey[0], 32); 1686 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED; 1687 // trigger next step 1688 if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){ 1689 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT; 1690 } 1691 sm_run(); 1692 } 1693 1694 static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){ 1695 // calculate DHKCheck 1696 sm_key56_t bd_addr_master, bd_addr_slave; 1697 bd_addr_master[0] = setup->sm_m_addr_type; 1698 bd_addr_slave[0] = setup->sm_s_addr_type; 1699 memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1700 memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1701 uint8_t iocap_a[3]; 1702 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1703 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1704 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 1705 uint8_t iocap_b[3]; 1706 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 1707 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 1708 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 1709 if (IS_RESPONDER(sm_conn->sm_role)){ 1710 // responder 1711 f6_engine(sm_conn, setup->sm_mackey, setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 1712 } else { 1713 // initiator 1714 f6_engine(sm_conn, setup->sm_mackey, setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 1715 } 1716 } 1717 1718 static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){ 1719 // validate E = f6() 1720 sm_key56_t bd_addr_master, bd_addr_slave; 1721 bd_addr_master[0] = setup->sm_m_addr_type; 1722 bd_addr_slave[0] = setup->sm_s_addr_type; 1723 memcpy(&bd_addr_master[1], setup->sm_m_address, 6); 1724 memcpy(&bd_addr_slave[1], setup->sm_s_address, 6); 1725 1726 uint8_t iocap_a[3]; 1727 iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq); 1728 iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq); 1729 iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq); 1730 uint8_t iocap_b[3]; 1731 iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres); 1732 iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres); 1733 iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres); 1734 if (IS_RESPONDER(sm_conn->sm_role)){ 1735 // responder 1736 f6_engine(sm_conn, setup->sm_mackey, setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave); 1737 } else { 1738 // initiator 1739 f6_engine(sm_conn, setup->sm_mackey, setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master); 1740 } 1741 } 1742 1743 1744 // 1745 // Link Key Conversion Function h6 1746 // 1747 // h6(W, keyID) = AES-CMACW(keyID) 1748 // - W is 128 bits 1749 // - keyID is 32 bits 1750 static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){ 1751 const uint16_t message_len = 4; 1752 sm_cmac_connection = sm_conn; 1753 big_endian_store_32(sm_cmac_sc_buffer, 0, key_id); 1754 log_info("h6 key"); 1755 log_info_hexdump(w, 16); 1756 log_info("h6 message"); 1757 log_info_hexdump(sm_cmac_sc_buffer, message_len); 1758 sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done); 1759 } 1760 1761 // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated) 1762 // Errata Service Release to the Bluetooth Specification: ESR09 1763 // E6405 – Cross transport key derivation from a key of size less than 128 bits 1764 // "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked." 1765 static void h6_calculate_ilk(sm_connection_t * sm_conn){ 1766 h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031); // "tmp1" 1767 } 1768 1769 static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){ 1770 h6_engine(sm_conn, setup->sm_t, 0x6c656272); // "lebr" 1771 } 1772 1773 #endif 1774 1775 // key management legacy connections: 1776 // - potentially two different LTKs based on direction. each device stores LTK provided by peer 1777 // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect) 1778 // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder 1779 // - responder reconnects: responder uses LTK receveived from master 1780 1781 // key management secure connections: 1782 // - both devices store same LTK from ECDH key exchange. 1783 1784 #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL) 1785 static void sm_load_security_info(sm_connection_t * sm_connection){ 1786 int encryption_key_size; 1787 int authenticated; 1788 int authorized; 1789 int secure_connection; 1790 1791 // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled 1792 le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk, 1793 &encryption_key_size, &authenticated, &authorized, &secure_connection); 1794 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); 1795 sm_connection->sm_actual_encryption_key_size = encryption_key_size; 1796 sm_connection->sm_connection_authenticated = authenticated; 1797 sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN; 1798 sm_connection->sm_connection_sc = secure_connection; 1799 } 1800 #endif 1801 1802 #ifdef ENABLE_LE_PERIPHERAL 1803 static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){ 1804 memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8); 1805 setup->sm_local_ediv = sm_connection->sm_local_ediv; 1806 // re-establish used key encryption size 1807 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 1808 sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7] & 0x0f) + 1; 1809 // no db for authenticated flag hack: flag is stored in bit 4 of LSB 1810 sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7] & 0x10) >> 4; 1811 // Legacy paring -> not SC 1812 sm_connection->sm_connection_sc = 0; 1813 log_info("sm: received ltk request with key size %u, authenticated %u", 1814 sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated); 1815 sm_connection->sm_engine_state = SM_RESPONDER_PH4_Y_GET_ENC; 1816 sm_run(); 1817 } 1818 #endif 1819 1820 static void sm_run(void){ 1821 1822 btstack_linked_list_iterator_t it; 1823 1824 // assert that stack has already bootet 1825 if (hci_get_state() != HCI_STATE_WORKING) return; 1826 1827 // assert that we can send at least commands 1828 if (!hci_can_send_command_packet_now()) return; 1829 1830 // pause until IR/ER are ready 1831 if (sm_persistent_keys_random_active) return; 1832 1833 // 1834 // non-connection related behaviour 1835 // 1836 1837 // distributed key generation 1838 switch (dkg_state){ 1839 case DKG_CALC_IRK: 1840 // already busy? 1841 if (sm_aes128_state == SM_AES128_IDLE) { 1842 log_info("DKG_CALC_IRK started"); 1843 // IRK = d1(IR, 1, 0) 1844 sm_d1_d_prime(1, 0, sm_aes128_plaintext); // plaintext = d1 prime 1845 sm_aes128_state = SM_AES128_ACTIVE; 1846 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_irk, sm_handle_encryption_result_dkg_irk, NULL); 1847 return; 1848 } 1849 break; 1850 case DKG_CALC_DHK: 1851 // already busy? 1852 if (sm_aes128_state == SM_AES128_IDLE) { 1853 log_info("DKG_CALC_DHK started"); 1854 // DHK = d1(IR, 3, 0) 1855 sm_d1_d_prime(3, 0, sm_aes128_plaintext); // plaintext = d1 prime 1856 sm_aes128_state = SM_AES128_ACTIVE; 1857 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_dhk, sm_handle_encryption_result_dkg_dhk, NULL); 1858 return; 1859 } 1860 break; 1861 default: 1862 break; 1863 } 1864 1865 // random address updates 1866 switch (rau_state){ 1867 case RAU_GET_RANDOM: 1868 rau_state = RAU_W4_RANDOM; 1869 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL); 1870 return; 1871 case RAU_GET_ENC: 1872 // already busy? 1873 if (sm_aes128_state == SM_AES128_IDLE) { 1874 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext); 1875 sm_aes128_state = SM_AES128_ACTIVE; 1876 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL); 1877 return; 1878 } 1879 break; 1880 case RAU_SET_ADDRESS: 1881 log_info("New random address: %s", bd_addr_to_str(sm_random_address)); 1882 rau_state = RAU_IDLE; 1883 hci_send_cmd(&hci_le_set_random_address, sm_random_address); 1884 return; 1885 default: 1886 break; 1887 } 1888 1889 // CSRK Lookup 1890 // -- if csrk lookup ready, find connection that require csrk lookup 1891 if (sm_address_resolution_idle()){ 1892 hci_connections_get_iterator(&it); 1893 while(btstack_linked_list_iterator_has_next(&it)){ 1894 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 1895 sm_connection_t * sm_connection = &hci_connection->sm_connection; 1896 if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){ 1897 // and start lookup 1898 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); 1899 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED; 1900 break; 1901 } 1902 } 1903 } 1904 1905 // -- if csrk lookup ready, resolved addresses for received addresses 1906 if (sm_address_resolution_idle()) { 1907 if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){ 1908 sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue; 1909 btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry); 1910 sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL); 1911 btstack_memory_sm_lookup_entry_free(entry); 1912 } 1913 } 1914 1915 // -- Continue with CSRK device lookup by public or resolvable private address 1916 if (!sm_address_resolution_idle()){ 1917 log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count()); 1918 while (sm_address_resolution_test < le_device_db_max_count()){ 1919 int addr_type = BD_ADDR_TYPE_UNKNOWN; 1920 bd_addr_t addr; 1921 sm_key_t irk; 1922 le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk); 1923 log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr)); 1924 1925 // skip unused entries 1926 if (addr_type == BD_ADDR_TYPE_UNKNOWN){ 1927 sm_address_resolution_test++; 1928 continue; 1929 } 1930 1931 if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){ 1932 log_info("LE Device Lookup: found CSRK by { addr_type, address} "); 1933 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCEEDED); 1934 break; 1935 } 1936 1937 // if connection type is public, it must be a different one 1938 if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){ 1939 sm_address_resolution_test++; 1940 continue; 1941 } 1942 1943 if (sm_aes128_state == SM_AES128_ACTIVE) break; 1944 1945 log_info("LE Device Lookup: calculate AH"); 1946 log_info_key("IRK", irk); 1947 1948 memcpy(sm_aes128_key, irk, 16); 1949 sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext); 1950 sm_address_resolution_ah_calculation_active = 1; 1951 sm_aes128_state = SM_AES128_ACTIVE; 1952 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL); 1953 return; 1954 } 1955 1956 if (sm_address_resolution_test >= le_device_db_max_count()){ 1957 log_info("LE Device Lookup: not found"); 1958 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED); 1959 } 1960 } 1961 1962 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1963 switch (sm_sc_oob_state){ 1964 case SM_SC_OOB_W2_CALC_CONFIRM: 1965 if (!sm_cmac_ready()) break; 1966 sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM; 1967 f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0); 1968 return; 1969 default: 1970 break; 1971 } 1972 #endif 1973 1974 // assert that we can send at least commands - cmd might have been sent by crypto engine 1975 if (!hci_can_send_command_packet_now()) return; 1976 1977 // handle basic actions that don't requires the full context 1978 hci_connections_get_iterator(&it); 1979 while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){ 1980 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 1981 sm_connection_t * sm_connection = &hci_connection->sm_connection; 1982 switch(sm_connection->sm_engine_state){ 1983 // responder side 1984 case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY: 1985 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 1986 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 1987 return; 1988 1989 #ifdef ENABLE_LE_SECURE_CONNECTIONS 1990 case SM_SC_RECEIVED_LTK_REQUEST: 1991 switch (sm_connection->sm_irk_lookup_state){ 1992 case IRK_LOOKUP_FAILED: 1993 log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Failed)"); 1994 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 1995 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 1996 return; 1997 default: 1998 break; 1999 } 2000 break; 2001 #endif 2002 default: 2003 break; 2004 } 2005 } 2006 2007 // 2008 // active connection handling 2009 // -- use loop to handle next connection if lock on setup context is released 2010 2011 while (1) { 2012 2013 // Find connections that requires setup context and make active if no other is locked 2014 hci_connections_get_iterator(&it); 2015 while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){ 2016 hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 2017 sm_connection_t * sm_connection = &hci_connection->sm_connection; 2018 // - if no connection locked and we're ready/waiting for setup context, fetch it and start 2019 int done = 1; 2020 int err; 2021 UNUSED(err); 2022 2023 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2024 // assert ec key is ready 2025 if ((sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED) 2026 || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)){ 2027 if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){ 2028 sm_ec_generate_new_key(); 2029 } 2030 if (ec_key_generation_state != EC_KEY_GENERATION_DONE){ 2031 continue; 2032 } 2033 } 2034 #endif 2035 2036 switch (sm_connection->sm_engine_state) { 2037 #ifdef ENABLE_LE_PERIPHERAL 2038 case SM_RESPONDER_SEND_SECURITY_REQUEST: 2039 // send packet if possible, 2040 if (l2cap_can_send_fixed_channel_packet_now(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)){ 2041 const uint8_t buffer[2] = { SM_CODE_SECURITY_REQUEST, sm_auth_req}; 2042 sm_connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST; 2043 l2cap_send_connectionless(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2044 } else { 2045 l2cap_request_can_send_fix_channel_now_event(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 2046 } 2047 // don't lock sxetup context yet 2048 done = 0; 2049 break; 2050 case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED: 2051 sm_reset_setup(); 2052 sm_init_setup(sm_connection); 2053 // recover pairing request 2054 memcpy(&setup->sm_m_preq, &sm_connection->sm_m_preq, sizeof(sm_pairing_packet_t)); 2055 err = sm_stk_generation_init(sm_connection); 2056 2057 #ifdef ENABLE_TESTING_SUPPORT 2058 if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){ 2059 log_info("testing_support: respond with pairing failure %u", test_pairing_failure); 2060 err = test_pairing_failure; 2061 } 2062 #endif 2063 if (err){ 2064 setup->sm_pairing_failed_reason = err; 2065 sm_connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 2066 break; 2067 } 2068 sm_timeout_start(sm_connection); 2069 // generate random number first, if we need to show passkey 2070 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 2071 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); 2072 break; 2073 } 2074 sm_connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE; 2075 break; 2076 case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST: 2077 sm_reset_setup(); 2078 sm_start_calculating_ltk_from_ediv_and_rand(sm_connection); 2079 break; 2080 2081 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2082 case SM_SC_RECEIVED_LTK_REQUEST: 2083 switch (sm_connection->sm_irk_lookup_state){ 2084 case IRK_LOOKUP_SUCCEEDED: 2085 // assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null 2086 // start using context by loading security info 2087 sm_reset_setup(); 2088 sm_load_security_info(sm_connection); 2089 if ((setup->sm_peer_ediv == 0) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){ 2090 memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16); 2091 sm_connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 2092 break; 2093 } 2094 log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)"); 2095 sm_connection->sm_engine_state = SM_RESPONDER_IDLE; 2096 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle); 2097 // don't lock setup context yet 2098 return; 2099 default: 2100 // just wait until IRK lookup is completed 2101 // don't lock setup context yet 2102 done = 0; 2103 break; 2104 } 2105 break; 2106 #endif /* ENABLE_LE_SECURE_CONNECTIONS */ 2107 #endif /* ENABLE_LE_PERIPHERAL */ 2108 2109 #ifdef ENABLE_LE_CENTRAL 2110 case SM_INITIATOR_PH0_HAS_LTK: 2111 sm_reset_setup(); 2112 sm_load_security_info(sm_connection); 2113 sm_connection->sm_engine_state = SM_INITIATOR_PH0_SEND_START_ENCRYPTION; 2114 break; 2115 case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST: 2116 sm_reset_setup(); 2117 sm_init_setup(sm_connection); 2118 sm_timeout_start(sm_connection); 2119 sm_connection->sm_engine_state = SM_INITIATOR_PH1_SEND_PAIRING_REQUEST; 2120 break; 2121 #endif 2122 2123 default: 2124 done = 0; 2125 break; 2126 } 2127 if (done){ 2128 sm_active_connection_handle = sm_connection->sm_handle; 2129 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); 2130 } 2131 } 2132 2133 // 2134 // active connection handling 2135 // 2136 2137 if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return; 2138 2139 sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle); 2140 if (!connection) { 2141 log_info("no connection for handle 0x%04x", sm_active_connection_handle); 2142 return; 2143 } 2144 2145 // assert that we could send a SM PDU - not needed for all of the following 2146 if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) { 2147 log_info("cannot send now, requesting can send now event"); 2148 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 2149 return; 2150 } 2151 2152 // send keypress notifications 2153 if (setup->sm_keypress_notification){ 2154 int i; 2155 uint8_t flags = setup->sm_keypress_notification & 0x1f; 2156 uint8_t num_actions = setup->sm_keypress_notification >> 5; 2157 uint8_t action = 0; 2158 for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){ 2159 if (flags & (1<<i)){ 2160 int clear_flag = 1; 2161 switch (i){ 2162 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 2163 case SM_KEYPRESS_PASSKEY_CLEARED: 2164 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 2165 default: 2166 break; 2167 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 2168 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 2169 num_actions--; 2170 clear_flag = num_actions == 0; 2171 break; 2172 } 2173 if (clear_flag){ 2174 flags &= ~(1<<i); 2175 } 2176 action = i; 2177 break; 2178 } 2179 } 2180 setup->sm_keypress_notification = (num_actions << 5) | flags; 2181 2182 // send keypress notification 2183 uint8_t buffer[2]; 2184 buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION; 2185 buffer[1] = action; 2186 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2187 2188 // try 2189 l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 2190 return; 2191 } 2192 2193 int key_distribution_flags; 2194 UNUSED(key_distribution_flags); 2195 2196 log_info("sm_run: state %u", connection->sm_engine_state); 2197 if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) { 2198 log_info("sm_run // cannot send"); 2199 } 2200 switch (connection->sm_engine_state){ 2201 2202 // general 2203 case SM_GENERAL_SEND_PAIRING_FAILED: { 2204 uint8_t buffer[2]; 2205 buffer[0] = SM_CODE_PAIRING_FAILED; 2206 buffer[1] = setup->sm_pairing_failed_reason; 2207 connection->sm_engine_state = connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 2208 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2209 sm_notify_client_status_reason(connection, ERROR_CODE_AUTHENTICATION_FAILURE, setup->sm_pairing_failed_reason); 2210 sm_done_for_handle(connection->sm_handle); 2211 break; 2212 } 2213 2214 // responding state 2215 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2216 case SM_SC_W2_CMAC_FOR_CONFIRMATION: 2217 if (!sm_cmac_ready()) break; 2218 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION; 2219 sm_sc_calculate_local_confirm(connection); 2220 break; 2221 case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION: 2222 if (!sm_cmac_ready()) break; 2223 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION; 2224 sm_sc_calculate_remote_confirm(connection); 2225 break; 2226 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 2227 if (!sm_cmac_ready()) break; 2228 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK; 2229 sm_sc_calculate_f6_for_dhkey_check(connection); 2230 break; 2231 case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK: 2232 if (!sm_cmac_ready()) break; 2233 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 2234 sm_sc_calculate_f6_to_verify_dhkey_check(connection); 2235 break; 2236 case SM_SC_W2_CALCULATE_F5_SALT: 2237 if (!sm_cmac_ready()) break; 2238 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT; 2239 f5_calculate_salt(connection); 2240 break; 2241 case SM_SC_W2_CALCULATE_F5_MACKEY: 2242 if (!sm_cmac_ready()) break; 2243 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY; 2244 f5_calculate_mackey(connection); 2245 break; 2246 case SM_SC_W2_CALCULATE_F5_LTK: 2247 if (!sm_cmac_ready()) break; 2248 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK; 2249 f5_calculate_ltk(connection); 2250 break; 2251 case SM_SC_W2_CALCULATE_G2: 2252 if (!sm_cmac_ready()) break; 2253 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2; 2254 g2_calculate(connection); 2255 break; 2256 case SM_SC_W2_CALCULATE_H6_ILK: 2257 if (!sm_cmac_ready()) break; 2258 connection->sm_engine_state = SM_SC_W4_CALCULATE_H6_ILK; 2259 h6_calculate_ilk(connection); 2260 break; 2261 case SM_SC_W2_CALCULATE_H6_BR_EDR_LINK_KEY: 2262 if (!sm_cmac_ready()) break; 2263 connection->sm_engine_state = SM_SC_W4_CALCULATE_H6_BR_EDR_LINK_KEY; 2264 h6_calculate_br_edr_link_key(connection); 2265 break; 2266 #endif 2267 2268 #ifdef ENABLE_LE_CENTRAL 2269 // initiator side 2270 case SM_INITIATOR_PH0_SEND_START_ENCRYPTION: { 2271 sm_key_t peer_ltk_flipped; 2272 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped); 2273 connection->sm_engine_state = SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED; 2274 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv); 2275 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0); 2276 uint32_t rand_low = big_endian_read_32(setup->sm_peer_rand, 4); 2277 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped); 2278 return; 2279 } 2280 2281 case SM_INITIATOR_PH1_SEND_PAIRING_REQUEST: 2282 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST); 2283 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE; 2284 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t)); 2285 sm_timeout_reset(connection); 2286 break; 2287 #endif 2288 2289 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2290 2291 case SM_SC_SEND_PUBLIC_KEY_COMMAND: { 2292 int trigger_user_response = 0; 2293 int trigger_start_calculating_local_confirm = 0; 2294 uint8_t buffer[65]; 2295 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY; 2296 // 2297 reverse_256(&ec_q[0], &buffer[1]); 2298 reverse_256(&ec_q[32], &buffer[33]); 2299 2300 #ifdef ENABLE_TESTING_SUPPORT 2301 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){ 2302 log_info("testing_support: invalidating public key"); 2303 // flip single bit of public key coordinate 2304 buffer[1] ^= 1; 2305 } 2306 #endif 2307 2308 // stk generation method 2309 // passkey entry: notify app to show passkey or to request passkey 2310 switch (setup->sm_stk_generation_method){ 2311 case JUST_WORKS: 2312 case NUMERIC_COMPARISON: 2313 if (IS_RESPONDER(connection->sm_role)){ 2314 // responder 2315 trigger_start_calculating_local_confirm = 1; 2316 connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE; 2317 } else { 2318 // initiator 2319 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2320 } 2321 break; 2322 case PK_INIT_INPUT: 2323 case PK_RESP_INPUT: 2324 case PK_BOTH_INPUT: 2325 // use random TK for display 2326 memcpy(setup->sm_ra, setup->sm_tk, 16); 2327 memcpy(setup->sm_rb, setup->sm_tk, 16); 2328 setup->sm_passkey_bit = 0; 2329 2330 if (IS_RESPONDER(connection->sm_role)){ 2331 // responder 2332 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2333 } else { 2334 // initiator 2335 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2336 } 2337 trigger_user_response = 1; 2338 break; 2339 case OOB: 2340 if (IS_RESPONDER(connection->sm_role)){ 2341 // responder 2342 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2343 } else { 2344 // initiator 2345 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2346 } 2347 break; 2348 } 2349 2350 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2351 sm_timeout_reset(connection); 2352 2353 // trigger user response and calc confirm after sending pdu 2354 if (trigger_user_response){ 2355 sm_trigger_user_response(connection); 2356 } 2357 if (trigger_start_calculating_local_confirm){ 2358 sm_sc_start_calculating_local_confirm(connection); 2359 } 2360 break; 2361 } 2362 case SM_SC_SEND_CONFIRMATION: { 2363 uint8_t buffer[17]; 2364 buffer[0] = SM_CODE_PAIRING_CONFIRM; 2365 reverse_128(setup->sm_local_confirm, &buffer[1]); 2366 if (IS_RESPONDER(connection->sm_role)){ 2367 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2368 } else { 2369 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2370 } 2371 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2372 sm_timeout_reset(connection); 2373 break; 2374 } 2375 case SM_SC_SEND_PAIRING_RANDOM: { 2376 uint8_t buffer[17]; 2377 buffer[0] = SM_CODE_PAIRING_RANDOM; 2378 reverse_128(setup->sm_local_nonce, &buffer[1]); 2379 log_info("stk method %u, num bits %u", setup->sm_stk_generation_method, setup->sm_passkey_bit); 2380 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20)){ 2381 log_info("SM_SC_SEND_PAIRING_RANDOM A"); 2382 if (IS_RESPONDER(connection->sm_role)){ 2383 // responder 2384 connection->sm_engine_state = SM_SC_W4_CONFIRMATION; 2385 } else { 2386 // initiator 2387 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2388 } 2389 } else { 2390 log_info("SM_SC_SEND_PAIRING_RANDOM B"); 2391 if (IS_RESPONDER(connection->sm_role)){ 2392 // responder 2393 if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){ 2394 log_info("SM_SC_SEND_PAIRING_RANDOM B1"); 2395 connection->sm_engine_state = SM_SC_W2_CALCULATE_G2; 2396 } else { 2397 log_info("SM_SC_SEND_PAIRING_RANDOM B2"); 2398 sm_sc_prepare_dhkey_check(connection); 2399 } 2400 } else { 2401 // initiator 2402 connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM; 2403 } 2404 } 2405 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2406 sm_timeout_reset(connection); 2407 break; 2408 } 2409 case SM_SC_SEND_DHKEY_CHECK_COMMAND: { 2410 uint8_t buffer[17]; 2411 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK; 2412 reverse_128(setup->sm_local_dhkey_check, &buffer[1]); 2413 2414 if (IS_RESPONDER(connection->sm_role)){ 2415 connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC; 2416 } else { 2417 connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND; 2418 } 2419 2420 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2421 sm_timeout_reset(connection); 2422 break; 2423 } 2424 2425 #endif 2426 2427 #ifdef ENABLE_LE_PERIPHERAL 2428 case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE: 2429 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE); 2430 2431 // start with initiator key dist flags 2432 key_distribution_flags = sm_key_distribution_flags_for_auth_req(); 2433 2434 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2435 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection 2436 if (setup->sm_use_secure_connections){ 2437 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY; 2438 } 2439 #endif 2440 // setup in response 2441 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); 2442 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); 2443 2444 // update key distribution after ENC was dropped 2445 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres)); 2446 2447 if (setup->sm_use_secure_connections){ 2448 connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND; 2449 } else { 2450 connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM; 2451 } 2452 2453 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t)); 2454 sm_timeout_reset(connection); 2455 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 2456 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){ 2457 sm_trigger_user_response(connection); 2458 } 2459 return; 2460 #endif 2461 2462 case SM_PH2_SEND_PAIRING_RANDOM: { 2463 uint8_t buffer[17]; 2464 buffer[0] = SM_CODE_PAIRING_RANDOM; 2465 reverse_128(setup->sm_local_random, &buffer[1]); 2466 if (IS_RESPONDER(connection->sm_role)){ 2467 connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST; 2468 } else { 2469 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM; 2470 } 2471 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2472 sm_timeout_reset(connection); 2473 break; 2474 } 2475 2476 case SM_PH2_C1_GET_ENC_A: 2477 // already busy? 2478 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2479 // calculate confirm using aes128 engine - step 1 2480 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); 2481 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A; 2482 sm_aes128_state = SM_AES128_ACTIVE; 2483 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); 2484 break; 2485 2486 case SM_PH2_C1_GET_ENC_C: 2487 // already busy? 2488 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2489 // calculate m_confirm using aes128 engine - step 1 2490 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); 2491 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C; 2492 sm_aes128_state = SM_AES128_ACTIVE; 2493 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); 2494 break; 2495 2496 case SM_PH2_CALC_STK: 2497 // already busy? 2498 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2499 // calculate STK 2500 if (IS_RESPONDER(connection->sm_role)){ 2501 sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext); 2502 } else { 2503 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 2504 } 2505 connection->sm_engine_state = SM_PH2_W4_STK; 2506 sm_aes128_state = SM_AES128_ACTIVE; 2507 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); 2508 break; 2509 2510 case SM_PH3_Y_GET_ENC: 2511 // already busy? 2512 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2513 // PH3B2 - calculate Y from - enc 2514 2515 // dm helper (was sm_dm_r_prime) 2516 // r' = padding || r 2517 // r - 64 bit value 2518 memset(&sm_aes128_plaintext[0], 0, 8); 2519 memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 2520 2521 // Y = dm(DHK, Rand) 2522 connection->sm_engine_state = SM_PH3_Y_W4_ENC; 2523 sm_aes128_state = SM_AES128_ACTIVE; 2524 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); 2525 break; 2526 2527 case SM_PH2_C1_SEND_PAIRING_CONFIRM: { 2528 uint8_t buffer[17]; 2529 buffer[0] = SM_CODE_PAIRING_CONFIRM; 2530 reverse_128(setup->sm_local_confirm, &buffer[1]); 2531 if (IS_RESPONDER(connection->sm_role)){ 2532 connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM; 2533 } else { 2534 connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM; 2535 } 2536 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2537 sm_timeout_reset(connection); 2538 return; 2539 } 2540 #ifdef ENABLE_LE_PERIPHERAL 2541 case SM_RESPONDER_PH2_SEND_LTK_REPLY: { 2542 sm_key_t stk_flipped; 2543 reverse_128(setup->sm_ltk, stk_flipped); 2544 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 2545 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped); 2546 return; 2547 } 2548 case SM_RESPONDER_PH4_SEND_LTK_REPLY: { 2549 sm_key_t ltk_flipped; 2550 reverse_128(setup->sm_ltk, ltk_flipped); 2551 connection->sm_engine_state = SM_RESPONDER_IDLE; 2552 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped); 2553 sm_done_for_handle(connection->sm_handle); 2554 return; 2555 } 2556 case SM_RESPONDER_PH4_Y_GET_ENC: 2557 // already busy? 2558 if (sm_aes128_state == SM_AES128_ACTIVE) break; 2559 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv); 2560 2561 // dm helper (was sm_dm_r_prime) 2562 // r' = padding || r 2563 // r - 64 bit value 2564 memset(&sm_aes128_plaintext[0], 0, 8); 2565 memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8); 2566 2567 // Y = dm(DHK, Rand) 2568 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC; 2569 sm_aes128_state = SM_AES128_ACTIVE; 2570 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); 2571 return; 2572 #endif 2573 #ifdef ENABLE_LE_CENTRAL 2574 case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: { 2575 sm_key_t stk_flipped; 2576 reverse_128(setup->sm_ltk, stk_flipped); 2577 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED; 2578 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped); 2579 return; 2580 } 2581 #endif 2582 2583 case SM_PH3_DISTRIBUTE_KEYS: 2584 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){ 2585 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2586 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 2587 uint8_t buffer[17]; 2588 buffer[0] = SM_CODE_ENCRYPTION_INFORMATION; 2589 reverse_128(setup->sm_ltk, &buffer[1]); 2590 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2591 sm_timeout_reset(connection); 2592 return; 2593 } 2594 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){ 2595 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2596 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 2597 uint8_t buffer[11]; 2598 buffer[0] = SM_CODE_MASTER_IDENTIFICATION; 2599 little_endian_store_16(buffer, 1, setup->sm_local_ediv); 2600 reverse_64(setup->sm_local_rand, &buffer[3]); 2601 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2602 sm_timeout_reset(connection); 2603 return; 2604 } 2605 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){ 2606 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2607 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 2608 uint8_t buffer[17]; 2609 buffer[0] = SM_CODE_IDENTITY_INFORMATION; 2610 reverse_128(sm_persistent_irk, &buffer[1]); 2611 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2612 sm_timeout_reset(connection); 2613 return; 2614 } 2615 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){ 2616 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2617 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 2618 bd_addr_t local_address; 2619 uint8_t buffer[8]; 2620 buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION; 2621 switch (gap_random_address_get_mode()){ 2622 case GAP_RANDOM_ADDRESS_TYPE_OFF: 2623 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 2624 // public or static random 2625 gap_le_get_own_address(&buffer[1], local_address); 2626 break; 2627 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 2628 case GAP_RANDOM_ADDRESS_RESOLVABLE: 2629 // fallback to public 2630 gap_local_bd_addr(local_address); 2631 buffer[1] = 0; 2632 break; 2633 } 2634 reverse_bd_addr(local_address, &buffer[2]); 2635 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2636 sm_timeout_reset(connection); 2637 return; 2638 } 2639 if (setup->sm_key_distribution_send_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){ 2640 setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2641 setup->sm_key_distribution_sent_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 2642 2643 #ifdef ENABLE_LE_SIGNED_WRITE 2644 // hack to reproduce test runs 2645 if (test_use_fixed_local_csrk){ 2646 memset(setup->sm_local_csrk, 0xcc, 16); 2647 } 2648 2649 // store local CSRK 2650 if (setup->sm_le_device_index >= 0){ 2651 log_info("sm: store local CSRK"); 2652 le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk); 2653 le_device_db_local_counter_set(setup->sm_le_device_index, 0); 2654 } 2655 #endif 2656 2657 uint8_t buffer[17]; 2658 buffer[0] = SM_CODE_SIGNING_INFORMATION; 2659 reverse_128(setup->sm_local_csrk, &buffer[1]); 2660 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer)); 2661 sm_timeout_reset(connection); 2662 return; 2663 } 2664 2665 // keys are sent 2666 if (IS_RESPONDER(connection->sm_role)){ 2667 // slave -> receive master keys if any 2668 if (sm_key_distribution_all_received(connection)){ 2669 sm_key_distribution_handle_all_received(connection); 2670 connection->sm_engine_state = SM_RESPONDER_IDLE; 2671 sm_notify_client_status_reason(connection, ERROR_CODE_SUCCESS, 0); 2672 sm_done_for_handle(connection->sm_handle); 2673 } else { 2674 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 2675 } 2676 } else { 2677 // master -> all done 2678 connection->sm_engine_state = SM_INITIATOR_CONNECTED; 2679 sm_notify_client_status_reason(connection, ERROR_CODE_SUCCESS, 0); 2680 sm_done_for_handle(connection->sm_handle); 2681 } 2682 break; 2683 2684 default: 2685 break; 2686 } 2687 2688 // check again if active connection was released 2689 if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break; 2690 } 2691 } 2692 2693 // sm_aes128_state stays active 2694 static void sm_handle_encryption_result_enc_a(void *arg){ 2695 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2696 sm_aes128_state = SM_AES128_IDLE; 2697 2698 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2699 if (connection == NULL) return; 2700 2701 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 2702 sm_aes128_state = SM_AES128_ACTIVE; 2703 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); 2704 } 2705 2706 static void sm_handle_encryption_result_enc_b(void *arg){ 2707 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2708 sm_aes128_state = SM_AES128_IDLE; 2709 2710 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2711 if (connection == NULL) return; 2712 2713 log_info_key("c1!", setup->sm_local_confirm); 2714 connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM; 2715 sm_run(); 2716 } 2717 2718 // sm_aes128_state stays active 2719 static void sm_handle_encryption_result_enc_c(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 sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value); 2727 sm_aes128_state = SM_AES128_ACTIVE; 2728 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); 2729 } 2730 2731 static void sm_handle_encryption_result_enc_d(void * arg){ 2732 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2733 sm_aes128_state = SM_AES128_IDLE; 2734 2735 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2736 if (connection == NULL) return; 2737 2738 log_info_key("c1!", sm_aes128_ciphertext); 2739 if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){ 2740 setup->sm_pairing_failed_reason = SM_REASON_CONFIRM_VALUE_FAILED; 2741 connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 2742 sm_run(); 2743 return; 2744 } 2745 if (IS_RESPONDER(connection->sm_role)){ 2746 connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 2747 sm_run(); 2748 } else { 2749 sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext); 2750 sm_aes128_state = SM_AES128_ACTIVE; 2751 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); 2752 } 2753 } 2754 2755 static void sm_handle_encryption_result_enc_stk(void *arg){ 2756 sm_aes128_state = SM_AES128_IDLE; 2757 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2758 2759 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2760 if (connection == NULL) return; 2761 2762 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 2763 log_info_key("stk", setup->sm_ltk); 2764 if (IS_RESPONDER(connection->sm_role)){ 2765 connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 2766 } else { 2767 connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION; 2768 } 2769 sm_run(); 2770 } 2771 2772 // sm_aes128_state stays active 2773 static void sm_handle_encryption_result_enc_ph3_y(void *arg){ 2774 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2775 sm_aes128_state = SM_AES128_IDLE; 2776 2777 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2778 if (connection == NULL) return; 2779 2780 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 2781 log_info_hex16("y", setup->sm_local_y); 2782 // PH3B3 - calculate EDIV 2783 setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div; 2784 log_info_hex16("ediv", setup->sm_local_ediv); 2785 // PH3B4 - calculate LTK - enc 2786 // LTK = d1(ER, DIV, 0)) 2787 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 2788 sm_aes128_state = SM_AES128_ACTIVE; 2789 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); 2790 } 2791 2792 #ifdef ENABLE_LE_PERIPHERAL 2793 // sm_aes128_state stays active 2794 static void sm_handle_encryption_result_enc_ph4_y(void *arg){ 2795 sm_aes128_state = SM_AES128_IDLE; 2796 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2797 2798 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2799 if (connection == NULL) return; 2800 2801 setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14); 2802 log_info_hex16("y", setup->sm_local_y); 2803 2804 // PH3B3 - calculate DIV 2805 setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv; 2806 log_info_hex16("ediv", setup->sm_local_ediv); 2807 // PH3B4 - calculate LTK - enc 2808 // LTK = d1(ER, DIV, 0)) 2809 sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext); 2810 sm_aes128_state = SM_AES128_ACTIVE; 2811 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); 2812 } 2813 #endif 2814 2815 // sm_aes128_state stays active 2816 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){ 2817 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2818 sm_aes128_state = SM_AES128_IDLE; 2819 2820 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2821 if (connection == NULL) return; 2822 2823 log_info_key("ltk", setup->sm_ltk); 2824 // calc CSRK next 2825 sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext); 2826 sm_aes128_state = SM_AES128_ACTIVE; 2827 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); 2828 } 2829 2830 static void sm_handle_encryption_result_enc_csrk(void *arg){ 2831 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2832 sm_aes128_state = SM_AES128_IDLE; 2833 2834 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2835 if (connection == NULL) return; 2836 2837 sm_aes128_state = SM_AES128_IDLE; 2838 log_info_key("csrk", setup->sm_local_csrk); 2839 if (setup->sm_key_distribution_send_set){ 2840 connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 2841 } else { 2842 // no keys to send, just continue 2843 if (IS_RESPONDER(connection->sm_role)){ 2844 // slave -> receive master keys 2845 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS; 2846 } else { 2847 if (setup->sm_use_secure_connections && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION)){ 2848 connection->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK; 2849 } else { 2850 // master -> all done 2851 connection->sm_engine_state = SM_INITIATOR_CONNECTED; 2852 sm_done_for_handle(connection->sm_handle); 2853 } 2854 } 2855 } 2856 sm_run(); 2857 } 2858 2859 #ifdef ENABLE_LE_PERIPHERAL 2860 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){ 2861 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2862 sm_aes128_state = SM_AES128_IDLE; 2863 2864 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2865 if (connection == NULL) return; 2866 2867 sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size); 2868 log_info_key("ltk", setup->sm_ltk); 2869 connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY; 2870 sm_run(); 2871 } 2872 #endif 2873 2874 static void sm_handle_encryption_result_address_resolution(void *arg){ 2875 UNUSED(arg); 2876 sm_aes128_state = SM_AES128_IDLE; 2877 2878 sm_address_resolution_ah_calculation_active = 0; 2879 // compare calulated address against connecting device 2880 uint8_t * hash = &sm_aes128_ciphertext[13]; 2881 if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){ 2882 log_info("LE Device Lookup: matched resolvable private address"); 2883 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCEEDED); 2884 sm_run(); 2885 return; 2886 } 2887 // no match, try next 2888 sm_address_resolution_test++; 2889 sm_run(); 2890 } 2891 2892 static void sm_handle_encryption_result_dkg_irk(void *arg){ 2893 UNUSED(arg); 2894 sm_aes128_state = SM_AES128_IDLE; 2895 2896 log_info_key("irk", sm_persistent_irk); 2897 dkg_state = DKG_CALC_DHK; 2898 sm_run(); 2899 } 2900 2901 static void sm_handle_encryption_result_dkg_dhk(void *arg){ 2902 UNUSED(arg); 2903 sm_aes128_state = SM_AES128_IDLE; 2904 2905 log_info_key("dhk", sm_persistent_dhk); 2906 dkg_state = DKG_READY; 2907 sm_run(); 2908 } 2909 2910 static void sm_handle_encryption_result_rau(void *arg){ 2911 UNUSED(arg); 2912 sm_aes128_state = SM_AES128_IDLE; 2913 2914 memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3); 2915 rau_state = RAU_SET_ADDRESS; 2916 sm_run(); 2917 } 2918 2919 static void sm_handle_random_result_rau(void * arg){ 2920 UNUSED(arg); 2921 // non-resolvable vs. resolvable 2922 switch (gap_random_adress_type){ 2923 case GAP_RANDOM_ADDRESS_RESOLVABLE: 2924 // resolvable: use random as prand and calc address hash 2925 // "The two most significant bits of prand shall be equal to ‘0’ and ‘1" 2926 sm_random_address[0] &= 0x3f; 2927 sm_random_address[0] |= 0x40; 2928 rau_state = RAU_GET_ENC; 2929 break; 2930 case GAP_RANDOM_ADDRESS_NON_RESOLVABLE: 2931 default: 2932 // "The two most significant bits of the address shall be equal to ‘0’"" 2933 sm_random_address[0] &= 0x3f; 2934 rau_state = RAU_SET_ADDRESS; 2935 break; 2936 } 2937 sm_run(); 2938 } 2939 2940 #ifdef ENABLE_LE_SECURE_CONNECTIONS 2941 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){ 2942 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2943 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2944 if (connection == NULL) return; 2945 2946 connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 2947 sm_run(); 2948 } 2949 2950 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){ 2951 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2952 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2953 if (connection == NULL) return; 2954 2955 connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION; 2956 sm_run(); 2957 } 2958 #endif 2959 2960 static void sm_handle_random_result_ph2_random(void * arg){ 2961 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2962 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2963 if (connection == NULL) return; 2964 2965 connection->sm_engine_state = SM_PH2_C1_GET_ENC_A; 2966 sm_run(); 2967 } 2968 2969 static void sm_handle_random_result_ph2_tk(void * arg){ 2970 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 2971 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 2972 if (connection == NULL) return; 2973 2974 sm_reset_tk(); 2975 uint32_t tk; 2976 if (sm_fixed_passkey_in_display_role == 0xffffffff){ 2977 // map random to 0-999999 without speding much cycles on a modulus operation 2978 tk = little_endian_read_32(sm_random_data,0); 2979 tk = tk & 0xfffff; // 1048575 2980 if (tk >= 999999){ 2981 tk = tk - 999999; 2982 } 2983 } else { 2984 // override with pre-defined passkey 2985 tk = sm_fixed_passkey_in_display_role; 2986 } 2987 big_endian_store_32(setup->sm_tk, 12, tk); 2988 if (IS_RESPONDER(connection->sm_role)){ 2989 connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE; 2990 } else { 2991 if (setup->sm_use_secure_connections){ 2992 connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 2993 } else { 2994 connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 2995 sm_trigger_user_response(connection); 2996 // response_idle == nothing <--> sm_trigger_user_response() did not require response 2997 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 2998 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); 2999 } 3000 } 3001 } 3002 sm_run(); 3003 } 3004 3005 static void sm_handle_random_result_ph3_div(void * arg){ 3006 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3007 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3008 if (connection == NULL) return; 3009 3010 // use 16 bit from random value as div 3011 setup->sm_local_div = big_endian_read_16(sm_random_data, 0); 3012 log_info_hex16("div", setup->sm_local_div); 3013 connection->sm_engine_state = SM_PH3_Y_GET_ENC; 3014 sm_run(); 3015 } 3016 3017 static void sm_handle_random_result_ph3_random(void * arg){ 3018 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg; 3019 sm_connection_t * connection = sm_get_connection_for_handle(con_handle); 3020 if (connection == NULL) return; 3021 3022 reverse_64(sm_random_data, setup->sm_local_rand); 3023 // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand 3024 setup->sm_local_rand[7] = (setup->sm_local_rand[7] & 0xf0) + (connection->sm_actual_encryption_key_size - 1); 3025 // no db for authenticated flag hack: store flag in bit 4 of LSB 3026 setup->sm_local_rand[7] = (setup->sm_local_rand[7] & 0xef) + (connection->sm_connection_authenticated << 4); 3027 btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle); 3028 } 3029 static void sm_validate_er_ir(void){ 3030 // warn about default ER/IR 3031 int warning = 0; 3032 if (sm_ir_is_default()){ 3033 warning = 1; 3034 log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues"); 3035 } 3036 if (sm_er_is_default()){ 3037 warning = 1; 3038 log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure"); 3039 } 3040 if (warning) { 3041 log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys"); 3042 } 3043 } 3044 3045 static void sm_handle_random_result_ir(void *arg){ 3046 sm_persistent_keys_random_active = 0; 3047 if (arg){ 3048 // key generated, store in tlv 3049 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16); 3050 log_info("Generated IR key. Store in TLV status: %d", status); 3051 } 3052 log_info_key("IR", sm_persistent_ir); 3053 dkg_state = DKG_CALC_IRK; 3054 3055 if (test_use_fixed_local_irk){ 3056 log_info_key("IRK", sm_persistent_irk); 3057 dkg_state = DKG_CALC_DHK; 3058 } 3059 3060 sm_run(); 3061 } 3062 3063 static void sm_handle_random_result_er(void *arg){ 3064 sm_persistent_keys_random_active = 0; 3065 if (arg){ 3066 // key generated, store in tlv 3067 int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16); 3068 log_info("Generated ER key. Store in TLV status: %d", status); 3069 } 3070 log_info_key("ER", sm_persistent_er); 3071 3072 // try load ir 3073 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16); 3074 if (key_size == 16){ 3075 // ok, let's continue 3076 log_info("IR from TLV"); 3077 sm_handle_random_result_ir( NULL ); 3078 } else { 3079 // invalid, generate new random one 3080 sm_persistent_keys_random_active = 1; 3081 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir); 3082 } 3083 } 3084 3085 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 3086 3087 UNUSED(channel); // ok: there is no channel 3088 UNUSED(size); // ok: fixed format HCI events 3089 3090 sm_connection_t * sm_conn; 3091 hci_con_handle_t con_handle; 3092 3093 switch (packet_type) { 3094 3095 case HCI_EVENT_PACKET: 3096 switch (hci_event_packet_get_type(packet)) { 3097 3098 case BTSTACK_EVENT_STATE: 3099 // bt stack activated, get started 3100 if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){ 3101 log_info("HCI Working!"); 3102 3103 // setup IR/ER with TLV 3104 btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context); 3105 if (sm_tlv_impl){ 3106 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16); 3107 if (key_size == 16){ 3108 // ok, let's continue 3109 log_info("ER from TLV"); 3110 sm_handle_random_result_er( NULL ); 3111 } else { 3112 // invalid, generate random one 3113 sm_persistent_keys_random_active = 1; 3114 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er); 3115 } 3116 } else { 3117 sm_validate_er_ir(); 3118 dkg_state = DKG_CALC_IRK; 3119 3120 if (test_use_fixed_local_irk){ 3121 log_info_key("IRK", sm_persistent_irk); 3122 dkg_state = DKG_CALC_DHK; 3123 } 3124 } 3125 3126 // restart random address updates after power cycle 3127 gap_random_address_set_mode(gap_random_adress_type); 3128 } 3129 break; 3130 3131 case HCI_EVENT_LE_META: 3132 switch (packet[2]) { 3133 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 3134 3135 log_info("sm: connected"); 3136 3137 if (packet[3]) return; // connection failed 3138 3139 con_handle = little_endian_read_16(packet, 4); 3140 sm_conn = sm_get_connection_for_handle(con_handle); 3141 if (!sm_conn) break; 3142 3143 sm_conn->sm_handle = con_handle; 3144 sm_conn->sm_role = packet[6]; 3145 sm_conn->sm_peer_addr_type = packet[7]; 3146 reverse_bd_addr(&packet[8], sm_conn->sm_peer_address); 3147 3148 log_info("New sm_conn, role %s", sm_conn->sm_role ? "slave" : "master"); 3149 3150 // reset security properties 3151 sm_conn->sm_connection_encrypted = 0; 3152 sm_conn->sm_connection_authenticated = 0; 3153 sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN; 3154 sm_conn->sm_le_db_index = -1; 3155 3156 // prepare CSRK lookup (does not involve setup) 3157 sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY; 3158 3159 // just connected -> everything else happens in sm_run() 3160 if (IS_RESPONDER(sm_conn->sm_role)){ 3161 // slave - state already could be SM_RESPONDER_SEND_SECURITY_REQUEST instead 3162 if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){ 3163 if (sm_slave_request_security) { 3164 // request security if requested by app 3165 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 3166 } else { 3167 // otherwise, wait for pairing request 3168 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3169 } 3170 } 3171 break; 3172 } else { 3173 // master 3174 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3175 } 3176 break; 3177 3178 case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST: 3179 con_handle = little_endian_read_16(packet, 3); 3180 sm_conn = sm_get_connection_for_handle(con_handle); 3181 if (!sm_conn) break; 3182 3183 log_info("LTK Request: state %u", sm_conn->sm_engine_state); 3184 if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){ 3185 sm_conn->sm_engine_state = SM_PH2_CALC_STK; 3186 break; 3187 } 3188 if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){ 3189 // PH2 SEND LTK as we need to exchange keys in PH3 3190 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY; 3191 break; 3192 } 3193 3194 // store rand and ediv 3195 reverse_64(&packet[5], sm_conn->sm_local_rand); 3196 sm_conn->sm_local_ediv = little_endian_read_16(packet, 13); 3197 3198 // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a 3199 // potentially stored LTK is from the master 3200 if ((sm_conn->sm_local_ediv != 0) || !sm_is_null_random(sm_conn->sm_local_rand)){ 3201 if (sm_reconstruct_ltk_without_le_device_db_entry){ 3202 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3203 break; 3204 } 3205 // additionally check if remote is in LE Device DB if requested 3206 switch(sm_conn->sm_irk_lookup_state){ 3207 case IRK_LOOKUP_FAILED: 3208 log_info("LTK Request: device not in device db"); 3209 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3210 break; 3211 case IRK_LOOKUP_SUCCEEDED: 3212 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST; 3213 break; 3214 default: 3215 // wait for irk look doen 3216 sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK; 3217 break; 3218 } 3219 break; 3220 } 3221 3222 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3223 sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST; 3224 #else 3225 log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported"); 3226 sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY; 3227 #endif 3228 break; 3229 3230 default: 3231 break; 3232 } 3233 break; 3234 3235 case HCI_EVENT_ENCRYPTION_CHANGE: 3236 con_handle = little_endian_read_16(packet, 3); 3237 sm_conn = sm_get_connection_for_handle(con_handle); 3238 if (!sm_conn) break; 3239 3240 sm_conn->sm_connection_encrypted = packet[5]; 3241 log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted, 3242 sm_conn->sm_actual_encryption_key_size); 3243 log_info("event handler, state %u", sm_conn->sm_engine_state); 3244 3245 // encryption change event concludes re-encryption for bonded devices (even if it fails) 3246 if (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED){ 3247 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3248 // notify client, if pairing was requested before 3249 if (sm_conn->sm_pairing_requested){ 3250 sm_conn->sm_pairing_requested = 0; 3251 if (sm_conn->sm_connection_encrypted){ 3252 sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0); 3253 } else { 3254 sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, 0); 3255 } 3256 } 3257 sm_done_for_handle(sm_conn->sm_handle); 3258 break; 3259 } 3260 3261 if (!sm_conn->sm_connection_encrypted) break; 3262 sm_conn->sm_connection_sc = setup->sm_use_secure_connections; 3263 3264 // continue pairing 3265 switch (sm_conn->sm_engine_state){ 3266 case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED: 3267 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3268 sm_done_for_handle(sm_conn->sm_handle); 3269 break; 3270 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3271 if (IS_RESPONDER(sm_conn->sm_role)){ 3272 // slave 3273 if (setup->sm_use_secure_connections){ 3274 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3275 } else { 3276 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); 3277 } 3278 } else { 3279 // master 3280 if (sm_key_distribution_all_received(sm_conn)){ 3281 // skip receiving keys as there are none 3282 sm_key_distribution_handle_all_received(sm_conn); 3283 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); 3284 } else { 3285 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3286 } 3287 } 3288 break; 3289 default: 3290 break; 3291 } 3292 break; 3293 3294 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE: 3295 con_handle = little_endian_read_16(packet, 3); 3296 sm_conn = sm_get_connection_for_handle(con_handle); 3297 if (!sm_conn) break; 3298 3299 log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size); 3300 log_info("event handler, state %u", sm_conn->sm_engine_state); 3301 // continue if part of initial pairing 3302 switch (sm_conn->sm_engine_state){ 3303 case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED: 3304 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED; 3305 sm_done_for_handle(sm_conn->sm_handle); 3306 break; 3307 case SM_PH2_W4_CONNECTION_ENCRYPTED: 3308 if (IS_RESPONDER(sm_conn->sm_role)){ 3309 // slave 3310 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); 3311 } else { 3312 // master 3313 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS; 3314 } 3315 break; 3316 default: 3317 break; 3318 } 3319 break; 3320 3321 3322 case HCI_EVENT_DISCONNECTION_COMPLETE: 3323 con_handle = little_endian_read_16(packet, 3); 3324 sm_done_for_handle(con_handle); 3325 sm_conn = sm_get_connection_for_handle(con_handle); 3326 if (!sm_conn) break; 3327 3328 // delete stored bonding on disconnect with authentication failure in ph0 3329 if ((sm_conn->sm_role == 0) 3330 && (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED) 3331 && (packet[2] == ERROR_CODE_AUTHENTICATION_FAILURE)){ 3332 le_device_db_remove(sm_conn->sm_le_db_index); 3333 } 3334 3335 // pairing failed, if it was ongoing 3336 switch (sm_conn->sm_engine_state){ 3337 case SM_GENERAL_IDLE: 3338 case SM_INITIATOR_CONNECTED: 3339 case SM_RESPONDER_IDLE: 3340 break; 3341 default: 3342 sm_notify_client_status_reason(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0); 3343 break; 3344 } 3345 3346 sm_conn->sm_engine_state = SM_GENERAL_IDLE; 3347 sm_conn->sm_handle = 0; 3348 break; 3349 3350 case HCI_EVENT_COMMAND_COMPLETE: 3351 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){ 3352 // set local addr for le device db 3353 bd_addr_t addr; 3354 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr); 3355 le_device_db_set_local_bd_addr(addr); 3356 } 3357 break; 3358 default: 3359 break; 3360 } 3361 break; 3362 default: 3363 break; 3364 } 3365 3366 sm_run(); 3367 } 3368 3369 static inline int sm_calc_actual_encryption_key_size(int other){ 3370 if (other < sm_min_encryption_key_size) return 0; 3371 if (other < sm_max_encryption_key_size) return other; 3372 return sm_max_encryption_key_size; 3373 } 3374 3375 3376 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3377 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){ 3378 switch (method){ 3379 case JUST_WORKS: 3380 case NUMERIC_COMPARISON: 3381 return 1; 3382 default: 3383 return 0; 3384 } 3385 } 3386 // responder 3387 3388 static int sm_passkey_used(stk_generation_method_t method){ 3389 switch (method){ 3390 case PK_RESP_INPUT: 3391 return 1; 3392 default: 3393 return 0; 3394 } 3395 } 3396 3397 static int sm_passkey_entry(stk_generation_method_t method){ 3398 switch (method){ 3399 case PK_RESP_INPUT: 3400 case PK_INIT_INPUT: 3401 case PK_BOTH_INPUT: 3402 return 1; 3403 default: 3404 return 0; 3405 } 3406 } 3407 3408 #endif 3409 3410 /** 3411 * @return ok 3412 */ 3413 static int sm_validate_stk_generation_method(void){ 3414 // check if STK generation method is acceptable by client 3415 switch (setup->sm_stk_generation_method){ 3416 case JUST_WORKS: 3417 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0; 3418 case PK_RESP_INPUT: 3419 case PK_INIT_INPUT: 3420 case PK_BOTH_INPUT: 3421 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0; 3422 case OOB: 3423 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0; 3424 case NUMERIC_COMPARISON: 3425 return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0; 3426 default: 3427 return 0; 3428 } 3429 } 3430 3431 // size of complete sm_pdu used to validate input 3432 static const uint8_t sm_pdu_size[] = { 3433 0, // 0x00 invalid opcode 3434 7, // 0x01 pairing request 3435 7, // 0x02 pairing response 3436 17, // 0x03 pairing confirm 3437 17, // 0x04 pairing random 3438 2, // 0x05 pairing failed 3439 17, // 0x06 encryption information 3440 11, // 0x07 master identification 3441 17, // 0x08 identification information 3442 8, // 0x09 identify address information 3443 17, // 0x0a signing information 3444 2, // 0x0b security request 3445 65, // 0x0c pairing public key 3446 17, // 0x0d pairing dhk check 3447 2, // 0x0e keypress notification 3448 }; 3449 3450 static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){ 3451 3452 if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){ 3453 sm_run(); 3454 } 3455 3456 if (packet_type != SM_DATA_PACKET) return; 3457 if (size == 0) return; 3458 3459 uint8_t sm_pdu_code = packet[0]; 3460 3461 // validate pdu size 3462 if (sm_pdu_code >= sizeof(sm_pdu_size)) return; 3463 if (sm_pdu_size[sm_pdu_code] != size) return; 3464 3465 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 3466 if (!sm_conn) return; 3467 3468 if (sm_pdu_code == SM_CODE_PAIRING_FAILED){ 3469 sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]); 3470 sm_done_for_handle(con_handle); 3471 sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED; 3472 return; 3473 } 3474 3475 log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code); 3476 3477 int err; 3478 UNUSED(err); 3479 3480 if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){ 3481 uint8_t buffer[5]; 3482 buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION; 3483 buffer[1] = 3; 3484 little_endian_store_16(buffer, 2, con_handle); 3485 buffer[4] = packet[1]; 3486 sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer)); 3487 return; 3488 } 3489 3490 switch (sm_conn->sm_engine_state){ 3491 3492 // a sm timeout requries a new physical connection 3493 case SM_GENERAL_TIMEOUT: 3494 return; 3495 3496 #ifdef ENABLE_LE_CENTRAL 3497 3498 // Initiator 3499 case SM_INITIATOR_CONNECTED: 3500 if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){ 3501 sm_pdu_received_in_wrong_state(sm_conn); 3502 break; 3503 } 3504 3505 // IRK complete? 3506 int have_ltk; 3507 uint8_t ltk[16]; 3508 switch (sm_conn->sm_irk_lookup_state){ 3509 case IRK_LOOKUP_FAILED: 3510 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 3511 break; 3512 case IRK_LOOKUP_SUCCEEDED: 3513 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 3514 have_ltk = !sm_is_null_key(ltk); 3515 log_info("central: security request - have_ltk %u", have_ltk); 3516 if (have_ltk){ 3517 sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK; 3518 } else { 3519 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 3520 } 3521 break; 3522 default: 3523 break; 3524 } 3525 3526 // otherwise, store security request 3527 sm_conn->sm_security_request_received = 1; 3528 break; 3529 3530 case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE: 3531 // Core 5, Vol 3, Part H, 2.4.6: 3532 // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request 3533 // without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup." 3534 if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){ 3535 log_info("Ignoring Security Request"); 3536 break; 3537 } 3538 3539 // all other pdus are incorrect 3540 if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){ 3541 sm_pdu_received_in_wrong_state(sm_conn); 3542 break; 3543 } 3544 3545 // store pairing request 3546 memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t)); 3547 err = sm_stk_generation_init(sm_conn); 3548 3549 #ifdef ENABLE_TESTING_SUPPORT 3550 if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){ 3551 log_info("testing_support: abort with pairing failure %u", test_pairing_failure); 3552 err = test_pairing_failure; 3553 } 3554 #endif 3555 3556 if (err){ 3557 setup->sm_pairing_failed_reason = err; 3558 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 3559 break; 3560 } 3561 3562 // generate random number first, if we need to show passkey 3563 if (setup->sm_stk_generation_method == PK_RESP_INPUT){ 3564 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); 3565 break; 3566 } 3567 3568 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3569 if (setup->sm_use_secure_connections){ 3570 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged 3571 if (setup->sm_stk_generation_method == JUST_WORKS){ 3572 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 3573 sm_trigger_user_response(sm_conn); 3574 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 3575 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 3576 } 3577 } else { 3578 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 3579 } 3580 break; 3581 } 3582 #endif 3583 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 3584 sm_trigger_user_response(sm_conn); 3585 // response_idle == nothing <--> sm_trigger_user_response() did not require response 3586 if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){ 3587 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); 3588 } 3589 break; 3590 3591 case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM: 3592 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 3593 sm_pdu_received_in_wrong_state(sm_conn); 3594 break; 3595 } 3596 3597 // store s_confirm 3598 reverse_128(&packet[1], setup->sm_peer_confirm); 3599 3600 #ifdef ENABLE_TESTING_SUPPORT 3601 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 3602 log_info("testing_support: reset confirm value"); 3603 memset(setup->sm_peer_confirm, 0, 16); 3604 } 3605 #endif 3606 sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM; 3607 break; 3608 3609 case SM_INITIATOR_PH2_W4_PAIRING_RANDOM: 3610 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 3611 sm_pdu_received_in_wrong_state(sm_conn); 3612 break;; 3613 } 3614 3615 // received random value 3616 reverse_128(&packet[1], setup->sm_peer_random); 3617 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 3618 break; 3619 #endif 3620 3621 #ifdef ENABLE_LE_PERIPHERAL 3622 // Responder 3623 case SM_RESPONDER_IDLE: 3624 case SM_RESPONDER_SEND_SECURITY_REQUEST: 3625 case SM_RESPONDER_PH1_W4_PAIRING_REQUEST: 3626 if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){ 3627 sm_pdu_received_in_wrong_state(sm_conn); 3628 break;; 3629 } 3630 3631 // store pairing request 3632 memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t)); 3633 sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED; 3634 break; 3635 #endif 3636 3637 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3638 case SM_SC_W4_PUBLIC_KEY_COMMAND: 3639 if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){ 3640 sm_pdu_received_in_wrong_state(sm_conn); 3641 break; 3642 } 3643 3644 // store public key for DH Key calculation 3645 reverse_256(&packet[01], &setup->sm_peer_q[0]); 3646 reverse_256(&packet[33], &setup->sm_peer_q[32]); 3647 3648 // validate public key 3649 err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q); 3650 if (err){ 3651 log_error("sm: peer public key invalid %x", err); 3652 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED); 3653 break; 3654 } 3655 3656 // start calculating dhkey 3657 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); 3658 3659 3660 log_info("public key received, generation method %u", setup->sm_stk_generation_method); 3661 if (IS_RESPONDER(sm_conn->sm_role)){ 3662 // responder 3663 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 3664 } else { 3665 // initiator 3666 // stk generation method 3667 // passkey entry: notify app to show passkey or to request passkey 3668 switch (setup->sm_stk_generation_method){ 3669 case JUST_WORKS: 3670 case NUMERIC_COMPARISON: 3671 sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION; 3672 break; 3673 case PK_RESP_INPUT: 3674 sm_sc_start_calculating_local_confirm(sm_conn); 3675 break; 3676 case PK_INIT_INPUT: 3677 case PK_BOTH_INPUT: 3678 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 3679 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 3680 break; 3681 } 3682 sm_sc_start_calculating_local_confirm(sm_conn); 3683 break; 3684 case OOB: 3685 // generate Nx 3686 log_info("Generate Na"); 3687 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); 3688 break; 3689 } 3690 } 3691 break; 3692 3693 case SM_SC_W4_CONFIRMATION: 3694 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 3695 sm_pdu_received_in_wrong_state(sm_conn); 3696 break; 3697 } 3698 // received confirm value 3699 reverse_128(&packet[1], setup->sm_peer_confirm); 3700 3701 #ifdef ENABLE_TESTING_SUPPORT 3702 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 3703 log_info("testing_support: reset confirm value"); 3704 memset(setup->sm_peer_confirm, 0, 16); 3705 } 3706 #endif 3707 if (IS_RESPONDER(sm_conn->sm_role)){ 3708 // responder 3709 if (sm_passkey_used(setup->sm_stk_generation_method)){ 3710 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){ 3711 // still waiting for passkey 3712 sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE; 3713 break; 3714 } 3715 } 3716 sm_sc_start_calculating_local_confirm(sm_conn); 3717 } else { 3718 // initiator 3719 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){ 3720 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); 3721 } else { 3722 sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM; 3723 } 3724 } 3725 break; 3726 3727 case SM_SC_W4_PAIRING_RANDOM: 3728 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 3729 sm_pdu_received_in_wrong_state(sm_conn); 3730 break; 3731 } 3732 3733 // received random value 3734 reverse_128(&packet[1], setup->sm_peer_nonce); 3735 3736 // validate confirm value if Cb = f4(Pkb, Pka, Nb, z) 3737 // only check for JUST WORK/NC in initiator role OR passkey entry 3738 if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)) 3739 || (sm_passkey_used(setup->sm_stk_generation_method)) ) { 3740 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 3741 break; 3742 } 3743 3744 // OOB 3745 if (setup->sm_stk_generation_method == OOB){ 3746 3747 // setup local random, set to zero if remote did not receive our data 3748 log_info("Received nonce, setup local random ra/rb for dhkey check"); 3749 if (IS_RESPONDER(sm_conn->sm_role)){ 3750 if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0){ 3751 log_info("Reset rb as A does not have OOB data"); 3752 memset(setup->sm_rb, 0, 16); 3753 } else { 3754 memcpy(setup->sm_rb, sm_sc_oob_random, 16); 3755 log_info("Use stored rb"); 3756 log_info_hexdump(setup->sm_rb, 16); 3757 } 3758 } else { 3759 if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0){ 3760 log_info("Reset ra as B does not have OOB data"); 3761 memset(setup->sm_ra, 0, 16); 3762 } else { 3763 memcpy(setup->sm_ra, sm_sc_oob_random, 16); 3764 log_info("Use stored ra"); 3765 log_info_hexdump(setup->sm_ra, 16); 3766 } 3767 } 3768 3769 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received 3770 if (setup->sm_have_oob_data){ 3771 sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION; 3772 break; 3773 } 3774 } 3775 3776 // TODO: we only get here for Responder role with JW/NC 3777 sm_sc_state_after_receiving_random(sm_conn); 3778 break; 3779 3780 case SM_SC_W2_CALCULATE_G2: 3781 case SM_SC_W4_CALCULATE_G2: 3782 case SM_SC_W4_CALCULATE_DHKEY: 3783 case SM_SC_W2_CALCULATE_F5_SALT: 3784 case SM_SC_W4_CALCULATE_F5_SALT: 3785 case SM_SC_W2_CALCULATE_F5_MACKEY: 3786 case SM_SC_W4_CALCULATE_F5_MACKEY: 3787 case SM_SC_W2_CALCULATE_F5_LTK: 3788 case SM_SC_W4_CALCULATE_F5_LTK: 3789 case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK: 3790 case SM_SC_W4_DHKEY_CHECK_COMMAND: 3791 case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK: 3792 if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){ 3793 sm_pdu_received_in_wrong_state(sm_conn); 3794 break; 3795 } 3796 // store DHKey Check 3797 setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED; 3798 reverse_128(&packet[01], setup->sm_peer_dhkey_check); 3799 3800 // have we been only waiting for dhkey check command? 3801 if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){ 3802 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK; 3803 } 3804 break; 3805 #endif 3806 3807 #ifdef ENABLE_LE_PERIPHERAL 3808 case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM: 3809 if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){ 3810 sm_pdu_received_in_wrong_state(sm_conn); 3811 break; 3812 } 3813 3814 // received confirm value 3815 reverse_128(&packet[1], setup->sm_peer_confirm); 3816 3817 #ifdef ENABLE_TESTING_SUPPORT 3818 if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){ 3819 log_info("testing_support: reset confirm value"); 3820 memset(setup->sm_peer_confirm, 0, 16); 3821 } 3822 #endif 3823 // notify client to hide shown passkey 3824 if (setup->sm_stk_generation_method == PK_INIT_INPUT){ 3825 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address); 3826 } 3827 3828 // handle user cancel pairing? 3829 if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){ 3830 setup->sm_pairing_failed_reason = SM_REASON_PASSKEY_ENTRY_FAILED; 3831 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED; 3832 break; 3833 } 3834 3835 // wait for user action? 3836 if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){ 3837 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE; 3838 break; 3839 } 3840 3841 // calculate and send local_confirm 3842 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); 3843 break; 3844 3845 case SM_RESPONDER_PH2_W4_PAIRING_RANDOM: 3846 if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){ 3847 sm_pdu_received_in_wrong_state(sm_conn); 3848 break;; 3849 } 3850 3851 // received random value 3852 reverse_128(&packet[1], setup->sm_peer_random); 3853 sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C; 3854 break; 3855 #endif 3856 3857 case SM_PH3_RECEIVE_KEYS: 3858 switch(sm_pdu_code){ 3859 case SM_CODE_ENCRYPTION_INFORMATION: 3860 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION; 3861 reverse_128(&packet[1], setup->sm_peer_ltk); 3862 break; 3863 3864 case SM_CODE_MASTER_IDENTIFICATION: 3865 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION; 3866 setup->sm_peer_ediv = little_endian_read_16(packet, 1); 3867 reverse_64(&packet[3], setup->sm_peer_rand); 3868 break; 3869 3870 case SM_CODE_IDENTITY_INFORMATION: 3871 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION; 3872 reverse_128(&packet[1], setup->sm_peer_irk); 3873 break; 3874 3875 case SM_CODE_IDENTITY_ADDRESS_INFORMATION: 3876 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION; 3877 setup->sm_peer_addr_type = packet[1]; 3878 reverse_bd_addr(&packet[2], setup->sm_peer_address); 3879 break; 3880 3881 case SM_CODE_SIGNING_INFORMATION: 3882 setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION; 3883 reverse_128(&packet[1], setup->sm_peer_csrk); 3884 break; 3885 default: 3886 // Unexpected PDU 3887 log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]); 3888 break; 3889 } 3890 // done with key distribution? 3891 if (sm_key_distribution_all_received(sm_conn)){ 3892 3893 sm_key_distribution_handle_all_received(sm_conn); 3894 3895 if (IS_RESPONDER(sm_conn->sm_role)){ 3896 if (setup->sm_use_secure_connections && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION)){ 3897 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK; 3898 } else { 3899 sm_conn->sm_engine_state = SM_RESPONDER_IDLE; 3900 sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0); 3901 sm_done_for_handle(sm_conn->sm_handle); 3902 } 3903 } else { 3904 if (setup->sm_use_secure_connections){ 3905 sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS; 3906 } else { 3907 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); 3908 } 3909 } 3910 } 3911 break; 3912 default: 3913 // Unexpected PDU 3914 log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state); 3915 break; 3916 } 3917 3918 // try to send preparared packet 3919 sm_run(); 3920 } 3921 3922 // Security Manager Client API 3923 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){ 3924 sm_get_oob_data = get_oob_data_callback; 3925 } 3926 3927 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)){ 3928 sm_get_sc_oob_data = get_sc_oob_data_callback; 3929 } 3930 3931 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 3932 btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler); 3933 } 3934 3935 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){ 3936 sm_accepted_stk_generation_methods = accepted_stk_generation_methods; 3937 } 3938 3939 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){ 3940 sm_min_encryption_key_size = min_size; 3941 sm_max_encryption_key_size = max_size; 3942 } 3943 3944 void sm_set_authentication_requirements(uint8_t auth_req){ 3945 #ifndef ENABLE_LE_SECURE_CONNECTIONS 3946 if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){ 3947 log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag"); 3948 auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION; 3949 } 3950 #endif 3951 sm_auth_req = auth_req; 3952 } 3953 3954 void sm_set_io_capabilities(io_capability_t io_capability){ 3955 sm_io_capabilities = io_capability; 3956 } 3957 3958 #ifdef ENABLE_LE_PERIPHERAL 3959 void sm_set_request_security(int enable){ 3960 sm_slave_request_security = enable; 3961 } 3962 #endif 3963 3964 void sm_set_er(sm_key_t er){ 3965 memcpy(sm_persistent_er, er, 16); 3966 } 3967 3968 void sm_set_ir(sm_key_t ir){ 3969 memcpy(sm_persistent_ir, ir, 16); 3970 } 3971 3972 // Testing support only 3973 void sm_test_set_irk(sm_key_t irk){ 3974 memcpy(sm_persistent_irk, irk, 16); 3975 dkg_state = DKG_CALC_DHK; 3976 test_use_fixed_local_irk = true; 3977 } 3978 3979 void sm_test_use_fixed_local_csrk(void){ 3980 test_use_fixed_local_csrk = true; 3981 } 3982 3983 #ifdef ENABLE_LE_SECURE_CONNECTIONS 3984 static void sm_ec_generated(void * arg){ 3985 UNUSED(arg); 3986 ec_key_generation_state = EC_KEY_GENERATION_DONE; 3987 // trigger pairing if pending for ec key 3988 sm_run(); 3989 } 3990 static void sm_ec_generate_new_key(void){ 3991 log_info("sm: generate new ec key"); 3992 ec_key_generation_state = EC_KEY_GENERATION_ACTIVE; 3993 btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL); 3994 } 3995 #endif 3996 3997 #ifdef ENABLE_TESTING_SUPPORT 3998 void sm_test_set_pairing_failure(int reason){ 3999 test_pairing_failure = reason; 4000 } 4001 #endif 4002 4003 void sm_init(void){ 4004 // set default ER and IR values (should be unique - set by app or sm later using TLV) 4005 sm_er_ir_set_default(); 4006 4007 // defaults 4008 sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS 4009 | SM_STK_GENERATION_METHOD_OOB 4010 | SM_STK_GENERATION_METHOD_PASSKEY 4011 | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON; 4012 4013 sm_max_encryption_key_size = 16; 4014 sm_min_encryption_key_size = 7; 4015 4016 sm_fixed_passkey_in_display_role = 0xffffffff; 4017 sm_reconstruct_ltk_without_le_device_db_entry = 1; 4018 4019 #ifdef USE_CMAC_ENGINE 4020 sm_cmac_active = 0; 4021 #endif 4022 dkg_state = DKG_W4_WORKING; 4023 rau_state = RAU_IDLE; 4024 sm_aes128_state = SM_AES128_IDLE; 4025 sm_address_resolution_test = -1; // no private address to resolve yet 4026 sm_address_resolution_ah_calculation_active = 0; 4027 sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE; 4028 sm_address_resolution_general_queue = NULL; 4029 4030 gap_random_adress_update_period = 15 * 60 * 1000L; 4031 sm_active_connection_handle = HCI_CON_HANDLE_INVALID; 4032 4033 test_use_fixed_local_csrk = false; 4034 4035 // register for HCI Events from HCI 4036 hci_event_callback_registration.callback = &sm_event_packet_handler; 4037 hci_add_event_handler(&hci_event_callback_registration); 4038 4039 // 4040 btstack_crypto_init(); 4041 4042 // init le_device_db 4043 le_device_db_init(); 4044 4045 // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW 4046 l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 4047 4048 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4049 sm_ec_generate_new_key(); 4050 #endif 4051 } 4052 4053 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){ 4054 sm_fixed_passkey_in_display_role = passkey; 4055 } 4056 4057 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){ 4058 sm_reconstruct_ltk_without_le_device_db_entry = allow; 4059 } 4060 4061 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 4062 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 4063 if (!hci_con) return NULL; 4064 return &hci_con->sm_connection; 4065 } 4066 4067 static void sm_send_security_request_for_connection(sm_connection_t * sm_conn){ 4068 switch (sm_conn->sm_engine_state){ 4069 case SM_GENERAL_IDLE: 4070 case SM_RESPONDER_IDLE: 4071 sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST; 4072 sm_run(); 4073 break; 4074 default: 4075 break; 4076 } 4077 } 4078 4079 /** 4080 * @brief Trigger Security Request 4081 */ 4082 void sm_send_security_request(hci_con_handle_t con_handle){ 4083 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4084 if (!sm_conn) return; 4085 sm_send_security_request_for_connection(sm_conn); 4086 } 4087 4088 // request pairing 4089 void sm_request_pairing(hci_con_handle_t con_handle){ 4090 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4091 if (!sm_conn) return; // wrong connection 4092 4093 log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state); 4094 if (IS_RESPONDER(sm_conn->sm_role)){ 4095 sm_send_security_request_for_connection(sm_conn); 4096 } else { 4097 // used as a trigger to start central/master/initiator security procedures 4098 if (sm_conn->sm_engine_state == SM_INITIATOR_CONNECTED){ 4099 uint8_t ltk[16]; 4100 switch (sm_conn->sm_irk_lookup_state){ 4101 case IRK_LOOKUP_SUCCEEDED: 4102 #ifndef ENABLE_LE_CENTRAL_AUTO_ENCRYPTION 4103 le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL); 4104 log_info("have ltk %u", !sm_is_null_key(ltk)); 4105 // trigger 'pairing complete' event on encryption change 4106 sm_conn->sm_pairing_requested = 1; 4107 sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK; 4108 break; 4109 #endif 4110 /* explicit fall-through */ 4111 4112 case IRK_LOOKUP_FAILED: 4113 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST; 4114 break; 4115 default: 4116 log_info("irk lookup pending"); 4117 sm_conn->sm_pairing_requested = 1; 4118 break; 4119 } 4120 } else if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){ 4121 sm_conn->sm_pairing_requested = 1; 4122 } 4123 } 4124 sm_run(); 4125 } 4126 4127 // called by client app on authorization request 4128 void sm_authorization_decline(hci_con_handle_t con_handle){ 4129 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4130 if (!sm_conn) return; // wrong connection 4131 sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED; 4132 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0); 4133 } 4134 4135 void sm_authorization_grant(hci_con_handle_t con_handle){ 4136 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4137 if (!sm_conn) return; // wrong connection 4138 sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED; 4139 sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1); 4140 } 4141 4142 // GAP Bonding API 4143 4144 void sm_bonding_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 setup->sm_user_response = SM_USER_RESPONSE_DECLINE; 4148 log_info("decline, state %u", sm_conn->sm_engine_state); 4149 switch(sm_conn->sm_engine_state){ 4150 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4151 case SM_SC_W4_USER_RESPONSE: 4152 case SM_SC_W4_CONFIRMATION: 4153 case SM_SC_W4_PUBLIC_KEY_COMMAND: 4154 #endif 4155 case SM_PH1_W4_USER_RESPONSE: 4156 switch (setup->sm_stk_generation_method){ 4157 case PK_RESP_INPUT: 4158 case PK_INIT_INPUT: 4159 case PK_BOTH_INPUT: 4160 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED); 4161 break; 4162 case NUMERIC_COMPARISON: 4163 sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED); 4164 break; 4165 case JUST_WORKS: 4166 case OOB: 4167 sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON); 4168 break; 4169 } 4170 break; 4171 default: 4172 break; 4173 } 4174 sm_run(); 4175 } 4176 4177 void sm_just_works_confirm(hci_con_handle_t con_handle){ 4178 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4179 if (!sm_conn) return; // wrong connection 4180 setup->sm_user_response = SM_USER_RESPONSE_CONFIRM; 4181 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 4182 if (setup->sm_use_secure_connections){ 4183 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND; 4184 } else { 4185 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); 4186 } 4187 } 4188 4189 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4190 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 4191 sm_sc_prepare_dhkey_check(sm_conn); 4192 } 4193 #endif 4194 4195 sm_run(); 4196 } 4197 4198 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){ 4199 // for now, it's the same 4200 sm_just_works_confirm(con_handle); 4201 } 4202 4203 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){ 4204 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4205 if (!sm_conn) return; // wrong connection 4206 sm_reset_tk(); 4207 big_endian_store_32(setup->sm_tk, 12, passkey); 4208 setup->sm_user_response = SM_USER_RESPONSE_PASSKEY; 4209 if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){ 4210 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); 4211 } 4212 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4213 memcpy(setup->sm_ra, setup->sm_tk, 16); 4214 memcpy(setup->sm_rb, setup->sm_tk, 16); 4215 if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){ 4216 sm_sc_start_calculating_local_confirm(sm_conn); 4217 } 4218 #endif 4219 sm_run(); 4220 } 4221 4222 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){ 4223 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4224 if (!sm_conn) return; // wrong connection 4225 if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return; 4226 uint8_t num_actions = setup->sm_keypress_notification >> 5; 4227 uint8_t flags = setup->sm_keypress_notification & 0x1f; 4228 switch (action){ 4229 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED: 4230 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED: 4231 flags |= (1 << action); 4232 break; 4233 case SM_KEYPRESS_PASSKEY_CLEARED: 4234 // clear counter, keypress & erased flags + set passkey cleared 4235 flags = (flags & 0x19) | (1 << SM_KEYPRESS_PASSKEY_CLEARED); 4236 break; 4237 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED: 4238 if (flags & (1 << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){ 4239 // erase actions queued 4240 num_actions--; 4241 if (num_actions == 0){ 4242 // clear counter, keypress & erased flags 4243 flags &= 0x19; 4244 } 4245 break; 4246 } 4247 num_actions++; 4248 flags |= (1 << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED); 4249 break; 4250 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED: 4251 if (flags & (1 << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){ 4252 // enter actions queued 4253 num_actions--; 4254 if (num_actions == 0){ 4255 // clear counter, keypress & erased flags 4256 flags &= 0x19; 4257 } 4258 break; 4259 } 4260 num_actions++; 4261 flags |= (1 << SM_KEYPRESS_PASSKEY_DIGIT_ERASED); 4262 break; 4263 default: 4264 break; 4265 } 4266 setup->sm_keypress_notification = (num_actions << 5) | flags; 4267 sm_run(); 4268 } 4269 4270 #ifdef ENABLE_LE_SECURE_CONNECTIONS 4271 static void sm_handle_random_result_oob(void * arg){ 4272 UNUSED(arg); 4273 sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM; 4274 sm_run(); 4275 } 4276 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){ 4277 if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 4278 sm_sc_oob_callback = callback; 4279 sm_sc_oob_state = SM_SC_OOB_W4_RANDOM; 4280 btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL); 4281 return 0; 4282 } 4283 #endif 4284 4285 /** 4286 * @brief Get Identity Resolving state 4287 * @param con_handle 4288 * @return irk_lookup_state_t 4289 */ 4290 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){ 4291 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4292 if (!sm_conn) return IRK_LOOKUP_IDLE; 4293 return sm_conn->sm_irk_lookup_state; 4294 } 4295 4296 /** 4297 * @brief Identify device in LE Device DB 4298 * @param handle 4299 * @returns index from le_device_db or -1 if not found/identified 4300 */ 4301 int sm_le_device_index(hci_con_handle_t con_handle ){ 4302 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4303 if (!sm_conn) return -1; 4304 return sm_conn->sm_le_db_index; 4305 } 4306 4307 static int gap_random_address_type_requires_updates(void){ 4308 switch (gap_random_adress_type){ 4309 case GAP_RANDOM_ADDRESS_TYPE_OFF: 4310 case GAP_RANDOM_ADDRESS_TYPE_STATIC: 4311 return 0; 4312 default: 4313 return 1; 4314 } 4315 } 4316 4317 static uint8_t own_address_type(void){ 4318 switch (gap_random_adress_type){ 4319 case GAP_RANDOM_ADDRESS_TYPE_OFF: 4320 return BD_ADDR_TYPE_LE_PUBLIC; 4321 default: 4322 return BD_ADDR_TYPE_LE_RANDOM; 4323 } 4324 } 4325 4326 // GAP LE API 4327 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){ 4328 gap_random_address_update_stop(); 4329 gap_random_adress_type = random_address_type; 4330 hci_le_set_own_address_type(own_address_type()); 4331 if (!gap_random_address_type_requires_updates()) return; 4332 gap_random_address_update_start(); 4333 gap_random_address_trigger(); 4334 } 4335 4336 gap_random_address_type_t gap_random_address_get_mode(void){ 4337 return gap_random_adress_type; 4338 } 4339 4340 void gap_random_address_set_update_period(int period_ms){ 4341 gap_random_adress_update_period = period_ms; 4342 if (!gap_random_address_type_requires_updates()) return; 4343 gap_random_address_update_stop(); 4344 gap_random_address_update_start(); 4345 } 4346 4347 void gap_random_address_set(bd_addr_t addr){ 4348 gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC); 4349 memcpy(sm_random_address, addr, 6); 4350 rau_state = RAU_SET_ADDRESS; 4351 sm_run(); 4352 } 4353 4354 #ifdef ENABLE_LE_PERIPHERAL 4355 /* 4356 * @brief Set Advertisement Paramters 4357 * @param adv_int_min 4358 * @param adv_int_max 4359 * @param adv_type 4360 * @param direct_address_type 4361 * @param direct_address 4362 * @param channel_map 4363 * @param filter_policy 4364 * 4365 * @note own_address_type is used from gap_random_address_set_mode 4366 */ 4367 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 4368 uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){ 4369 hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 4370 direct_address_typ, direct_address, channel_map, filter_policy); 4371 } 4372 #endif 4373 4374 int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){ 4375 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 4376 // wrong connection 4377 if (!sm_conn) return 0; 4378 // already encrypted 4379 if (sm_conn->sm_connection_encrypted) return 0; 4380 // only central can re-encrypt 4381 if (sm_conn->sm_role == HCI_ROLE_SLAVE) return 0; 4382 // irk status? 4383 switch(sm_conn->sm_irk_lookup_state){ 4384 case IRK_LOOKUP_FAILED: 4385 // done, cannot setup encryption 4386 return 0; 4387 case IRK_LOOKUP_SUCCEEDED: 4388 break; 4389 default: 4390 // IR Lookup pending 4391 return 1; 4392 } 4393 // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset 4394 return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED; 4395 } 4396