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