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