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