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