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