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