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