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