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