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