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