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