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