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