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