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