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