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