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