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