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