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