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