xref: /btstack/src/ble/sm.c (revision 5d4d8cc7b1d35a90bbd6d5ffd2d3050b2bfc861c)
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 bool sm_run_ready(void) {
2810     // assert that stack has already booted
2811     if (hci_get_state() != HCI_STATE_WORKING) return false;
2812 
2813     // assert that we can send at least commands
2814     if (!hci_can_send_command_packet_now()) return false;
2815 
2816     // pause until IR/ER are ready
2817     if (sm_persistent_keys_random_active) return false;
2818 
2819     return true;
2820 }
2821 
2822 static void sm_run(void){
2823 
2824     // ready
2825     if (sm_run_ready() == false) return;
2826 
2827     // non-connection related behaviour
2828     bool done = sm_run_non_connection_logic();
2829     if (done) return;
2830 
2831     // assert that we can send at least commands - cmd might have been sent by crypto engine
2832     if (!hci_can_send_command_packet_now()) return;
2833 
2834     // handle basic actions that don't requires the full context
2835     done = sm_run_basic();
2836     if (done) return;
2837 
2838     //
2839     // active connection handling
2840     // -- use loop to handle next connection if lock on setup context is released
2841 
2842     while (true) {
2843 
2844         sm_run_activate_connection();
2845 
2846         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
2847 
2848         //
2849         // active connection handling
2850         //
2851 
2852         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
2853         if (!connection) {
2854             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
2855             return;
2856         }
2857 
2858         // assert that we could send a SM PDU - not needed for all of the following
2859         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) {
2860             log_info("cannot send now, requesting can send now event");
2861             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2862             return;
2863         }
2864 
2865         // send keypress notifications
2866         if (setup->sm_keypress_notification != 0u){
2867             sm_run_send_keypress_notification(connection);
2868             return;
2869         }
2870 
2871 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2872         // assert that sm cmac engine is ready
2873         if (sm_cmac_ready() == false){
2874             break;
2875         }
2876 #endif
2877 
2878         // initialize to avoid 'maybe used uninitialized' error
2879         int key_distribution_flags = 0;
2880         UNUSED(key_distribution_flags);
2881 #ifdef ENABLE_LE_PERIPHERAL
2882         int err;
2883         bool have_ltk;
2884         uint8_t ltk[16];
2885 #endif
2886 
2887         log_info("sm_run: state %u", connection->sm_engine_state);
2888         switch (connection->sm_engine_state){
2889 
2890             // secure connections, initiator + responding states
2891 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2892             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2893                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2894                 sm_sc_calculate_local_confirm(connection);
2895                 break;
2896             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2897                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2898                 sm_sc_calculate_remote_confirm(connection);
2899                 break;
2900             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2901                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2902                 sm_sc_calculate_f6_for_dhkey_check(connection);
2903                 break;
2904             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2905                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
2906                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
2907                 break;
2908             case SM_SC_W2_CALCULATE_F5_SALT:
2909                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
2910                 f5_calculate_salt(connection);
2911                 break;
2912             case SM_SC_W2_CALCULATE_F5_MACKEY:
2913                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
2914                 f5_calculate_mackey(connection);
2915                 break;
2916             case SM_SC_W2_CALCULATE_F5_LTK:
2917                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
2918                 f5_calculate_ltk(connection);
2919                 break;
2920             case SM_SC_W2_CALCULATE_G2:
2921                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2922                 g2_calculate(connection);
2923                 break;
2924 #endif
2925 
2926 #ifdef ENABLE_LE_CENTRAL
2927             // initiator side
2928 
2929             case SM_INITIATOR_PH4_HAS_LTK: {
2930 				sm_reset_setup();
2931 				sm_load_security_info(connection);
2932 
2933                 // cache key before using
2934                 sm_cache_ltk(connection, setup->sm_peer_ltk);
2935 
2936                 sm_key_t peer_ltk_flipped;
2937                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
2938                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
2939                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2940                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2941                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
2942                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
2943 
2944                 // notify after sending
2945                 sm_reencryption_started(connection);
2946                 return;
2947             }
2948 
2949 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2950 				sm_reset_setup();
2951 				sm_init_setup(connection);
2952 
2953                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
2954                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2955                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
2956                 sm_timeout_reset(connection);
2957 
2958                 // notify after sending
2959                 sm_pairing_started(connection);
2960                 break;
2961 #endif
2962 
2963 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2964             case SM_SC_SEND_PUBLIC_KEY_COMMAND:
2965                 sm_run_state_sc_send_public_key_command(connection);
2966                 break;
2967             case SM_SC_SEND_CONFIRMATION:
2968                 sm_run_state_sc_send_confirmation(connection);
2969                 break;
2970             case SM_SC_SEND_PAIRING_RANDOM:
2971                 sm_run_state_sc_send_pairing_random(connection);
2972                 break;
2973             case SM_SC_SEND_DHKEY_CHECK_COMMAND:
2974                 sm_run_state_sc_send_dhkey_check_command(connection);
2975                 break;
2976 #endif
2977 
2978 #ifdef ENABLE_LE_PERIPHERAL
2979 
2980 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
2981 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
2982 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2983 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2984 				sm_timeout_start(connection);
2985 				break;
2986 			}
2987 
2988 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2989 			case SM_SC_RECEIVED_LTK_REQUEST:
2990 				switch (connection->sm_irk_lookup_state){
2991 					case IRK_LOOKUP_SUCCEEDED:
2992 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
2993 						// start using context by loading security info
2994 						sm_reset_setup();
2995 						sm_load_security_info(connection);
2996 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
2997 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
2998 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
2999                             sm_reencryption_started(connection);
3000                             sm_trigger_run();
3001 							break;
3002 						}
3003 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
3004 						connection->sm_engine_state = SM_RESPONDER_IDLE;
3005 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
3006 						return;
3007 					default:
3008 						// just wait until IRK lookup is completed
3009 						break;
3010 				}
3011 				break;
3012 #endif /* ENABLE_LE_SECURE_CONNECTIONS */
3013 
3014 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
3015                 sm_reset_setup();
3016 
3017 			    // handle Pairing Request with LTK available
3018                 switch (connection->sm_irk_lookup_state) {
3019                     case IRK_LOOKUP_SUCCEEDED:
3020                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3021                         have_ltk = !sm_is_null_key(ltk);
3022                         if (have_ltk){
3023                             log_info("pairing request but LTK available");
3024                             // emit re-encryption start/fail sequence
3025                             sm_reencryption_started(connection);
3026                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
3027                         }
3028                         break;
3029                     default:
3030                         break;
3031                 }
3032 
3033 				sm_init_setup(connection);
3034 
3035 				// recover pairing request
3036 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3037 				err = sm_stk_generation_init(connection);
3038 
3039 #ifdef ENABLE_TESTING_SUPPORT
3040 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
3041                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
3042                         err = test_pairing_failure;
3043                     }
3044 #endif
3045 				if (err != 0){
3046                     // emit pairing started/failed sequence
3047                     sm_pairing_started(connection);
3048                     sm_pairing_error(connection, err);
3049 					sm_trigger_run();
3050 					break;
3051 				}
3052 
3053 				sm_timeout_start(connection);
3054 
3055 				// generate random number first, if we need to show passkey, otherwise send response
3056 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
3057 					btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph2_tk, (void *)(uintptr_t) connection->sm_handle);
3058 					break;
3059 				}
3060 
3061 				/* fall through */
3062 
3063             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
3064                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
3065 
3066                 // start with initiator key dist flags
3067                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
3068 
3069 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3070                 // LTK (= encryption information & master identification) only exchanged for LE Legacy Connection
3071                 if (setup->sm_use_secure_connections){
3072                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3073                 }
3074 #endif
3075                 // setup in response
3076                 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);
3077                 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);
3078 
3079                 // update key distribution after ENC was dropped
3080                 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));
3081 
3082                 if (setup->sm_use_secure_connections){
3083                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
3084                 } else {
3085                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
3086                 }
3087 
3088                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3089                 sm_timeout_reset(connection);
3090 
3091                 // notify after sending
3092                 sm_pairing_started(connection);
3093 
3094                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
3095                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
3096                     sm_trigger_user_response(connection);
3097                 }
3098                 return;
3099 #endif
3100 
3101             case SM_PH2_SEND_PAIRING_RANDOM: {
3102                 uint8_t buffer[17];
3103                 buffer[0] = SM_CODE_PAIRING_RANDOM;
3104                 reverse_128(setup->sm_local_random, &buffer[1]);
3105                 if (IS_RESPONDER(connection->sm_role)){
3106                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
3107                 } else {
3108                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
3109                 }
3110                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
3111                 sm_timeout_reset(connection);
3112                 break;
3113             }
3114 
3115             case SM_PH2_C1_GET_ENC_A:
3116                 // already busy?
3117                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3118                 // calculate confirm using aes128 engine - step 1
3119                 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);
3120                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
3121                 sm_aes128_state = SM_AES128_ACTIVE;
3122                 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);
3123                 break;
3124 
3125             case SM_PH2_C1_GET_ENC_C:
3126                 // already busy?
3127                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3128                 // calculate m_confirm using aes128 engine - step 1
3129                 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);
3130                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
3131                 sm_aes128_state = SM_AES128_ACTIVE;
3132                 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);
3133                 break;
3134 
3135             case SM_PH2_CALC_STK:
3136                 // already busy?
3137                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3138                 // calculate STK
3139                 if (IS_RESPONDER(connection->sm_role)){
3140                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
3141                 } else {
3142                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3143                 }
3144                 connection->sm_engine_state = SM_PH2_W4_STK;
3145                 sm_aes128_state = SM_AES128_ACTIVE;
3146                 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);
3147                 break;
3148 
3149             case SM_PH3_Y_GET_ENC:
3150                 // already busy?
3151                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3152                 // PH3B2 - calculate Y from      - enc
3153 
3154                 // dm helper (was sm_dm_r_prime)
3155                 // r' = padding || r
3156                 // r - 64 bit value
3157                 memset(&sm_aes128_plaintext[0], 0, 8);
3158                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3159 
3160                 // Y = dm(DHK, Rand)
3161                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
3162                 sm_aes128_state = SM_AES128_ACTIVE;
3163                 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);
3164                 break;
3165 
3166             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
3167                 uint8_t buffer[17];
3168                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
3169                 reverse_128(setup->sm_local_confirm, &buffer[1]);
3170                 if (IS_RESPONDER(connection->sm_role)){
3171                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
3172                 } else {
3173                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
3174                 }
3175                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
3176                 sm_timeout_reset(connection);
3177                 return;
3178             }
3179 #ifdef ENABLE_LE_PERIPHERAL
3180             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
3181                 // cache key before using
3182                 sm_cache_ltk(connection, setup->sm_ltk);
3183                 sm_key_t stk_flipped;
3184                 reverse_128(setup->sm_ltk, stk_flipped);
3185                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
3186                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
3187                 return;
3188             }
3189             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3190                 // allow to override LTK
3191                 if (sm_get_ltk_callback != NULL){
3192                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3193                 }
3194                 // cache key before using
3195                 sm_cache_ltk(connection, setup->sm_ltk);
3196                 sm_key_t ltk_flipped;
3197                 reverse_128(setup->sm_ltk, ltk_flipped);
3198                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
3199                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
3200                 return;
3201             }
3202 
3203 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
3204                 // already busy?
3205                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3206                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3207 
3208 				sm_reset_setup();
3209 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3210 
3211 				sm_reencryption_started(connection);
3212 
3213                 // dm helper (was sm_dm_r_prime)
3214                 // r' = padding || r
3215                 // r - 64 bit value
3216                 memset(&sm_aes128_plaintext[0], 0, 8);
3217                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3218 
3219                 // Y = dm(DHK, Rand)
3220                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3221                 sm_aes128_state = SM_AES128_ACTIVE;
3222                 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);
3223                 return;
3224 #endif
3225 #ifdef ENABLE_LE_CENTRAL
3226             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
3227                 // cache key before using
3228                 sm_cache_ltk(connection, setup->sm_ltk);
3229 
3230                 sm_key_t stk_flipped;
3231                 reverse_128(setup->sm_ltk, stk_flipped);
3232                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
3233                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
3234                 return;
3235             }
3236 #endif
3237 
3238             case SM_PH3_DISTRIBUTE_KEYS:
3239                 // send next key
3240                 if (setup->sm_key_distribution_send_set != 0){
3241                     sm_run_distribute_keys(connection);
3242                 }
3243 
3244                 // more to send?
3245                 if (setup->sm_key_distribution_send_set != 0){
3246                     return;
3247                 }
3248 
3249                 // keys are sent
3250                 if (IS_RESPONDER(connection->sm_role)){
3251                     // slave -> receive master keys if any
3252                     if (sm_key_distribution_all_received()){
3253                         sm_key_distribution_handle_all_received(connection);
3254                         sm_key_distribution_complete_responder(connection);
3255                         // start CTKD right away
3256                         continue;
3257                     } else {
3258                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3259                     }
3260                 } else {
3261                     sm_master_pairing_success(connection);
3262                 }
3263                 break;
3264 
3265 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3266             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3267                 // fill in sm setup (lite version of sm_init_setup)
3268                 sm_reset_setup();
3269                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3270                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3271                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3272                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3273                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3274                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3275                 setup->sm_use_secure_connections = true;
3276                 sm_ctkd_fetch_br_edr_link_key(connection);
3277 
3278                 // Enc Key and IRK if requested
3279                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3280 #ifdef ENABLE_LE_SIGNED_WRITE
3281                 // Plus signing key if supported
3282                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3283 #endif
3284                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3285                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3286                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3287                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3288                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3289                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3290                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3291 
3292                 // set state and send pairing response
3293                 sm_timeout_start(connection);
3294                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3295                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3296                 break;
3297 
3298             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3299                 // fill in sm setup (lite version of sm_init_setup)
3300                 sm_reset_setup();
3301                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3302                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3303                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3304                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3305                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3306                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3307                 setup->sm_use_secure_connections = true;
3308                 sm_ctkd_fetch_br_edr_link_key(connection);
3309                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3310 
3311                 // Enc Key and IRK if requested
3312                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3313 #ifdef ENABLE_LE_SIGNED_WRITE
3314                 // Plus signing key if supported
3315                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3316 #endif
3317                 // drop flags not requested by initiator
3318                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3319 
3320                 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use:
3321                 // - the IO Capability field,
3322                 // - the OOB data flag field, and
3323                 // - all bits in the Auth Req field except the CT2 bit.
3324                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3325                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3326                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3327                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3328                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3329                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3330                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3331 
3332                 // configure key distribution, LTK is derived locally
3333                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3334                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3335 
3336                 // set state and send pairing response
3337                 sm_timeout_start(connection);
3338                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3339                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3340                 break;
3341             case SM_BR_EDR_DISTRIBUTE_KEYS:
3342                 // send next key
3343                 if (setup->sm_key_distribution_send_set != 0) {
3344                     sm_run_distribute_keys(connection);
3345                 }
3346 
3347                 // more to send?
3348                 if (setup->sm_key_distribution_send_set != 0){
3349                     return;
3350                 }
3351 
3352                 // keys are sent
3353                 if (IS_RESPONDER(connection->sm_role)) {
3354                     // responder -> receive master keys if there are any
3355                     if (!sm_key_distribution_all_received()){
3356                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3357                         break;
3358                     }
3359                 }
3360                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3361                 sm_ctkd_start_from_br_edr(connection);
3362                 continue;
3363             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3364                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3365                 h6_calculate_ilk_from_le_ltk(connection);
3366                 break;
3367             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3368                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3369                 h6_calculate_br_edr_link_key(connection);
3370                 break;
3371             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3372                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3373                 h7_calculate_ilk_from_le_ltk(connection);
3374                 break;
3375             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3376                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3377                 h6_calculate_ilk_from_br_edr(connection);
3378                 break;
3379             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3380                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3381                 h6_calculate_le_ltk(connection);
3382                 break;
3383             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3384                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3385                 h7_calculate_ilk_from_br_edr(connection);
3386                 break;
3387 #endif
3388 
3389             default:
3390                 break;
3391         }
3392 
3393         // check again if active connection was released
3394         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
3395     }
3396 }
3397 
3398 // sm_aes128_state stays active
3399 static void sm_handle_encryption_result_enc_a(void *arg){
3400     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3401     sm_aes128_state = SM_AES128_IDLE;
3402 
3403     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3404     if (connection == NULL) return;
3405 
3406     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
3407     sm_aes128_state = SM_AES128_ACTIVE;
3408     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);
3409 }
3410 
3411 static void sm_handle_encryption_result_enc_b(void *arg){
3412     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3413     sm_aes128_state = SM_AES128_IDLE;
3414 
3415     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3416     if (connection == NULL) return;
3417 
3418     log_info_key("c1!", setup->sm_local_confirm);
3419     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
3420     sm_trigger_run();
3421 }
3422 
3423 // sm_aes128_state stays active
3424 static void sm_handle_encryption_result_enc_c(void *arg){
3425     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3426     sm_aes128_state = SM_AES128_IDLE;
3427 
3428     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3429     if (connection == NULL) return;
3430 
3431     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
3432     sm_aes128_state = SM_AES128_ACTIVE;
3433     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);
3434 }
3435 
3436 static void sm_handle_encryption_result_enc_d(void * arg){
3437     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3438     sm_aes128_state = SM_AES128_IDLE;
3439 
3440     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3441     if (connection == NULL) return;
3442 
3443     log_info_key("c1!", sm_aes128_ciphertext);
3444     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3445         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
3446         sm_trigger_run();
3447         return;
3448     }
3449     if (IS_RESPONDER(connection->sm_role)){
3450         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
3451         sm_trigger_run();
3452     } else {
3453         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3454         sm_aes128_state = SM_AES128_ACTIVE;
3455         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);
3456     }
3457 }
3458 
3459 static void sm_handle_encryption_result_enc_stk(void *arg){
3460     sm_aes128_state = SM_AES128_IDLE;
3461     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3462 
3463     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3464     if (connection == NULL) return;
3465 
3466     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
3467     log_info_key("stk", setup->sm_ltk);
3468     if (IS_RESPONDER(connection->sm_role)){
3469         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3470     } else {
3471         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
3472     }
3473     sm_trigger_run();
3474 }
3475 
3476 // sm_aes128_state stays active
3477 static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3478     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3479     sm_aes128_state = SM_AES128_IDLE;
3480 
3481     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3482     if (connection == NULL) return;
3483 
3484     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
3485     log_info_hex16("y", setup->sm_local_y);
3486     // PH3B3 - calculate EDIV
3487     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
3488     log_info_hex16("ediv", setup->sm_local_ediv);
3489     // PH3B4 - calculate LTK         - enc
3490     // LTK = d1(ER, DIV, 0))
3491     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
3492     sm_aes128_state = SM_AES128_ACTIVE;
3493     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);
3494 }
3495 
3496 #ifdef ENABLE_LE_PERIPHERAL
3497 // sm_aes128_state stays active
3498 static void sm_handle_encryption_result_enc_ph4_y(void *arg){
3499     sm_aes128_state = SM_AES128_IDLE;
3500     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3501 
3502     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3503     if (connection == NULL) return;
3504 
3505     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
3506     log_info_hex16("y", setup->sm_local_y);
3507 
3508     // PH3B3 - calculate DIV
3509     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
3510     log_info_hex16("ediv", setup->sm_local_ediv);
3511     // PH3B4 - calculate LTK         - enc
3512     // LTK = d1(ER, DIV, 0))
3513     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
3514     sm_aes128_state = SM_AES128_ACTIVE;
3515     btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_er, sm_aes128_plaintext, setup->sm_ltk, sm_handle_encryption_result_enc_ph4_ltk, (void *)(uintptr_t) connection->sm_handle);
3516 }
3517 #endif
3518 
3519 // sm_aes128_state stays active
3520 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3521     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3522     sm_aes128_state = SM_AES128_IDLE;
3523 
3524     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3525     if (connection == NULL) return;
3526 
3527     log_info_key("ltk", setup->sm_ltk);
3528     // calc CSRK next
3529     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
3530     sm_aes128_state = SM_AES128_ACTIVE;
3531     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);
3532 }
3533 
3534 static void sm_handle_encryption_result_enc_csrk(void *arg){
3535     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3536     sm_aes128_state = SM_AES128_IDLE;
3537 
3538     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3539     if (connection == NULL) return;
3540 
3541     sm_aes128_state = SM_AES128_IDLE;
3542     log_info_key("csrk", setup->sm_local_csrk);
3543     if (setup->sm_key_distribution_send_set != 0u){
3544         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3545     } else {
3546         // no keys to send, just continue
3547         if (IS_RESPONDER(connection->sm_role)){
3548             if (sm_key_distribution_all_received()){
3549                 sm_key_distribution_handle_all_received(connection);
3550                 sm_key_distribution_complete_responder(connection);
3551             } else {
3552                 // slave -> receive master keys
3553                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3554             }
3555         } else {
3556             sm_key_distribution_complete_initiator(connection);
3557         }
3558     }
3559     sm_trigger_run();
3560 }
3561 
3562 #ifdef ENABLE_LE_PERIPHERAL
3563 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3564     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3565     sm_aes128_state = SM_AES128_IDLE;
3566 
3567     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3568     if (connection == NULL) return;
3569 
3570     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
3571     log_info_key("ltk", setup->sm_ltk);
3572     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
3573     sm_trigger_run();
3574 }
3575 #endif
3576 
3577 static void sm_handle_encryption_result_address_resolution(void *arg){
3578     UNUSED(arg);
3579     sm_aes128_state = SM_AES128_IDLE;
3580 
3581     // compare calulated address against connecting device
3582     uint8_t * hash = &sm_aes128_ciphertext[13];
3583     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3584         log_info("LE Device Lookup: matched resolvable private address");
3585         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
3586         sm_trigger_run();
3587         return;
3588     }
3589     // no match, try next
3590     sm_address_resolution_test++;
3591     sm_trigger_run();
3592 }
3593 
3594 static void sm_handle_encryption_result_dkg_irk(void *arg){
3595     UNUSED(arg);
3596     sm_aes128_state = SM_AES128_IDLE;
3597 
3598     log_info_key("irk", sm_persistent_irk);
3599     dkg_state = DKG_CALC_DHK;
3600     sm_trigger_run();
3601 }
3602 
3603 static void sm_handle_encryption_result_dkg_dhk(void *arg){
3604     UNUSED(arg);
3605     sm_aes128_state = SM_AES128_IDLE;
3606 
3607     log_info_key("dhk", sm_persistent_dhk);
3608     dkg_state = DKG_READY;
3609     sm_trigger_run();
3610 }
3611 
3612 static void sm_handle_encryption_result_rau(void *arg){
3613     UNUSED(arg);
3614     sm_aes128_state = SM_AES128_IDLE;
3615 
3616     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3617     rau_state = RAU_IDLE;
3618     hci_le_random_address_set(sm_random_address);
3619 
3620     sm_trigger_run();
3621 }
3622 
3623 static void sm_handle_random_result_rau(void * arg){
3624     UNUSED(arg);
3625     // non-resolvable vs. resolvable
3626     switch (gap_random_adress_type){
3627         case GAP_RANDOM_ADDRESS_RESOLVABLE:
3628             // resolvable: use random as prand and calc address hash
3629             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
3630             sm_random_address[0u] &= 0x3fu;
3631             sm_random_address[0u] |= 0x40u;
3632             rau_state = RAU_GET_ENC;
3633             break;
3634         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
3635         default:
3636             // "The two most significant bits of the address shall be equal to ‘0’""
3637             sm_random_address[0u] &= 0x3fu;
3638             rau_state = RAU_IDLE;
3639             hci_le_random_address_set(sm_random_address);
3640             break;
3641     }
3642     sm_trigger_run();
3643 }
3644 
3645 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3646 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3647     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3648     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3649     if (connection == NULL) return;
3650 
3651     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
3652     sm_trigger_run();
3653 }
3654 
3655 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
3656     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3657     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3658     if (connection == NULL) return;
3659 
3660     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
3661     sm_trigger_run();
3662 }
3663 #endif
3664 
3665 static void sm_handle_random_result_ph2_random(void * arg){
3666     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3667     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3668     if (connection == NULL) return;
3669 
3670     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
3671     sm_trigger_run();
3672 }
3673 
3674 static void sm_handle_random_result_ph2_tk(void * arg){
3675     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3676     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3677     if (connection == NULL) return;
3678 
3679     sm_reset_tk();
3680     uint32_t tk;
3681     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
3682         // map random to 0-999999 without speding much cycles on a modulus operation
3683         tk = little_endian_read_32(sm_random_data,0);
3684         tk = tk & 0xfffff;  // 1048575
3685         if (tk >= 999999u){
3686             tk = tk - 999999u;
3687         }
3688     } else {
3689         // override with pre-defined passkey
3690         tk = sm_fixed_passkey_in_display_role;
3691     }
3692     big_endian_store_32(setup->sm_tk, 12, tk);
3693     if (IS_RESPONDER(connection->sm_role)){
3694         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
3695     } else {
3696         if (setup->sm_use_secure_connections){
3697             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3698         } else {
3699             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3700             sm_trigger_user_response(connection);
3701             // response_idle == nothing <--> sm_trigger_user_response() did not require response
3702             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3703                 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);
3704             }
3705         }
3706     }
3707     sm_trigger_run();
3708 }
3709 
3710 static void sm_handle_random_result_ph3_div(void * arg){
3711     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3712     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3713     if (connection == NULL) return;
3714 
3715     // use 16 bit from random value as div
3716     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3717     log_info_hex16("div", setup->sm_local_div);
3718     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
3719     sm_trigger_run();
3720 }
3721 
3722 static void sm_handle_random_result_ph3_random(void * arg){
3723     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3724     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3725     if (connection == NULL) return;
3726 
3727     reverse_64(sm_random_data, setup->sm_local_rand);
3728     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
3729     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
3730     // no db for authenticated flag hack: store flag in bit 4 of LSB
3731     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
3732     btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle);
3733 }
3734 static void sm_validate_er_ir(void){
3735     // warn about default ER/IR
3736     bool warning = false;
3737     if (sm_ir_is_default()){
3738         warning = true;
3739         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3740     }
3741     if (sm_er_is_default()){
3742         warning = true;
3743         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3744     }
3745     if (warning) {
3746         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3747     }
3748 }
3749 
3750 static void sm_handle_random_result_ir(void *arg){
3751     sm_persistent_keys_random_active = false;
3752     if (arg != NULL){
3753         // key generated, store in tlv
3754         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3755         log_info("Generated IR key. Store in TLV status: %d", status);
3756         UNUSED(status);
3757     }
3758     log_info_key("IR", sm_persistent_ir);
3759     dkg_state = DKG_CALC_IRK;
3760 
3761     if (test_use_fixed_local_irk){
3762         log_info_key("IRK", sm_persistent_irk);
3763         dkg_state = DKG_CALC_DHK;
3764     }
3765 
3766     sm_trigger_run();
3767 }
3768 
3769 static void sm_handle_random_result_er(void *arg){
3770     sm_persistent_keys_random_active = false;
3771     if (arg != NULL){
3772         // key generated, store in tlv
3773         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3774         log_info("Generated ER key. Store in TLV status: %d", status);
3775         UNUSED(status);
3776     }
3777     log_info_key("ER", sm_persistent_er);
3778 
3779     // try load ir
3780     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3781     if (key_size == 16){
3782         // ok, let's continue
3783         log_info("IR from TLV");
3784         sm_handle_random_result_ir( NULL );
3785     } else {
3786         // invalid, generate new random one
3787         sm_persistent_keys_random_active = true;
3788         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3789     }
3790 }
3791 
3792 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){
3793 
3794     // connection info
3795     sm_conn->sm_handle = con_handle;
3796     sm_conn->sm_role = role;
3797     sm_conn->sm_peer_addr_type = peer_addr_type;
3798     memcpy(sm_conn->sm_peer_address, peer_address, 6);
3799 
3800     // security properties
3801     sm_conn->sm_connection_encrypted = 0;
3802     sm_conn->sm_connection_authenticated = 0;
3803     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3804     sm_conn->sm_le_db_index = -1;
3805     sm_conn->sm_reencryption_active = false;
3806 
3807     // prepare CSRK lookup (does not involve setup)
3808     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3809 
3810     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3811 }
3812 
3813 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3814 static void sm_event_handle_classic_encryption_event(sm_connection_t * sm_conn, hci_con_handle_t con_handle){
3815     // CTKD requires BR/EDR Secure Connection
3816     if (sm_conn->sm_connection_encrypted != 2) return;
3817     // prepare for pairing request
3818     if (IS_RESPONDER(sm_conn->sm_role)){
3819         log_info("CTKD: SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST");
3820         sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3821     } else if (sm_conn->sm_pairing_requested){
3822         // check if remote supports fixed channels
3823         bool defer = true;
3824         const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3825         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE){
3826             // check if remote supports SMP over BR/EDR
3827             if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
3828                 log_info("CTKD: SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST");
3829                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3830             } else {
3831                 defer = false;
3832             }
3833         } else {
3834             // wait for fixed channel info
3835             log_info("CTKD: SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK");
3836             sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK;
3837         }
3838         if (defer){
3839             hci_dedicated_bonding_defer_disconnect(con_handle, true);
3840         }
3841     }
3842 }
3843 #endif
3844 
3845 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3846 
3847     UNUSED(channel);    // ok: there is no channel
3848     UNUSED(size);       // ok: fixed format HCI events
3849 
3850     sm_connection_t * sm_conn;
3851     hci_con_handle_t  con_handle;
3852     uint8_t           status;
3853     bd_addr_t         addr;
3854     bd_addr_type_t    addr_type;
3855 
3856     switch (packet_type) {
3857 
3858 		case HCI_EVENT_PACKET:
3859 			switch (hci_event_packet_get_type(packet)) {
3860 
3861                 case BTSTACK_EVENT_STATE:
3862                     switch (btstack_event_state_get_state(packet)){
3863                         case HCI_STATE_WORKING:
3864                             log_info("HCI Working!");
3865                             // setup IR/ER with TLV
3866                             btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
3867                             if (sm_tlv_impl != NULL){
3868                                 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3869                                 if (key_size == 16){
3870                                     // ok, let's continue
3871                                     log_info("ER from TLV");
3872                                     sm_handle_random_result_er( NULL );
3873                                 } else {
3874                                     // invalid, generate random one
3875                                     sm_persistent_keys_random_active = true;
3876                                     btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3877                                 }
3878                             } else {
3879                                 sm_validate_er_ir();
3880                                 dkg_state = DKG_CALC_IRK;
3881 
3882                                 if (test_use_fixed_local_irk){
3883                                     log_info_key("IRK", sm_persistent_irk);
3884                                     dkg_state = DKG_CALC_DHK;
3885                                 }
3886                             }
3887 
3888 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3889                             // trigger ECC key generation
3890                             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
3891                                 sm_ec_generate_new_key();
3892                             }
3893 #endif
3894 
3895                             // restart random address updates after power cycle
3896                             if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){
3897                                 gap_random_address_set(sm_random_address);
3898                             } else {
3899                                 gap_random_address_set_mode(gap_random_adress_type);
3900                             }
3901                             break;
3902 
3903                         case HCI_STATE_OFF:
3904                         case HCI_STATE_HALTING:
3905                             log_info("SM: reset state");
3906                             // stop random address update
3907                             gap_random_address_update_stop();
3908                             // reset state
3909                             sm_state_reset();
3910                             break;
3911 
3912                         default:
3913                             break;
3914                     }
3915 					break;
3916 
3917 #ifdef ENABLE_CLASSIC
3918 			    case HCI_EVENT_CONNECTION_COMPLETE:
3919 			        // ignore if connection failed
3920 			        if (hci_event_connection_complete_get_status(packet)) return;
3921 
3922 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
3923 			        sm_conn = sm_get_connection_for_handle(con_handle);
3924 			        if (!sm_conn) break;
3925 
3926                     hci_event_connection_complete_get_bd_addr(packet, addr);
3927 			        sm_connection_init(sm_conn,
3928                                        con_handle,
3929                                        (uint8_t) gap_get_role(con_handle),
3930                                        BD_ADDR_TYPE_LE_PUBLIC,
3931                                        addr);
3932 			        // classic connection corresponds to public le address
3933 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
3934                     gap_local_bd_addr(sm_conn->sm_own_address);
3935                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3936                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
3937 			        break;
3938 
3939 #endif
3940 
3941 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3942                 case HCI_EVENT_ROLE_CHANGE:
3943                     hci_event_role_change_get_bd_addr(packet, addr);
3944                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3945                     if (sm_conn == NULL) break;
3946                     sm_conn->sm_role = hci_event_role_change_get_role(packet);
3947                     break;
3948 
3949 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3950 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3951                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3952                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3953                     if (sm_conn == NULL) break;
3954                     sm_conn->sm_pairing_requested = true;
3955 			        break;
3956 #endif
3957 
3958 			    case HCI_EVENT_META_GAP:
3959 			        switch (hci_event_gap_meta_get_subevent_code(packet)) {
3960 			            case GAP_SUBEVENT_LE_CONNECTION_COMPLETE:
3961 			                // ignore if connection failed
3962 			                if (gap_subevent_le_connection_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3963 
3964 			                con_handle = gap_subevent_le_connection_complete_get_connection_handle(packet);
3965 			                sm_conn = sm_get_connection_for_handle(con_handle);
3966 			                if (!sm_conn) break;
3967 
3968                             // Get current peer address
3969                             addr_type = gap_subevent_le_connection_complete_get_peer_address_type(packet);
3970                             if (hci_is_le_identity_address_type(addr_type)){
3971                                 addr_type = BD_ADDR_TYPE_LE_RANDOM;
3972                                 gap_subevent_le_connection_complete_get_peer_resolvable_private_address(packet, addr);
3973                             } else {
3974                                 gap_subevent_le_connection_complete_get_peer_address(packet, addr);
3975                             }
3976 			                sm_connection_init(sm_conn,
3977                                                con_handle,
3978                                                gap_subevent_le_connection_complete_get_role(packet),
3979                                                addr_type,
3980                                                addr);
3981 			                sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3982 
3983 			                // track our addr used for this connection and set state
3984 #ifdef ENABLE_LE_PERIPHERAL
3985 			                if (gap_subevent_le_connection_complete_get_role(packet) != 0){
3986 			                    // responder - use own address from advertisements
3987 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
3988                                 if (hci_le_extended_advertising_supported()){
3989                                     // cache local resolvable address
3990                                     // note: will be overwritten if random or private address was used in adv set by HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED
3991                                     sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_RANDOM;
3992                                     gap_subevent_le_connection_complete_get_local_resolvable_private_address(packet,sm_conn->sm_own_address);
3993                                 } else
3994 #endif
3995                                 {
3996                                     gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3997                                 }
3998 			                    sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3999 			                }
4000 #endif
4001 #ifdef ENABLE_LE_CENTRAL
4002 			                if (gap_subevent_le_connection_complete_get_role(packet) == 0){
4003 			                    // initiator - use own address from create connection
4004 			                    gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
4005 			                    sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4006 			                }
4007 #endif
4008 			                break;
4009 			            default:
4010 			                break;
4011 			        }
4012 			        break;
4013                 case HCI_EVENT_LE_META:
4014                     switch (hci_event_le_meta_get_subevent_code(packet)) {
4015 #ifdef ENABLE_LE_PERIPHERAL
4016 #ifdef ENABLE_LE_EXTENDED_ADVERTISING
4017                         case HCI_SUBEVENT_LE_ADVERTISING_SET_TERMINATED:
4018                             if (hci_subevent_le_advertising_set_terminated_get_status(packet) == ERROR_CODE_SUCCESS){
4019                                 uint8_t advertising_handle = hci_subevent_le_advertising_set_terminated_get_advertising_handle(packet);
4020                                 con_handle = hci_subevent_le_advertising_set_terminated_get_connection_handle(packet);
4021                                 sm_conn = sm_get_connection_for_handle(con_handle);
4022                                 if (!sm_conn) break;
4023 
4024                                 gap_le_get_own_advertising_set_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address, advertising_handle);
4025                                 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,
4026                                          bd_addr_to_str(sm_conn->sm_own_address), con_handle);
4027                             }
4028                             break;
4029 #endif
4030 #endif
4031                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
4032                             con_handle = hci_subevent_le_long_term_key_request_get_connection_handle(packet);
4033                             sm_conn = sm_get_connection_for_handle(con_handle);
4034                             if (!sm_conn) break;
4035 
4036                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
4037                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
4038                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
4039                                 break;
4040                             }
4041                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
4042                                 // PH2 SEND LTK as we need to exchange keys in PH3
4043                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
4044                                 break;
4045                             }
4046 
4047                             // store rand and ediv
4048                             reverse_64(&packet[5], sm_conn->sm_local_rand);
4049                             sm_conn->sm_local_ediv = hci_subevent_le_long_term_key_request_get_encryption_diversifier(packet);
4050 
4051                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
4052                             // potentially stored LTK is from the master
4053                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
4054                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
4055                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
4056                                     break;
4057                                 }
4058                                 // additionally check if remote is in LE Device DB if requested
4059                                 switch(sm_conn->sm_irk_lookup_state){
4060                                     case IRK_LOOKUP_FAILED:
4061                                         log_info("LTK Request: device not in device db");
4062                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
4063                                         break;
4064                                     case IRK_LOOKUP_SUCCEEDED:
4065                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
4066                                         break;
4067                                     default:
4068                                         // wait for irk look doen
4069                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
4070                                         break;
4071                                 }
4072                                 break;
4073                             }
4074 
4075 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4076                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
4077 #else
4078                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
4079                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
4080 #endif
4081                             break;
4082 
4083                         default:
4084                             break;
4085                     }
4086                     break;
4087 
4088                 case HCI_EVENT_ENCRYPTION_CHANGE:
4089                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
4090                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
4091                     sm_conn = sm_get_connection_for_handle(con_handle);
4092                     if (!sm_conn) break;
4093 
4094                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
4095                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
4096                         sm_conn->sm_actual_encryption_key_size);
4097                     log_info("event handler, state %u", sm_conn->sm_engine_state);
4098 
4099                     switch (sm_conn->sm_engine_state){
4100 
4101                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
4102                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
4103                             if (sm_conn->sm_connection_encrypted != 0u) {
4104                                 status = ERROR_CODE_SUCCESS;
4105                                 if (IS_RESPONDER(sm_conn->sm_role)){
4106                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
4107                                 } else {
4108                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4109                                 }
4110                             } else {
4111                                 status = hci_event_encryption_change_get_status(packet);
4112                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
4113                                 // also, gap_reconnect_security_setup_active will return true
4114                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
4115                             }
4116 
4117                             // emit re-encryption complete
4118                             sm_reencryption_complete(sm_conn, status);
4119 
4120                             // notify client, if pairing was requested before
4121                             if (sm_conn->sm_pairing_requested){
4122                                 sm_conn->sm_pairing_requested = false;
4123                                 sm_pairing_complete(sm_conn, status, 0);
4124                             }
4125 
4126                             sm_done_for_handle(sm_conn->sm_handle);
4127                             break;
4128 
4129                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
4130                             if (!sm_conn->sm_connection_encrypted) break;
4131                             // handler for HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE
4132                             // contains the same code for this state
4133                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
4134                             if (IS_RESPONDER(sm_conn->sm_role)){
4135                                 // slave
4136                                 if (sm_conn->sm_connection_sc){
4137                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4138                                 } else {
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                                 }
4141                             } else {
4142                                 // master
4143                                 if (sm_key_distribution_all_received()){
4144                                     // skip receiving keys as there are none
4145                                     sm_key_distribution_handle_all_received(sm_conn);
4146                                     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);
4147                                 } else {
4148                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
4149                                 }
4150                             }
4151                             break;
4152 
4153 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4154                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
4155                             sm_event_handle_classic_encryption_event(sm_conn, con_handle);
4156                             break;
4157 #endif
4158                         default:
4159                             break;
4160                     }
4161                     break;
4162 
4163                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
4164                     con_handle = little_endian_read_16(packet, 3);
4165                     sm_conn = sm_get_connection_for_handle(con_handle);
4166                     if (!sm_conn) break;
4167 
4168                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
4169                     log_info("event handler, state %u", sm_conn->sm_engine_state);
4170                     // continue if part of initial pairing
4171                     switch (sm_conn->sm_engine_state){
4172                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
4173                             if (IS_RESPONDER(sm_conn->sm_role)){
4174                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
4175                             } else {
4176                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4177                             }
4178                             sm_done_for_handle(sm_conn->sm_handle);
4179                             break;
4180                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
4181                             // handler for HCI_EVENT_ENCRYPTION_CHANGE
4182                             // contains the same code for this state
4183                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
4184                             if (IS_RESPONDER(sm_conn->sm_role)){
4185                                 // slave
4186                                 if (sm_conn->sm_connection_sc){
4187                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4188                                 } else {
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                                 }
4191                             } else {
4192                                 // master
4193                                 if (sm_key_distribution_all_received()){
4194                                     // skip receiving keys as there are none
4195                                     sm_key_distribution_handle_all_received(sm_conn);
4196                                     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);
4197                                 } else {
4198                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
4199                                 }
4200                             }
4201                             break;
4202 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4203                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
4204                             sm_event_handle_classic_encryption_event(sm_conn, con_handle);
4205                             break;
4206 #endif
4207                         default:
4208                             break;
4209                     }
4210                     break;
4211 
4212 
4213                 case HCI_EVENT_DISCONNECTION_COMPLETE:
4214                     con_handle = little_endian_read_16(packet, 3);
4215                     sm_done_for_handle(con_handle);
4216                     sm_conn = sm_get_connection_for_handle(con_handle);
4217                     if (!sm_conn) break;
4218 
4219                     // pairing failed, if it was ongoing
4220                     switch (sm_conn->sm_engine_state){
4221                         case SM_GENERAL_IDLE:
4222                         case SM_INITIATOR_CONNECTED:
4223                         case SM_RESPONDER_IDLE:
4224                             break;
4225                         default:
4226                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
4227                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
4228                             break;
4229                     }
4230 
4231                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
4232                     sm_conn->sm_handle = 0;
4233                     break;
4234 
4235                 case HCI_EVENT_COMMAND_COMPLETE:
4236                     if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) {
4237                         // set local addr for le device db
4238                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
4239                         le_device_db_set_local_bd_addr(addr);
4240                     }
4241                     break;
4242 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4243                 case L2CAP_EVENT_INFORMATION_RESPONSE:
4244                     con_handle = l2cap_event_information_response_get_con_handle(packet);
4245                     sm_conn = sm_get_connection_for_handle(con_handle);
4246                     if (!sm_conn) break;
4247                     if (sm_conn->sm_engine_state == SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK){
4248                         // check if remote supports SMP over BR/EDR
4249                         const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
4250                         if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
4251                             sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
4252                         } else {
4253                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4254                             hci_dedicated_bonding_defer_disconnect(con_handle, false);
4255                         }
4256                     }
4257                     break;
4258 #endif
4259                 default:
4260                     break;
4261 			}
4262             break;
4263         default:
4264             break;
4265 	}
4266 
4267     sm_run();
4268 }
4269 
4270 static inline int sm_calc_actual_encryption_key_size(int other){
4271     if (other < sm_min_encryption_key_size) return 0;
4272     if (other < sm_max_encryption_key_size) return other;
4273     return sm_max_encryption_key_size;
4274 }
4275 
4276 
4277 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4278 static bool sm_just_works_or_numeric_comparison(stk_generation_method_t method){
4279     switch (method){
4280         case JUST_WORKS:
4281         case NUMERIC_COMPARISON:
4282             return true;
4283         default:
4284             return false;
4285     }
4286 }
4287 // responder
4288 
4289 static bool sm_passkey_used(stk_generation_method_t method){
4290     switch (method){
4291         case PK_RESP_INPUT:
4292             return true;
4293         default:
4294             return 0;
4295     }
4296 }
4297 
4298 static bool sm_passkey_entry(stk_generation_method_t method){
4299     switch (method){
4300         case PK_RESP_INPUT:
4301         case PK_INIT_INPUT:
4302         case PK_BOTH_INPUT:
4303             return true;
4304         default:
4305             return false;
4306     }
4307 }
4308 
4309 #endif
4310 
4311 /**
4312  * @return ok
4313  */
4314 static int sm_validate_stk_generation_method(void){
4315     // check if STK generation method is acceptable by client
4316     switch (setup->sm_stk_generation_method){
4317         case JUST_WORKS:
4318             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
4319         case PK_RESP_INPUT:
4320         case PK_INIT_INPUT:
4321         case PK_BOTH_INPUT:
4322             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
4323         case OOB:
4324             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
4325         case NUMERIC_COMPARISON:
4326             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
4327         default:
4328             return 0;
4329     }
4330 }
4331 
4332 #ifdef ENABLE_LE_CENTRAL
4333 static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
4334 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4335     if (sm_sc_only_mode){
4336         uint8_t auth_req = packet[1];
4337         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
4338             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
4339             return;
4340         }
4341     }
4342 #else
4343     UNUSED(packet);
4344 #endif
4345 
4346     int have_ltk;
4347     uint8_t ltk[16];
4348 
4349     // IRK complete?
4350     switch (sm_conn->sm_irk_lookup_state){
4351         case IRK_LOOKUP_FAILED:
4352             // start pairing
4353             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4354             break;
4355         case IRK_LOOKUP_SUCCEEDED:
4356             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4357             have_ltk = !sm_is_null_key(ltk);
4358             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
4359             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
4360                 // start re-encrypt if we have LTK and the connection is not already encrypted
4361                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4362             } else {
4363                 // start pairing
4364                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4365             }
4366             break;
4367         default:
4368             // otherwise, store security request
4369             sm_conn->sm_security_request_received = true;
4370             break;
4371     }
4372 }
4373 #endif
4374 
4375 static uint8_t sm_pdu_validate_and_get_opcode(uint8_t packet_type, const uint8_t *packet, uint16_t size){
4376 
4377     // size of complete sm_pdu used to validate input
4378     static const uint8_t sm_pdu_size[] = {
4379             0,  // 0x00 invalid opcode
4380             7,  // 0x01 pairing request
4381             7,  // 0x02 pairing response
4382             17, // 0x03 pairing confirm
4383             17, // 0x04 pairing random
4384             2,  // 0x05 pairing failed
4385             17, // 0x06 encryption information
4386             11, // 0x07 master identification
4387             17, // 0x08 identification information
4388             8,  // 0x09 identify address information
4389             17, // 0x0a signing information
4390             2,  // 0x0b security request
4391             65, // 0x0c pairing public key
4392             17, // 0x0d pairing dhk check
4393             2,  // 0x0e keypress notification
4394     };
4395 
4396     if (packet_type != SM_DATA_PACKET) return 0;
4397     if (size == 0u) return 0;
4398 
4399     uint8_t sm_pdu_code = packet[0];
4400 
4401     // validate pdu size
4402     if (sm_pdu_code >= sizeof(sm_pdu_size)) return 0;
4403     if (sm_pdu_size[sm_pdu_code] != size)   return 0;
4404 
4405     return sm_pdu_code;
4406 }
4407 
4408 
4409 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4410 static void sm_pdu_handler_pairing_public_key(sm_connection_t * sm_conn, const uint8_t * packet) {
4411     // store public key for DH Key calculation
4412     reverse_256(&packet[01], &setup->sm_peer_q[0]);
4413     reverse_256(&packet[33], &setup->sm_peer_q[32]);
4414 
4415     // CVE-2020-26558: abort pairing if remote uses the same public key
4416     if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
4417         log_info("Remote PK matches ours");
4418         sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4419         return;
4420     }
4421 
4422     // validate public key
4423     int err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
4424     if (err != 0){
4425         log_info("sm: peer public key invalid %x", err);
4426         sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4427         return;
4428     }
4429 
4430     // start calculating dhkey
4431     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);
4432 
4433     log_info("public key received, generation method %u", setup->sm_stk_generation_method);
4434     if (IS_RESPONDER(sm_conn->sm_role)){
4435         // responder
4436         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4437     } else {
4438         // initiator
4439         // stk generation method
4440         // passkey entry: notify app to show passkey or to request passkey
4441         switch (setup->sm_stk_generation_method){
4442             case JUST_WORKS:
4443             case NUMERIC_COMPARISON:
4444                 sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4445                 break;
4446             case PK_RESP_INPUT:
4447                 sm_sc_start_calculating_local_confirm(sm_conn);
4448                 break;
4449             case PK_INIT_INPUT:
4450             case PK_BOTH_INPUT:
4451                 if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
4452                     sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
4453                     break;
4454                 }
4455                 sm_sc_start_calculating_local_confirm(sm_conn);
4456                 break;
4457             case OOB:
4458                 if (setup->sm_have_oob_data){
4459                     // if we have received rb & cb, verify Cb = f4(PKb, PKb, rb, 0)
4460                     sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4461                 } else {
4462                     // otherwise, generate our nonce
4463                     sm_sc_generate_nx_for_send_random(sm_conn);
4464                 }
4465                 break;
4466             default:
4467                 btstack_assert(false);
4468                 break;
4469         }
4470     }
4471 }
4472 #endif
4473 
4474 
4475 static void sm_pdu_handler(sm_connection_t *sm_conn, uint8_t sm_pdu_code, const uint8_t *packet) {
4476     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
4477 
4478 #ifdef ENABLE_LE_CENTRAL
4479     int err;
4480 #endif
4481     uint8_t max_encryption_key_size;
4482 
4483     switch (sm_conn->sm_engine_state){
4484 
4485         // a sm timeout requires a new physical connection
4486         case SM_GENERAL_TIMEOUT:
4487             return;
4488 
4489 #ifdef ENABLE_LE_CENTRAL
4490 
4491         // Initiator
4492         case SM_INITIATOR_CONNECTED:
4493             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
4494                 sm_pdu_received_in_wrong_state(sm_conn);
4495                 break;
4496             }
4497             sm_initiator_connected_handle_security_request(sm_conn, packet);
4498             break;
4499 
4500         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4501             // Core 5, Vol 3, Part H, 2.4.6:
4502             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4503             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4504             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4505                 log_info("Ignoring Security Request");
4506                 break;
4507             }
4508 
4509             // all other pdus are incorrect
4510             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4511                 sm_pdu_received_in_wrong_state(sm_conn);
4512                 break;
4513             }
4514 
4515             // store pairing request
4516             (void)memcpy(&setup->sm_s_pres, packet,
4517                          sizeof(sm_pairing_packet_t));
4518 
4519             // validate encryption key size
4520             max_encryption_key_size = sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres);
4521             if ((max_encryption_key_size < 7) || (max_encryption_key_size > 16)){
4522                 sm_pairing_error(sm_conn, SM_REASON_INVALID_PARAMETERS);
4523                 break;
4524             }
4525 
4526             err = sm_stk_generation_init(sm_conn);
4527 
4528 #ifdef ENABLE_TESTING_SUPPORT
4529             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
4530                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
4531                 err = test_pairing_failure;
4532             }
4533 #endif
4534 
4535             if (err != 0){
4536                 sm_pairing_error(sm_conn, err);
4537                 break;
4538             }
4539 
4540             // generate random number first, if we need to show passkey
4541             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4542                 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);
4543                 break;
4544             }
4545 
4546 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4547             if (setup->sm_use_secure_connections){
4548                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
4549                 if (setup->sm_stk_generation_method == JUST_WORKS){
4550                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4551                     sm_trigger_user_response(sm_conn);
4552                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4553                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4554                     }
4555                 } else {
4556                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4557                 }
4558                 break;
4559             }
4560 #endif
4561             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4562             sm_trigger_user_response(sm_conn);
4563             // response_idle == nothing <--> sm_trigger_user_response() did not require response
4564             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4565                 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);
4566             }
4567             break;
4568 
4569         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
4570             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
4571                 sm_pdu_received_in_wrong_state(sm_conn);
4572                 break;
4573             }
4574 
4575             // store s_confirm
4576             reverse_128(&packet[1], setup->sm_peer_confirm);
4577 
4578             // abort if s_confirm matches m_confirm
4579             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4580                 sm_pdu_received_in_wrong_state(sm_conn);
4581                 break;
4582             }
4583 
4584 #ifdef ENABLE_TESTING_SUPPORT
4585             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4586                 log_info("testing_support: reset confirm value");
4587                 memset(setup->sm_peer_confirm, 0, 16);
4588             }
4589 #endif
4590             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
4591             break;
4592 
4593         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
4594             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4595                 sm_pdu_received_in_wrong_state(sm_conn);
4596                 break;;
4597             }
4598 
4599             // received random value
4600             reverse_128(&packet[1], setup->sm_peer_random);
4601             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
4602             break;
4603 
4604         case SM_INITIATOR_PH4_HAS_LTK:
4605         case SM_PH4_W4_CONNECTION_ENCRYPTED:
4606             // ignore Security Request, see SM_INITIATOR_PH1_W4_PAIRING_RESPONSE above
4607             if (sm_pdu_code != SM_CODE_SECURITY_REQUEST){
4608                 sm_pdu_received_in_wrong_state(sm_conn);
4609             }
4610             break;
4611 #endif
4612 
4613 #ifdef ENABLE_LE_PERIPHERAL
4614         // Responder
4615         case SM_RESPONDER_IDLE:
4616         case SM_RESPONDER_SEND_SECURITY_REQUEST:
4617         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
4618             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4619                 sm_pdu_received_in_wrong_state(sm_conn);
4620                 break;;
4621             }
4622 
4623             // store pairing request
4624             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4625 
4626             // validation encryption key size
4627             max_encryption_key_size = sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq);
4628             if ((max_encryption_key_size < 7) || (max_encryption_key_size > 16)){
4629                 sm_pairing_error(sm_conn, SM_REASON_INVALID_PARAMETERS);
4630                 break;
4631             }
4632 
4633             // check if IRK completed
4634             switch (sm_conn->sm_irk_lookup_state){
4635                 case IRK_LOOKUP_SUCCEEDED:
4636                 case IRK_LOOKUP_FAILED:
4637                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
4638                     break;
4639                 default:
4640                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4641                     break;
4642             }
4643             break;
4644 #endif
4645 
4646 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4647         case SM_SC_W4_PUBLIC_KEY_COMMAND:
4648             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
4649                 sm_pdu_received_in_wrong_state(sm_conn);
4650                 break;
4651             }
4652             sm_pdu_handler_pairing_public_key(sm_conn, packet);
4653             break;
4654 
4655         case SM_SC_W4_CONFIRMATION:
4656             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
4657                 sm_pdu_received_in_wrong_state(sm_conn);
4658                 break;
4659             }
4660             // received confirm value
4661             reverse_128(&packet[1], setup->sm_peer_confirm);
4662 
4663 #ifdef ENABLE_TESTING_SUPPORT
4664             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4665                 log_info("testing_support: reset confirm value");
4666                 memset(setup->sm_peer_confirm, 0, 16);
4667             }
4668 #endif
4669             if (IS_RESPONDER(sm_conn->sm_role)){
4670                 // responder
4671                 if (sm_passkey_used(setup->sm_stk_generation_method)){
4672                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
4673                         // still waiting for passkey
4674                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
4675                         break;
4676                     }
4677                 }
4678                 sm_sc_start_calculating_local_confirm(sm_conn);
4679             } else {
4680                 // initiator
4681                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
4682                     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);
4683                 } else {
4684                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
4685                 }
4686             }
4687             break;
4688 
4689         case SM_SC_W4_PAIRING_RANDOM:
4690             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4691                 sm_pdu_received_in_wrong_state(sm_conn);
4692                 break;
4693             }
4694 
4695             // received random value
4696             reverse_128(&packet[1], setup->sm_peer_nonce);
4697 
4698             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4699             // only check for JUST WORK/NC in initiator role OR passkey entry
4700             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4701                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4702                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
4703             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4704             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4705                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4706                  break;
4707             }
4708 
4709             // OOB
4710             if (setup->sm_stk_generation_method == OOB){
4711 
4712                 // setup local random, set to zero if remote did not receive our data
4713                 log_info("Received nonce, setup local random ra/rb for dhkey check");
4714                 if (IS_RESPONDER(sm_conn->sm_role)) {
4715                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u) {
4716                         log_info("Reset rb as A does not have OOB data");
4717                         memset(setup->sm_rb, 0, 16);
4718                     } else {
4719                         (void) memcpy(setup->sm_rb, sm_sc_oob_random, 16);
4720                         log_info("Use stored rb");
4721                         log_info_hexdump(setup->sm_rb, 16);
4722                     }
4723                 } else {
4724                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
4725                         log_info("Reset ra as B does not have OOB data");
4726                         memset(setup->sm_ra, 0, 16);
4727                     } else {
4728                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
4729                         log_info("Use stored ra");
4730                         log_info_hexdump(setup->sm_ra, 16);
4731                     }
4732                 }
4733 
4734                 if (IS_RESPONDER(sm_conn->sm_role)){
4735                     if (setup->sm_have_oob_data){
4736                         // if we have received ra & ca, verify Ca = f4(PKa, PKa, ra, 0)
4737                         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4738                     } else {
4739                         // otherwise, generate our nonce
4740                         sm_sc_generate_nx_for_send_random(sm_conn);
4741                     }
4742                 } else {
4743                     // Confirm value already validated if received before,
4744                     // move on to DHKey check
4745                     sm_sc_prepare_dhkey_check(sm_conn);
4746                 }
4747                 break;
4748             }
4749 
4750             // TODO: we only get here for Responder role with JW/NC
4751             sm_sc_state_after_receiving_random(sm_conn);
4752             break;
4753 
4754         case SM_SC_W2_CALCULATE_G2:
4755         case SM_SC_W4_CALCULATE_G2:
4756         case SM_SC_W4_CALCULATE_DHKEY:
4757         case SM_SC_W2_CALCULATE_F5_SALT:
4758         case SM_SC_W4_CALCULATE_F5_SALT:
4759         case SM_SC_W2_CALCULATE_F5_MACKEY:
4760         case SM_SC_W4_CALCULATE_F5_MACKEY:
4761         case SM_SC_W2_CALCULATE_F5_LTK:
4762         case SM_SC_W4_CALCULATE_F5_LTK:
4763         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4764         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4765         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4766         case SM_SC_W4_USER_RESPONSE:
4767             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4768                 sm_pdu_received_in_wrong_state(sm_conn);
4769                 break;
4770             }
4771             // store DHKey Check
4772             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4773             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4774 
4775             // have we been only waiting for dhkey check command?
4776             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4777                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4778             }
4779             break;
4780 #endif
4781 
4782 #ifdef ENABLE_LE_PERIPHERAL
4783         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
4784             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
4785                 sm_pdu_received_in_wrong_state(sm_conn);
4786                 break;
4787             }
4788 
4789             // received confirm value
4790             reverse_128(&packet[1], setup->sm_peer_confirm);
4791 
4792 #ifdef ENABLE_TESTING_SUPPORT
4793             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4794                 log_info("testing_support: reset confirm value");
4795                 memset(setup->sm_peer_confirm, 0, 16);
4796             }
4797 #endif
4798             // notify client to hide shown passkey
4799             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
4800                 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
4801             }
4802 
4803             // handle user cancel pairing?
4804             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4805                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4806                 break;
4807             }
4808 
4809             // wait for user action?
4810             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
4811                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4812                 break;
4813             }
4814 
4815             // calculate and send local_confirm
4816             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);
4817             break;
4818 
4819         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
4820             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4821                 sm_pdu_received_in_wrong_state(sm_conn);
4822                 break;;
4823             }
4824 
4825             // received random value
4826             reverse_128(&packet[1], setup->sm_peer_random);
4827             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
4828             break;
4829 #endif
4830 
4831         case SM_PH2_W4_CONNECTION_ENCRYPTED:
4832         case SM_PH3_RECEIVE_KEYS:
4833             switch(sm_pdu_code){
4834                 case SM_CODE_ENCRYPTION_INFORMATION:
4835                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
4836                     reverse_128(&packet[1], setup->sm_peer_ltk);
4837                     break;
4838 
4839                 case SM_CODE_MASTER_IDENTIFICATION:
4840                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4841                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
4842                     reverse_64(&packet[3], setup->sm_peer_rand);
4843                     break;
4844 
4845                 case SM_CODE_IDENTITY_INFORMATION:
4846                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4847                     reverse_128(&packet[1], setup->sm_peer_irk);
4848                     break;
4849 
4850                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4851                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4852                     setup->sm_peer_addr_type = packet[1];
4853                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4854                     break;
4855 
4856                 case SM_CODE_SIGNING_INFORMATION:
4857                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4858                     reverse_128(&packet[1], setup->sm_peer_csrk);
4859                     break;
4860                 default:
4861                     // Unexpected PDU
4862                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4863                     break;
4864             }
4865             // done with key distribution?
4866             if (sm_key_distribution_all_received()){
4867 
4868                 sm_key_distribution_handle_all_received(sm_conn);
4869 
4870                 if (IS_RESPONDER(sm_conn->sm_role)){
4871                     sm_key_distribution_complete_responder(sm_conn);
4872                 } else {
4873                     if (setup->sm_use_secure_connections){
4874                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4875                     } else {
4876                         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);
4877                     }
4878                 }
4879             }
4880             break;
4881 
4882 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4883 
4884         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
4885             // GAP/DM/LEP/BI-02-C - reject CTKD if P-192 encryption is used
4886             if (sm_pdu_code == SM_CODE_PAIRING_REQUEST){
4887                 sm_pairing_error(sm_conn, SM_REASON_CROSS_TRANSPORT_KEY_DERIVATION_NOT_ALLOWED);
4888             }
4889             break;
4890 
4891         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4892 
4893             // dedicated bonding complete
4894             hci_dedicated_bonding_defer_disconnect(sm_conn->sm_handle, false);
4895 
4896             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4897                 sm_pdu_received_in_wrong_state(sm_conn);
4898                 break;
4899             }
4900             // store pairing response
4901             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4902 
4903             // validate encryption key size
4904             max_encryption_key_size = sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres);
4905             if ((max_encryption_key_size < 7) || (max_encryption_key_size > 16)){
4906                 sm_pairing_error(sm_conn, SM_REASON_INVALID_PARAMETERS);
4907                 break;
4908             }
4909             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(max_encryption_key_size);
4910             // SC Only mandates 128 bit key size
4911             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4912                 sm_conn->sm_actual_encryption_key_size  = 0;
4913             }
4914             if (sm_conn->sm_actual_encryption_key_size == 0){
4915                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4916                 break;
4917             }
4918 
4919             // prepare key exchange, LTK is derived locally
4920             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4921                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4922 
4923             // skip receive if there are none
4924             if (sm_key_distribution_all_received()){
4925                 // distribute keys in run handles 'no keys to send'
4926                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4927             } else {
4928                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4929             }
4930             break;
4931 
4932         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4933             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4934                 sm_pdu_received_in_wrong_state(sm_conn);
4935                 break;
4936             }
4937 
4938             // store pairing request
4939             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4940 
4941             // validate encryption key size
4942             max_encryption_key_size = sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq);
4943             if ((max_encryption_key_size < 7) || (max_encryption_key_size > 16)){
4944                 sm_pairing_error(sm_conn, SM_REASON_INVALID_PARAMETERS);
4945                 break;
4946             }
4947             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(max_encryption_key_size);
4948             // SC Only mandates 128 bit key size
4949             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4950                 sm_conn->sm_actual_encryption_key_size  = 0;
4951             }
4952             if (sm_conn->sm_actual_encryption_key_size == 0){
4953                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4954                 break;
4955             }
4956             // trigger response
4957             if (sm_ctkd_from_classic(sm_conn)){
4958                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4959             } else {
4960                 sm_pairing_error(sm_conn, SM_REASON_CROSS_TRANSPORT_KEY_DERIVATION_NOT_ALLOWED);
4961             }
4962             break;
4963 
4964         case SM_BR_EDR_RECEIVE_KEYS:
4965             switch(sm_pdu_code){
4966                 case SM_CODE_IDENTITY_INFORMATION:
4967                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4968                     reverse_128(&packet[1], setup->sm_peer_irk);
4969                     break;
4970                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4971                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4972                     setup->sm_peer_addr_type = packet[1];
4973                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4974                     break;
4975                 case SM_CODE_SIGNING_INFORMATION:
4976                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4977                     reverse_128(&packet[1], setup->sm_peer_csrk);
4978                     break;
4979                 default:
4980                     // Unexpected PDU
4981                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4982                     break;
4983             }
4984 
4985             // all keys received
4986             if (sm_key_distribution_all_received()){
4987                 if (IS_RESPONDER(sm_conn->sm_role)){
4988                     // responder -> keys exchanged, derive LE LTK
4989                     sm_ctkd_start_from_br_edr(sm_conn);
4990                 } else {
4991                     // initiator -> send our keys if any
4992                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4993                 }
4994             }
4995             break;
4996 #endif
4997 
4998         default:
4999             // Unexpected PDU
5000             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
5001             sm_pdu_received_in_wrong_state(sm_conn);
5002             break;
5003     }
5004 
5005     // try to send next pdu
5006     sm_trigger_run();
5007 }
5008 
5009 static void sm_channel_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
5010 
5011     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
5012         sm_run();
5013     }
5014 
5015     uint8_t sm_pdu_code = sm_pdu_validate_and_get_opcode(packet_type, packet, size);
5016     if (sm_pdu_code == 0) return;
5017 
5018     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5019     if (!sm_conn) return;
5020 
5021     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
5022         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
5023         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
5024         sm_done_for_handle(con_handle);
5025         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
5026         return;
5027     }
5028 
5029     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
5030         uint8_t buffer[5];
5031         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
5032         buffer[1] = 3;
5033         little_endian_store_16(buffer, 2, con_handle);
5034         buffer[4] = packet[1];
5035         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
5036         return;
5037     }
5038 
5039     sm_pdu_handler(sm_conn, sm_pdu_code, packet);
5040 }
5041 
5042 // Security Manager Client API
5043 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
5044     sm_get_oob_data = get_oob_data_callback;
5045 }
5046 
5047 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)){
5048     sm_get_sc_oob_data = get_sc_oob_data_callback;
5049 }
5050 
5051 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)){
5052     sm_get_ltk_callback = get_ltk_callback;
5053 }
5054 
5055 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
5056     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
5057 }
5058 
5059 void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
5060     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
5061 }
5062 
5063 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
5064     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
5065 }
5066 
5067 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
5068 	sm_min_encryption_key_size = min_size;
5069 	sm_max_encryption_key_size = max_size;
5070 }
5071 
5072 void sm_set_authentication_requirements(uint8_t auth_req){
5073 #ifndef ENABLE_LE_SECURE_CONNECTIONS
5074     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
5075         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
5076         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
5077     }
5078 #endif
5079     sm_auth_req = auth_req;
5080 }
5081 
5082 void sm_set_io_capabilities(io_capability_t io_capability){
5083     sm_io_capabilities = io_capability;
5084 }
5085 
5086 #ifdef ENABLE_LE_PERIPHERAL
5087 void sm_set_request_security(bool enable){
5088     sm_slave_request_security = enable;
5089 }
5090 #endif
5091 
5092 void sm_set_er(sm_key_t er){
5093     (void)memcpy(sm_persistent_er, er, 16);
5094 }
5095 
5096 void sm_set_ir(sm_key_t ir){
5097     (void)memcpy(sm_persistent_ir, ir, 16);
5098 }
5099 
5100 // Testing support only
5101 void sm_test_set_irk(sm_key_t irk){
5102     (void)memcpy(sm_persistent_irk, irk, 16);
5103     dkg_state = DKG_CALC_DHK;
5104     test_use_fixed_local_irk = true;
5105 }
5106 
5107 void sm_test_use_fixed_local_csrk(void){
5108     test_use_fixed_local_csrk = true;
5109 }
5110 
5111 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5112 static void sm_ec_generated(void * arg){
5113     UNUSED(arg);
5114     ec_key_generation_state = EC_KEY_GENERATION_DONE;
5115     // trigger pairing if pending for ec key
5116     sm_trigger_run();
5117 }
5118 static void sm_ec_generate_new_key(void) {
5119     log_info("sm: generate new ec key");
5120 #ifdef ENABLE_LE_SECURE_CONNECTIONS_DEBUG_KEY
5121     // LE Secure Connections Debug Key
5122     const uint8_t debug_key_public[64] = {
5123         0x20, 0xb0, 0x03, 0xd2, 0xf2, 0x97, 0xbe, 0x2c, 0x5e, 0x2c, 0x83, 0xa7, 0xe9, 0xf9, 0xa5, 0xb9,
5124         0xef, 0xf4, 0x91, 0x11, 0xac, 0xf4, 0xfd, 0xdb, 0xcc, 0x03, 0x01, 0x48, 0x0e, 0x35, 0x9d, 0xe6,
5125         0xdc, 0x80, 0x9c, 0x49, 0x65, 0x2a, 0xeb, 0x6d, 0x63, 0x32, 0x9a, 0xbf, 0x5a, 0x52, 0x15, 0x5c,
5126         0x76, 0x63, 0x45, 0xc2, 0x8f, 0xed, 0x30, 0x24, 0x74, 0x1c, 0x8e, 0xd0, 0x15, 0x89, 0xd2, 0x8b
5127     };
5128     const uint8_t debug_key_private[32] = {
5129         0x3f, 0x49, 0xf6, 0xd4, 0xa3, 0xc5, 0x5f, 0x38, 0x74, 0xc9, 0xb3, 0xe3, 0xd2, 0x10, 0x3f, 0x50,
5130         0x4a, 0xff, 0x60, 0x7b, 0xeb, 0x40, 0xb7, 0x99, 0x58, 0x99, 0xb8, 0xa6, 0xcd, 0x3c, 0x1a, 0xbd
5131     };
5132     if (sm_sc_debug_keys_enabled) {
5133         memcpy(ec_q, debug_key_public, 64);
5134         btstack_crypto_ecc_p256_set_key(debug_key_public, debug_key_private);
5135         ec_key_generation_state = EC_KEY_GENERATION_DONE;
5136     } else
5137 #endif
5138     {
5139         ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
5140         btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
5141     }
5142 }
5143 #endif
5144 
5145 #ifdef ENABLE_TESTING_SUPPORT
5146 void sm_test_set_pairing_failure(int reason){
5147     test_pairing_failure = reason;
5148 }
5149 #endif
5150 
5151 static void sm_state_reset(void) {
5152 #ifdef USE_CMAC_ENGINE
5153     sm_cmac_active  = 0;
5154 #endif
5155     dkg_state = DKG_W4_WORKING;
5156     rau_state = RAU_IDLE;
5157     sm_aes128_state = SM_AES128_IDLE;
5158     sm_address_resolution_test = -1;    // no private address to resolve yet
5159     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
5160     sm_address_resolution_general_queue = NULL;
5161     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
5162     sm_persistent_keys_random_active = false;
5163 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5164     ec_key_generation_state = EC_KEY_GENERATION_IDLE;
5165 #endif
5166 }
5167 
5168 void sm_init(void){
5169 
5170     if (sm_initialized) return;
5171 
5172     // set default ER and IR values (should be unique - set by app or sm later using TLV)
5173     sm_er_ir_set_default();
5174 
5175     // defaults
5176     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
5177                                        | SM_STK_GENERATION_METHOD_OOB
5178                                        | SM_STK_GENERATION_METHOD_PASSKEY
5179                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
5180 
5181     sm_max_encryption_key_size = 16;
5182     sm_min_encryption_key_size = 7;
5183 
5184     sm_fixed_passkey_in_display_role = 0xffffffffU;
5185     sm_reconstruct_ltk_without_le_device_db_entry = true;
5186 
5187     gap_random_adress_update_period = 15 * 60 * 1000L;
5188 
5189     test_use_fixed_local_csrk = false;
5190 
5191     // other
5192     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
5193 
5194     // register for HCI Events
5195     hci_event_callback_registration.callback = &sm_event_packet_handler;
5196     hci_add_event_handler(&hci_event_callback_registration);
5197 
5198 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
5199     // register for L2CAP events
5200     l2cap_event_callback_registration.callback = &sm_event_packet_handler;
5201     l2cap_add_event_handler(&l2cap_event_callback_registration);
5202 #endif
5203 
5204     //
5205     btstack_crypto_init();
5206 
5207     // init le_device_db
5208     le_device_db_init();
5209 
5210     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
5211     l2cap_register_fixed_channel(sm_channel_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
5212 #ifdef ENABLE_CLASSIC
5213     l2cap_register_fixed_channel(sm_channel_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER);
5214 #endif
5215 
5216     // state
5217     sm_state_reset();
5218 
5219     sm_initialized = true;
5220 }
5221 
5222 void sm_deinit(void){
5223     sm_initialized = false;
5224     btstack_run_loop_remove_timer(&sm_run_timer);
5225 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && defined (ENABLE_LE_SECURE_CONNECTION_DEBUG_KEY)
5226     sm_sc_debug_keys_enabled = false;
5227 #endif
5228 }
5229 
5230 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
5231     sm_fixed_passkey_in_display_role = passkey;
5232 }
5233 
5234 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
5235     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
5236 }
5237 
5238 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
5239     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
5240     if (!hci_con) return NULL;
5241     return &hci_con->sm_connection;
5242 }
5243 
5244 static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk){
5245     hci_connection_t * hci_con = hci_connection_for_handle(connection->sm_handle);
5246     btstack_assert(hci_con != NULL);
5247     memcpy(hci_con->link_key, ltk, 16);
5248     hci_con->link_key_type = COMBINATION_KEY;
5249 }
5250 
5251 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
5252 static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
5253     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
5254     if (!hci_con) return NULL;
5255     return &hci_con->sm_connection;
5256 }
5257 #endif
5258 
5259 // @deprecated: map onto sm_request_pairing
5260 void sm_send_security_request(hci_con_handle_t con_handle){
5261     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5262     if (!sm_conn) return;
5263     if (!IS_RESPONDER(sm_conn->sm_role)) return;
5264     sm_request_pairing(con_handle);
5265 }
5266 
5267 // request pairing
5268 void sm_request_pairing(hci_con_handle_t con_handle){
5269     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5270     if (!sm_conn) return;     // wrong connection
5271 
5272     bool have_ltk;
5273     uint8_t ltk[16];
5274     bool auth_required;
5275     int authenticated;
5276     bool trigger_reencryption;
5277     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
5278     if (IS_RESPONDER(sm_conn->sm_role)){
5279         switch (sm_conn->sm_engine_state){
5280             case SM_GENERAL_IDLE:
5281             case SM_RESPONDER_IDLE:
5282                 switch (sm_conn->sm_irk_lookup_state){
5283                     case IRK_LOOKUP_SUCCEEDED:
5284                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
5285                         have_ltk = !sm_is_null_key(ltk);
5286                         log_info("have ltk %u", have_ltk);
5287                         if (have_ltk){
5288                             sm_conn->sm_pairing_requested = true;
5289                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
5290                             sm_reencryption_started(sm_conn);
5291                             break;
5292                         }
5293                         /* fall through */
5294 
5295                     case IRK_LOOKUP_FAILED:
5296                         sm_conn->sm_pairing_requested = true;
5297                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
5298                         sm_pairing_started(sm_conn);
5299                         break;
5300                     default:
5301                         log_info("irk lookup pending");
5302                         sm_conn->sm_pairing_requested = true;
5303                         break;
5304                 }
5305                 break;
5306             default:
5307                 break;
5308         }
5309     } else {
5310         // used as a trigger to start central/master/initiator security procedures
5311         switch (sm_conn->sm_engine_state){
5312             case SM_INITIATOR_CONNECTED:
5313                 switch (sm_conn->sm_irk_lookup_state){
5314                     case IRK_LOOKUP_SUCCEEDED:
5315                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, &authenticated, NULL, NULL);
5316                         have_ltk = !sm_is_null_key(ltk);
5317                         auth_required = sm_auth_req & SM_AUTHREQ_MITM_PROTECTION;
5318                         // re-encrypt is sufficient if we have ltk and that is either already authenticated or we don't require authentication
5319                         trigger_reencryption = have_ltk && ((authenticated != 0) || (auth_required == false));
5320                         log_info("have ltk %u, authenticated %u, auth required %u => reencrypt %u", have_ltk, authenticated, auth_required, trigger_reencryption);
5321                         if (trigger_reencryption){
5322                             sm_conn->sm_pairing_requested = true;
5323                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
5324                             break;
5325                         }
5326                         /* fall through */
5327 
5328                     case IRK_LOOKUP_FAILED:
5329                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
5330                         break;
5331                     default:
5332                         log_info("irk lookup pending");
5333                         sm_conn->sm_pairing_requested = true;
5334                         break;
5335                 }
5336                 break;
5337             case SM_GENERAL_REENCRYPTION_FAILED:
5338                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
5339                 break;
5340             case SM_GENERAL_IDLE:
5341                 sm_conn->sm_pairing_requested = true;
5342                 break;
5343             default:
5344                 break;
5345         }
5346     }
5347     sm_trigger_run();
5348 }
5349 
5350 // called by client app on authorization request
5351 void sm_authorization_decline(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_DECLINED;
5355     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0);
5356 }
5357 
5358 void sm_authorization_grant(hci_con_handle_t con_handle){
5359     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5360     if (!sm_conn) return;     // wrong connection
5361     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
5362     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1);
5363 }
5364 
5365 // GAP Bonding API
5366 
5367 void sm_bonding_decline(hci_con_handle_t con_handle){
5368     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5369     if (!sm_conn) return;     // wrong connection
5370     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
5371     log_info("decline, state %u", sm_conn->sm_engine_state);
5372     switch(sm_conn->sm_engine_state){
5373 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5374         case SM_SC_W4_USER_RESPONSE:
5375         case SM_SC_W4_CONFIRMATION:
5376         case SM_SC_W4_PUBLIC_KEY_COMMAND:
5377 #endif
5378         case SM_PH1_W4_USER_RESPONSE:
5379             switch (setup->sm_stk_generation_method){
5380                 case PK_RESP_INPUT:
5381                 case PK_INIT_INPUT:
5382                 case PK_BOTH_INPUT:
5383                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
5384                     break;
5385                 case NUMERIC_COMPARISON:
5386                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
5387                     break;
5388                 case JUST_WORKS:
5389                 case OOB:
5390                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
5391                     break;
5392                 default:
5393                     btstack_assert(false);
5394                     break;
5395             }
5396             break;
5397         default:
5398             break;
5399     }
5400     sm_trigger_run();
5401 }
5402 
5403 void sm_just_works_confirm(hci_con_handle_t con_handle){
5404     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5405     if (!sm_conn) return;     // wrong connection
5406     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
5407     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5408         if (setup->sm_use_secure_connections){
5409             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
5410         } else {
5411             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);
5412         }
5413     }
5414 
5415 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5416     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
5417         sm_sc_prepare_dhkey_check(sm_conn);
5418     }
5419 #endif
5420 
5421     sm_trigger_run();
5422 }
5423 
5424 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
5425     // for now, it's the same
5426     sm_just_works_confirm(con_handle);
5427 }
5428 
5429 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
5430     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5431     if (!sm_conn) return;     // wrong connection
5432     sm_reset_tk();
5433     big_endian_store_32(setup->sm_tk, 12, passkey);
5434     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
5435     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5436         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);
5437     }
5438 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5439     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
5440     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
5441     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
5442         sm_sc_start_calculating_local_confirm(sm_conn);
5443     }
5444 #endif
5445     sm_trigger_run();
5446 }
5447 
5448 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
5449     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5450     if (!sm_conn) return;     // wrong connection
5451     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5452     uint8_t num_actions = setup->sm_keypress_notification >> 5;
5453     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5454     switch (action){
5455         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5456         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
5457             flags |= (1u << action);
5458             break;
5459         case SM_KEYPRESS_PASSKEY_CLEARED:
5460             // clear counter, keypress & erased flags + set passkey cleared
5461             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5462             break;
5463         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
5464             if ((flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)) != 0u){
5465                 // erase actions queued
5466                 num_actions--;
5467                 if (num_actions == 0u){
5468                     // clear counter, keypress & erased flags
5469                     flags &= 0x19u;
5470                 }
5471                 break;
5472             }
5473             num_actions++;
5474             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5475             break;
5476         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
5477             if ((flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)) != 0u){
5478                 // enter actions queued
5479                 num_actions--;
5480                 if (num_actions == 0u){
5481                     // clear counter, keypress & erased flags
5482                     flags &= 0x19u;
5483                 }
5484                 break;
5485             }
5486             num_actions++;
5487             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5488             break;
5489         default:
5490             break;
5491     }
5492     setup->sm_keypress_notification = (num_actions << 5) | flags;
5493     sm_trigger_run();
5494 }
5495 
5496 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5497 static void sm_handle_random_result_oob(void * arg){
5498     UNUSED(arg);
5499     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
5500     sm_trigger_run();
5501 }
5502 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
5503 
5504     static btstack_crypto_random_t   sm_crypto_random_oob_request;
5505 
5506     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5507     sm_sc_oob_callback = callback;
5508     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5509     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5510     return 0;
5511 }
5512 #endif
5513 
5514 /**
5515  * @brief Get Identity Resolving state
5516  * @param con_handle
5517  * @return irk_lookup_state_t
5518  */
5519 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5520     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5521     if (!sm_conn) return IRK_LOOKUP_IDLE;
5522     return sm_conn->sm_irk_lookup_state;
5523 }
5524 
5525 /**
5526  * @brief Identify device in LE Device DB
5527  * @param handle
5528  * @return index from le_device_db or -1 if not found/identified
5529  */
5530 int sm_le_device_index(hci_con_handle_t con_handle ){
5531     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5532     if (!sm_conn) return -1;
5533     return sm_conn->sm_le_db_index;
5534 }
5535 
5536 uint8_t sm_get_ltk(hci_con_handle_t con_handle, sm_key_t ltk){
5537     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5538     if (hci_connection == NULL){
5539         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5540     }
5541     if (hci_connection->link_key_type == INVALID_LINK_KEY){
5542         return ERROR_CODE_PIN_OR_KEY_MISSING;
5543     }
5544     memcpy(ltk, hci_connection->link_key, 16);
5545     return ERROR_CODE_SUCCESS;
5546 }
5547 
5548 static int gap_random_address_type_requires_updates(void){
5549     switch (gap_random_adress_type){
5550         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5551         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
5552             return 0;
5553         default:
5554             return 1;
5555     }
5556 }
5557 
5558 static uint8_t own_address_type(void){
5559     switch (gap_random_adress_type){
5560         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5561             return BD_ADDR_TYPE_LE_PUBLIC;
5562         default:
5563             return BD_ADDR_TYPE_LE_RANDOM;
5564     }
5565 }
5566 
5567 // GAP LE API
5568 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
5569     gap_random_address_update_stop();
5570     gap_random_adress_type = random_address_type;
5571     hci_le_set_own_address_type(own_address_type());
5572     if (!gap_random_address_type_requires_updates()) return;
5573     gap_random_address_update_start();
5574     gap_random_address_trigger();
5575 }
5576 
5577 gap_random_address_type_t gap_random_address_get_mode(void){
5578     return gap_random_adress_type;
5579 }
5580 
5581 void gap_random_address_set_update_period(int period_ms){
5582     gap_random_adress_update_period = period_ms;
5583     if (!gap_random_address_type_requires_updates()) return;
5584     gap_random_address_update_stop();
5585     gap_random_address_update_start();
5586 }
5587 
5588 void gap_random_address_set(const bd_addr_t addr){
5589     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
5590     (void)memcpy(sm_random_address, addr, 6);
5591     // assert msb bits are set to '11'
5592     sm_random_address[0] |= 0xc0;
5593     hci_le_random_address_set(sm_random_address);
5594 }
5595 
5596 #ifdef ENABLE_LE_PERIPHERAL
5597 /*
5598  * @brief Set Advertisement Paramters
5599  * @param adv_int_min
5600  * @param adv_int_max
5601  * @param adv_type
5602  * @param direct_address_type
5603  * @param direct_address
5604  * @param channel_map
5605  * @param filter_policy
5606  *
5607  * @note own_address_type is used from gap_random_address_set_mode
5608  */
5609 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
5610     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5611     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
5612         direct_address_typ, direct_address, channel_map, filter_policy);
5613 }
5614 #endif
5615 
5616 bool gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5617     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5618      // wrong connection
5619     if (!sm_conn) return false;
5620     // already encrypted
5621     if (sm_conn->sm_connection_encrypted) return false;
5622     // irk status?
5623     switch(sm_conn->sm_irk_lookup_state){
5624         case IRK_LOOKUP_FAILED:
5625             // done, cannot setup encryption
5626             return false;
5627         case IRK_LOOKUP_SUCCEEDED:
5628             break;
5629         default:
5630             // IR Lookup pending
5631             return true;
5632     }
5633     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5634     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return false;
5635     if (sm_conn->sm_role != 0){
5636         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5637     } else {
5638         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5639     }
5640 }
5641 
5642 void sm_set_secure_connections_only_mode(bool enable){
5643 #ifdef ENABLE_LE_SECURE_CONNECTIONS
5644     sm_sc_only_mode = enable;
5645 #else
5646     // SC Only mode not possible without support for SC
5647     btstack_assert(enable == false);
5648 #endif
5649 }
5650 
5651 #if defined(ENABLE_LE_SECURE_CONNECTIONS) && defined (ENABLE_LE_SECURE_CONNECTION_DEBUG_KEY)
5652 void sm_test_enable_secure_connections_debug_keys(void) {
5653     log_info("Enable LE Secure Connection Debug Keys for testing");
5654     sm_sc_debug_keys_enabled = true;
5655     // set debug key
5656     sm_ec_generate_new_key();
5657 }
5658 #endif
5659 
5660 const uint8_t * gap_get_persistent_irk(void){
5661     return sm_persistent_irk;
5662 }
5663 
5664 void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
5665     int index = sm_le_device_db_index_lookup(address_type, address);
5666     if (index >= 0){
5667         sm_remove_le_device_db_entry(index);
5668     }
5669 }
5670