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