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