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