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