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