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