xref: /btstack/src/ble/sm.c (revision c9921182ab4b1f83e3e5c671446dca5ffdf45b90)
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         }
1309 
1310         if (le_db_index >= 0){
1311 
1312             sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index);
1313             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
1314 
1315 #ifdef ENABLE_LE_SIGNED_WRITE
1316             // store local CSRK
1317             setup->sm_le_device_index = le_db_index;
1318             if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
1319                 log_info("sm: store local CSRK");
1320                 le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
1321                 le_device_db_local_counter_set(le_db_index, 0);
1322             }
1323 
1324             // store remote CSRK
1325             if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
1326                 log_info("sm: store remote CSRK");
1327                 le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
1328                 le_device_db_remote_counter_set(le_db_index, 0);
1329             }
1330 #endif
1331             // store encryption information for secure connections: LTK generated by ECDH
1332             if (setup->sm_use_secure_connections){
1333                 log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
1334                 uint8_t zero_rand[8];
1335                 memset(zero_rand, 0, 8);
1336                 le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
1337                     sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
1338             }
1339 
1340             // store encryption information for legacy pairing: peer LTK, EDIV, RAND
1341             else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
1342                    && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1343                 log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
1344                 le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
1345                     sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
1346 
1347             }
1348         }
1349     } else {
1350         log_info("Ignoring received keys, bonding not enabled");
1351     }
1352 
1353     // keep le_db_index
1354     sm_conn->sm_le_db_index = le_db_index;
1355 }
1356 
1357 static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1358     setup->sm_pairing_failed_reason = reason;
1359     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1360 }
1361 
1362 static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1363     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1364 }
1365 
1366 #ifdef ENABLE_LE_SECURE_CONNECTIONS
1367 
1368 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1369 static int sm_passkey_used(stk_generation_method_t method);
1370 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1371 
1372 static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1373     if (setup->sm_stk_generation_method == OOB){
1374         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1375     } else {
1376         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);
1377     }
1378 }
1379 
1380 static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
1381     if (IS_RESPONDER(sm_conn->sm_role)){
1382         // Responder
1383         if (setup->sm_stk_generation_method == OOB){
1384             // generate Nb
1385             log_info("Generate Nb");
1386             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);
1387         } else {
1388             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
1389         }
1390     } else {
1391         // Initiator role
1392         switch (setup->sm_stk_generation_method){
1393             case JUST_WORKS:
1394                 sm_sc_prepare_dhkey_check(sm_conn);
1395                 break;
1396 
1397             case NUMERIC_COMPARISON:
1398                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1399                 break;
1400             case PK_INIT_INPUT:
1401             case PK_RESP_INPUT:
1402             case PK_BOTH_INPUT:
1403                 if (setup->sm_passkey_bit < 20u) {
1404                     sm_sc_start_calculating_local_confirm(sm_conn);
1405                 } else {
1406                     sm_sc_prepare_dhkey_check(sm_conn);
1407                 }
1408                 break;
1409             case OOB:
1410                 sm_sc_prepare_dhkey_check(sm_conn);
1411                 break;
1412         }
1413     }
1414 }
1415 
1416 static void sm_sc_cmac_done(uint8_t * hash){
1417     log_info("sm_sc_cmac_done: ");
1418     log_info_hexdump(hash, 16);
1419 
1420     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1421         sm_sc_oob_state = SM_SC_OOB_IDLE;
1422         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1423         return;
1424     }
1425 
1426     sm_connection_t * sm_conn = sm_cmac_connection;
1427     sm_cmac_connection = NULL;
1428 #ifdef ENABLE_CLASSIC
1429     link_key_type_t link_key_type;
1430 #endif
1431 
1432     switch (sm_conn->sm_engine_state){
1433         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
1434             (void)memcpy(setup->sm_local_confirm, hash, 16);
1435             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1436             break;
1437         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1438             // check
1439             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1440                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1441                 break;
1442             }
1443             sm_sc_state_after_receiving_random(sm_conn);
1444             break;
1445         case SM_SC_W4_CALCULATE_G2: {
1446             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1447             big_endian_store_32(setup->sm_tk, 12, vab);
1448             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1449             sm_trigger_user_response(sm_conn);
1450             break;
1451         }
1452         case SM_SC_W4_CALCULATE_F5_SALT:
1453             (void)memcpy(setup->sm_t, hash, 16);
1454             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
1455             break;
1456         case SM_SC_W4_CALCULATE_F5_MACKEY:
1457             (void)memcpy(setup->sm_mackey, hash, 16);
1458             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
1459             break;
1460         case SM_SC_W4_CALCULATE_F5_LTK:
1461             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1462             // Errata Service Release to the Bluetooth Specification: ESR09
1463             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1464             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
1465             (void)memcpy(setup->sm_ltk, hash, 16);
1466             (void)memcpy(setup->sm_local_ltk, hash, 16);
1467             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1468             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1469             break;
1470         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
1471             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
1472             if (IS_RESPONDER(sm_conn->sm_role)){
1473                 // responder
1474                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1475                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1476                 } else {
1477                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1478                 }
1479             } else {
1480                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1481             }
1482             break;
1483         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1484             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1485                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1486                 break;
1487             }
1488             if (IS_RESPONDER(sm_conn->sm_role)){
1489                 // responder
1490                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1491             } else {
1492                 // initiator
1493                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1494             }
1495             break;
1496         case SM_SC_W4_CALCULATE_H6_ILK:
1497             (void)memcpy(setup->sm_t, hash, 16);
1498             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_H6_BR_EDR_LINK_KEY;
1499             break;
1500         case SM_SC_W4_CALCULATE_H6_BR_EDR_LINK_KEY:
1501 #ifdef ENABLE_CLASSIC
1502             reverse_128(hash, setup->sm_t);
1503             link_key_type = sm_conn->sm_connection_authenticated ?
1504                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1505             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
1506             if (IS_RESPONDER(sm_conn->sm_role)){
1507                 gap_store_link_key_for_bd_addr(setup->sm_m_address, setup->sm_t, link_key_type);
1508             } else {
1509                 gap_store_link_key_for_bd_addr(setup->sm_s_address, setup->sm_t, link_key_type);
1510             }
1511 #endif
1512             if (IS_RESPONDER(sm_conn->sm_role)){
1513                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
1514             } else {
1515                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
1516             }
1517             sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
1518             sm_done_for_handle(sm_conn->sm_handle);
1519             break;
1520         default:
1521             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1522             break;
1523     }
1524     sm_run();
1525 }
1526 
1527 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){
1528     const uint16_t message_len = 65;
1529     sm_cmac_connection = sm_conn;
1530     (void)memcpy(sm_cmac_sc_buffer, u, 32);
1531     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1532     sm_cmac_sc_buffer[64] = z;
1533     log_info("f4 key");
1534     log_info_hexdump(x, 16);
1535     log_info("f4 message");
1536     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1537     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1538 }
1539 
1540 static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
1541 static const uint8_t f5_length[] = { 0x01, 0x00};
1542 
1543 static void f5_calculate_salt(sm_connection_t * sm_conn){
1544 
1545     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
1546 
1547     log_info("f5_calculate_salt");
1548     // calculate salt for f5
1549     const uint16_t message_len = 32;
1550     sm_cmac_connection = sm_conn;
1551     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1552     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1553 }
1554 
1555 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){
1556     const uint16_t message_len = 53;
1557     sm_cmac_connection = sm_conn;
1558 
1559     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
1560     sm_cmac_sc_buffer[0] = 0;
1561     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
1562     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
1563     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
1564     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
1565     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
1566     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
1567     log_info("f5 key");
1568     log_info_hexdump(t, 16);
1569     log_info("f5 message for MacKey");
1570     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1571     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1572 }
1573 
1574 static void f5_calculate_mackey(sm_connection_t * sm_conn){
1575     sm_key56_t bd_addr_master, bd_addr_slave;
1576     bd_addr_master[0] =  setup->sm_m_addr_type;
1577     bd_addr_slave[0]  =  setup->sm_s_addr_type;
1578     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
1579     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1580     if (IS_RESPONDER(sm_conn->sm_role)){
1581         // responder
1582         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
1583     } else {
1584         // initiator
1585         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
1586     }
1587 }
1588 
1589 // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
1590 static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
1591     const uint16_t message_len = 53;
1592     sm_cmac_connection = sm_conn;
1593     sm_cmac_sc_buffer[0] = 1;
1594     // 1..52 setup before
1595     log_info("f5 key");
1596     log_info_hexdump(t, 16);
1597     log_info("f5 message for LTK");
1598     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1599     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1600 }
1601 
1602 static void f5_calculate_ltk(sm_connection_t * sm_conn){
1603     f5_ltk(sm_conn, setup->sm_t);
1604 }
1605 
1606 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){
1607     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
1608     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
1609     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
1610     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
1611     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
1612     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
1613 }
1614 
1615 static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
1616     const uint16_t message_len = 65;
1617     sm_cmac_connection = sm_conn;
1618     log_info("f6 key");
1619     log_info_hexdump(w, 16);
1620     log_info("f6 message");
1621     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1622     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1623 }
1624 
1625 // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1626 // - U is 256 bits
1627 // - V is 256 bits
1628 // - X is 128 bits
1629 // - Y is 128 bits
1630 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){
1631     const uint16_t message_len = 80;
1632     sm_cmac_connection = sm_conn;
1633     (void)memcpy(sm_cmac_sc_buffer, u, 32);
1634     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1635     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1636     log_info("g2 key");
1637     log_info_hexdump(x, 16);
1638     log_info("g2 message");
1639     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1640     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1641 }
1642 
1643 static void g2_calculate(sm_connection_t * sm_conn) {
1644     // calc Va if numeric comparison
1645     if (IS_RESPONDER(sm_conn->sm_role)){
1646         // responder
1647         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1648     } else {
1649         // initiator
1650         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1651     }
1652 }
1653 
1654 static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
1655     uint8_t z = 0;
1656     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1657         // some form of passkey
1658         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1659         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
1660         setup->sm_passkey_bit++;
1661     }
1662     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
1663 }
1664 
1665 static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1666     // OOB
1667     if (setup->sm_stk_generation_method == OOB){
1668         if (IS_RESPONDER(sm_conn->sm_role)){
1669             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
1670         } else {
1671             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
1672         }
1673         return;
1674     }
1675 
1676     uint8_t z = 0;
1677     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1678         // some form of passkey
1679         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1680         // sm_passkey_bit was increased before sending confirm value
1681         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1682     }
1683     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1684 }
1685 
1686 static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1687     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
1688 
1689     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
1690         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1691         return;
1692     } else {
1693         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
1694     }
1695 }
1696 
1697 static void sm_sc_dhkey_calculated(void * arg){
1698     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1699     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1700     if (sm_conn == NULL) return;
1701 
1702     log_info("dhkey");
1703     log_info_hexdump(&setup->sm_dhkey[0], 32);
1704     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1705     // trigger next step
1706     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1707         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1708     }
1709     sm_run();
1710 }
1711 
1712 static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1713     // calculate DHKCheck
1714     sm_key56_t bd_addr_master, bd_addr_slave;
1715     bd_addr_master[0] =  setup->sm_m_addr_type;
1716     bd_addr_slave[0]  =  setup->sm_s_addr_type;
1717     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
1718     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1719     uint8_t iocap_a[3];
1720     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1721     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1722     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1723     uint8_t iocap_b[3];
1724     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1725     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1726     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
1727     if (IS_RESPONDER(sm_conn->sm_role)){
1728         // responder
1729         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
1730         f6_engine(sm_conn, setup->sm_mackey);
1731     } else {
1732         // initiator
1733         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
1734         f6_engine(sm_conn, setup->sm_mackey);
1735     }
1736 }
1737 
1738 static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1739     // validate E = f6()
1740     sm_key56_t bd_addr_master, bd_addr_slave;
1741     bd_addr_master[0] =  setup->sm_m_addr_type;
1742     bd_addr_slave[0]  =  setup->sm_s_addr_type;
1743     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
1744     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1745 
1746     uint8_t iocap_a[3];
1747     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1748     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1749     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1750     uint8_t iocap_b[3];
1751     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1752     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1753     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
1754     if (IS_RESPONDER(sm_conn->sm_role)){
1755         // responder
1756         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
1757         f6_engine(sm_conn, setup->sm_mackey);
1758     } else {
1759         // initiator
1760         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
1761         f6_engine(sm_conn, setup->sm_mackey);
1762     }
1763 }
1764 
1765 
1766 //
1767 // Link Key Conversion Function h6
1768 //
1769 // h6(W, keyID) = AES-CMACW(keyID)
1770 // - W is 128 bits
1771 // - keyID is 32 bits
1772 static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
1773     const uint16_t message_len = 4;
1774     sm_cmac_connection = sm_conn;
1775     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
1776     log_info("h6 key");
1777     log_info_hexdump(w, 16);
1778     log_info("h6 message");
1779     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1780     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1781 }
1782 
1783 // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1784 // Errata Service Release to the Bluetooth Specification: ESR09
1785 //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1786 //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
1787 static void h6_calculate_ilk(sm_connection_t * sm_conn){
1788     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
1789 }
1790 
1791 static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
1792     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
1793 }
1794 
1795 #endif
1796 
1797 // key management legacy connections:
1798 // - potentially two different LTKs based on direction. each device stores LTK provided by peer
1799 // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
1800 // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
1801 // - responder  reconnects: responder uses LTK receveived from master
1802 
1803 // key management secure connections:
1804 // - both devices store same LTK from ECDH key exchange.
1805 
1806 #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
1807 static void sm_load_security_info(sm_connection_t * sm_connection){
1808     int encryption_key_size;
1809     int authenticated;
1810     int authorized;
1811     int secure_connection;
1812 
1813     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
1814     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
1815                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
1816     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);
1817     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
1818     sm_connection->sm_connection_authenticated = authenticated;
1819     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
1820     sm_connection->sm_connection_sc = secure_connection;
1821 }
1822 #endif
1823 
1824 #ifdef ENABLE_LE_PERIPHERAL
1825 static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
1826     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
1827     setup->sm_local_ediv = sm_connection->sm_local_ediv;
1828     // re-establish used key encryption size
1829     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
1830     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
1831     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
1832     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
1833     // Legacy paring -> not SC
1834     sm_connection->sm_connection_sc = 0;
1835     log_info("sm: received ltk request with key size %u, authenticated %u",
1836             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
1837     sm_connection->sm_engine_state = SM_RESPONDER_PH4_Y_GET_ENC;
1838     sm_run();
1839 }
1840 #endif
1841 
1842 // distributed key generation
1843 static bool sm_run_dpkg(void){
1844     switch (dkg_state){
1845         case DKG_CALC_IRK:
1846             // already busy?
1847             if (sm_aes128_state == SM_AES128_IDLE) {
1848                 log_info("DKG_CALC_IRK started");
1849                 // IRK = d1(IR, 1, 0)
1850                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
1851                 sm_aes128_state = SM_AES128_ACTIVE;
1852                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_irk, sm_handle_encryption_result_dkg_irk, NULL);
1853                 return true;
1854             }
1855             break;
1856         case DKG_CALC_DHK:
1857             // already busy?
1858             if (sm_aes128_state == SM_AES128_IDLE) {
1859                 log_info("DKG_CALC_DHK started");
1860                 // DHK = d1(IR, 3, 0)
1861                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
1862                 sm_aes128_state = SM_AES128_ACTIVE;
1863                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_dhk, sm_handle_encryption_result_dkg_dhk, NULL);
1864                 return true;
1865             }
1866             break;
1867         default:
1868             break;
1869     }
1870     return false;
1871 }
1872 
1873 // random address updates
1874 static bool sm_run_rau(void){
1875     switch (rau_state){
1876         case RAU_GET_RANDOM:
1877             rau_state = RAU_W4_RANDOM;
1878             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
1879             return true;
1880         case RAU_GET_ENC:
1881             // already busy?
1882             if (sm_aes128_state == SM_AES128_IDLE) {
1883                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
1884                 sm_aes128_state = SM_AES128_ACTIVE;
1885                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
1886                 return true;
1887             }
1888             break;
1889         case RAU_SET_ADDRESS:
1890             log_info("New random address: %s", bd_addr_to_str(sm_random_address));
1891             rau_state = RAU_IDLE;
1892             hci_send_cmd(&hci_le_set_random_address, sm_random_address);
1893             return true;
1894         default:
1895             break;
1896     }
1897     return false;
1898 }
1899 
1900 // CSRK Lookup
1901 static bool sm_run_csrk(void){
1902     btstack_linked_list_iterator_t it;
1903 
1904     // -- if csrk lookup ready, find connection that require csrk lookup
1905     if (sm_address_resolution_idle()){
1906         hci_connections_get_iterator(&it);
1907         while(btstack_linked_list_iterator_has_next(&it)){
1908             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1909             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
1910             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
1911                 // and start lookup
1912                 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);
1913                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
1914                 break;
1915             }
1916         }
1917     }
1918 
1919     // -- if csrk lookup ready, resolved addresses for received addresses
1920     if (sm_address_resolution_idle()) {
1921         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
1922             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
1923             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
1924             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
1925             btstack_memory_sm_lookup_entry_free(entry);
1926         }
1927     }
1928 
1929     // -- Continue with CSRK device lookup by public or resolvable private address
1930     if (!sm_address_resolution_idle()){
1931         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
1932         while (sm_address_resolution_test < le_device_db_max_count()){
1933             int addr_type = BD_ADDR_TYPE_UNKNOWN;
1934             bd_addr_t addr;
1935             sm_key_t irk;
1936             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
1937             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
1938 
1939             // skip unused entries
1940             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
1941                 sm_address_resolution_test++;
1942                 continue;
1943             }
1944 
1945             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
1946                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
1947                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCEEDED);
1948                 break;
1949             }
1950 
1951             // if connection type is public, it must be a different one
1952             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
1953                 sm_address_resolution_test++;
1954                 continue;
1955             }
1956 
1957             if (sm_aes128_state == SM_AES128_ACTIVE) break;
1958 
1959             log_info("LE Device Lookup: calculate AH");
1960             log_info_key("IRK", irk);
1961 
1962             (void)memcpy(sm_aes128_key, irk, 16);
1963             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
1964             sm_address_resolution_ah_calculation_active = 1;
1965             sm_aes128_state = SM_AES128_ACTIVE;
1966             btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL);
1967             return true;
1968         }
1969 
1970         if (sm_address_resolution_test >= le_device_db_max_count()){
1971             log_info("LE Device Lookup: not found");
1972             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
1973         }
1974     }
1975     return false;
1976 }
1977 
1978 // SC OOB
1979 static bool sm_run_oob(void){
1980 #ifdef ENABLE_LE_SECURE_CONNECTIONS
1981     switch (sm_sc_oob_state){
1982         case SM_SC_OOB_W2_CALC_CONFIRM:
1983             if (!sm_cmac_ready()) break;
1984             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
1985             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
1986             return true;
1987         default:
1988             break;
1989     }
1990 #endif
1991     return false;
1992 }
1993 
1994 // handle basic actions that don't requires the full context
1995 static bool sm_run_basic(void){
1996     btstack_linked_list_iterator_t it;
1997     hci_connections_get_iterator(&it);
1998     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
1999         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2000         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
2001         switch(sm_connection->sm_engine_state){
2002             // responder side
2003             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
2004                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
2005                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2006                 return true;
2007 
2008 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2009             case SM_SC_RECEIVED_LTK_REQUEST:
2010                 switch (sm_connection->sm_irk_lookup_state){
2011                     case IRK_LOOKUP_FAILED:
2012                         log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Failed)");
2013                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
2014                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2015                         return true;
2016                     default:
2017                         break;
2018                 }
2019                 break;
2020 #endif
2021             default:
2022                 break;
2023         }
2024     }
2025     return false;
2026 }
2027 
2028 static void sm_run_activate_connection(void){
2029     // Find connections that requires setup context and make active if no other is locked
2030     btstack_linked_list_iterator_t it;
2031     hci_connections_get_iterator(&it);
2032     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2033         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2034         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
2035         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
2036         int done = 1;
2037         int err;
2038         UNUSED(err);
2039 
2040 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2041         // assert ec key is ready
2042         if ((sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2043             ||  (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)){
2044             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
2045                 sm_ec_generate_new_key();
2046             }
2047             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
2048                 continue;
2049             }
2050         }
2051 #endif
2052 
2053         switch (sm_connection->sm_engine_state) {
2054 #ifdef ENABLE_LE_PERIPHERAL
2055             case SM_RESPONDER_SEND_SECURITY_REQUEST:
2056                 // send packet if possible,
2057                 if (l2cap_can_send_fixed_channel_packet_now(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)){
2058                     const uint8_t buffer[2] = { SM_CODE_SECURITY_REQUEST, sm_auth_req};
2059                     sm_connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2060                     l2cap_send_connectionless(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2061                 } else {
2062                     l2cap_request_can_send_fix_channel_now_event(sm_connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2063                 }
2064                 // don't lock sxetup context yet
2065                 done = 0;
2066                 break;
2067             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2068                 sm_reset_setup();
2069                 sm_init_setup(sm_connection);
2070                 // recover pairing request
2071                 (void)memcpy(&setup->sm_m_preq,
2072                              &sm_connection->sm_m_preq,
2073                              sizeof(sm_pairing_packet_t));
2074                 err = sm_stk_generation_init(sm_connection);
2075 
2076 #ifdef ENABLE_TESTING_SUPPORT
2077             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
2078                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2079                         err = test_pairing_failure;
2080                     }
2081 #endif
2082                 if (err){
2083                     setup->sm_pairing_failed_reason = err;
2084                     sm_connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
2085                     break;
2086                 }
2087                 sm_timeout_start(sm_connection);
2088                 // generate random number first, if we need to show passkey
2089                 if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2090                     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);
2091                     break;
2092                 }
2093                 sm_connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
2094                 break;
2095             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2096                 sm_reset_setup();
2097                 sm_start_calculating_ltk_from_ediv_and_rand(sm_connection);
2098                 break;
2099 
2100 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2101             case SM_SC_RECEIVED_LTK_REQUEST:
2102                 switch (sm_connection->sm_irk_lookup_state){
2103                     case IRK_LOOKUP_SUCCEEDED:
2104                         // assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
2105                         // start using context by loading security info
2106                         sm_reset_setup();
2107                         sm_load_security_info(sm_connection);
2108                         if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
2109                             (void)memcpy(setup->sm_ltk,
2110                                          setup->sm_peer_ltk, 16);
2111                             sm_connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
2112                             break;
2113                         }
2114                         log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
2115                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
2116                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2117                         // don't lock setup context yet
2118                         return;
2119                     default:
2120                         // just wait until IRK lookup is completed
2121                         // don't lock setup context yet
2122                         done = 0;
2123                         break;
2124                 }
2125                 break;
2126 #endif /* ENABLE_LE_SECURE_CONNECTIONS */
2127 #endif /* ENABLE_LE_PERIPHERAL */
2128 
2129 #ifdef ENABLE_LE_CENTRAL
2130             case SM_INITIATOR_PH0_HAS_LTK:
2131                 sm_reset_setup();
2132                 sm_load_security_info(sm_connection);
2133                 sm_connection->sm_engine_state = SM_INITIATOR_PH0_SEND_START_ENCRYPTION;
2134                 break;
2135             case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2136                 sm_reset_setup();
2137                 sm_init_setup(sm_connection);
2138                 sm_timeout_start(sm_connection);
2139                 sm_connection->sm_engine_state = SM_INITIATOR_PH1_SEND_PAIRING_REQUEST;
2140                 break;
2141 #endif
2142 
2143             default:
2144                 done = 0;
2145                 break;
2146         }
2147         if (done){
2148             sm_active_connection_handle = sm_connection->sm_handle;
2149             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);
2150         }
2151     }
2152 }
2153 
2154 static void sm_run(void){
2155 
2156     // assert that stack has already bootet
2157     if (hci_get_state() != HCI_STATE_WORKING) return;
2158 
2159     // assert that we can send at least commands
2160     if (!hci_can_send_command_packet_now()) return;
2161 
2162     // pause until IR/ER are ready
2163     if (sm_persistent_keys_random_active) return;
2164 
2165     bool done;
2166 
2167     //
2168     // non-connection related behaviour
2169     //
2170 
2171     done = sm_run_dpkg();
2172     if (done) return;
2173 
2174     done = sm_run_rau();
2175     if (done) return;
2176 
2177     done = sm_run_csrk();
2178     if (done) return;
2179 
2180     done = sm_run_oob();
2181     if (done) return;
2182 
2183     // assert that we can send at least commands - cmd might have been sent by crypto engine
2184     if (!hci_can_send_command_packet_now()) return;
2185 
2186     // handle basic actions that don't requires the full context
2187     done = sm_run_basic();
2188     if (done) return;
2189 
2190     //
2191     // active connection handling
2192     // -- use loop to handle next connection if lock on setup context is released
2193 
2194     while (true) {
2195 
2196         sm_run_activate_connection();
2197 
2198         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
2199 
2200         //
2201         // active connection handling
2202         //
2203 
2204         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
2205         if (!connection) {
2206             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
2207             return;
2208         }
2209 
2210         // assert that we could send a SM PDU - not needed for all of the following
2211         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2212             log_info("cannot send now, requesting can send now event");
2213             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2214             return;
2215         }
2216 
2217         // send keypress notifications
2218         if (setup->sm_keypress_notification){
2219             int i;
2220             uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2221             uint8_t num_actions = setup->sm_keypress_notification >> 5;
2222             uint8_t action = 0;
2223             for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2224                 if (flags & (1u<<i)){
2225                     int clear_flag = 1;
2226                     switch (i){
2227                         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2228                         case SM_KEYPRESS_PASSKEY_CLEARED:
2229                         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2230                         default:
2231                             break;
2232                         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2233                         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2234                             num_actions--;
2235                             clear_flag = num_actions == 0u;
2236                             break;
2237                     }
2238                     if (clear_flag){
2239                         flags &= ~(1<<i);
2240                     }
2241                     action = i;
2242                     break;
2243                 }
2244             }
2245             setup->sm_keypress_notification = (num_actions << 5) | flags;
2246 
2247             // send keypress notification
2248             uint8_t buffer[2];
2249             buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2250             buffer[1] = action;
2251             l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2252 
2253             // try
2254             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2255             return;
2256         }
2257 
2258         int key_distribution_flags;
2259         UNUSED(key_distribution_flags);
2260 
2261         log_info("sm_run: state %u", connection->sm_engine_state);
2262         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2263             log_info("sm_run // cannot send");
2264         }
2265         switch (connection->sm_engine_state){
2266 
2267             // general
2268             case SM_GENERAL_SEND_PAIRING_FAILED: {
2269                 uint8_t buffer[2];
2270                 buffer[0] = SM_CODE_PAIRING_FAILED;
2271                 buffer[1] = setup->sm_pairing_failed_reason;
2272                 connection->sm_engine_state = connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2273                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2274                 sm_notify_client_status_reason(connection, ERROR_CODE_AUTHENTICATION_FAILURE, setup->sm_pairing_failed_reason);
2275                 sm_done_for_handle(connection->sm_handle);
2276                 break;
2277             }
2278 
2279             // responding state
2280 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2281             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2282                 if (!sm_cmac_ready()) break;
2283                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2284                 sm_sc_calculate_local_confirm(connection);
2285                 break;
2286             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2287                 if (!sm_cmac_ready()) break;
2288                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2289                 sm_sc_calculate_remote_confirm(connection);
2290                 break;
2291             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2292                 if (!sm_cmac_ready()) break;
2293                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2294                 sm_sc_calculate_f6_for_dhkey_check(connection);
2295                 break;
2296             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2297                 if (!sm_cmac_ready()) break;
2298                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
2299                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
2300                 break;
2301             case SM_SC_W2_CALCULATE_F5_SALT:
2302                 if (!sm_cmac_ready()) break;
2303                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
2304                 f5_calculate_salt(connection);
2305                 break;
2306             case SM_SC_W2_CALCULATE_F5_MACKEY:
2307                 if (!sm_cmac_ready()) break;
2308                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
2309                 f5_calculate_mackey(connection);
2310                 break;
2311             case SM_SC_W2_CALCULATE_F5_LTK:
2312                 if (!sm_cmac_ready()) break;
2313                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
2314                 f5_calculate_ltk(connection);
2315                 break;
2316             case SM_SC_W2_CALCULATE_G2:
2317                 if (!sm_cmac_ready()) break;
2318                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2319                 g2_calculate(connection);
2320                 break;
2321             case SM_SC_W2_CALCULATE_H6_ILK:
2322                 if (!sm_cmac_ready()) break;
2323                 connection->sm_engine_state = SM_SC_W4_CALCULATE_H6_ILK;
2324                 h6_calculate_ilk(connection);
2325                 break;
2326             case SM_SC_W2_CALCULATE_H6_BR_EDR_LINK_KEY:
2327                 if (!sm_cmac_ready()) break;
2328                 connection->sm_engine_state = SM_SC_W4_CALCULATE_H6_BR_EDR_LINK_KEY;
2329                 h6_calculate_br_edr_link_key(connection);
2330                 break;
2331 #endif
2332 
2333 #ifdef ENABLE_LE_CENTRAL
2334             // initiator side
2335             case SM_INITIATOR_PH0_SEND_START_ENCRYPTION: {
2336                 sm_key_t peer_ltk_flipped;
2337                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
2338                 connection->sm_engine_state = SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED;
2339                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2340                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2341                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
2342                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
2343                 return;
2344             }
2345 
2346             case SM_INITIATOR_PH1_SEND_PAIRING_REQUEST:
2347                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
2348                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2349                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
2350                 sm_timeout_reset(connection);
2351                 break;
2352 #endif
2353 
2354 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2355 
2356             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
2357                 int trigger_user_response   = 0;
2358                 int trigger_start_calculating_local_confirm = 0;
2359                 uint8_t buffer[65];
2360                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
2361                 //
2362                 reverse_256(&ec_q[0],  &buffer[1]);
2363                 reverse_256(&ec_q[32], &buffer[33]);
2364 
2365 #ifdef ENABLE_TESTING_SUPPORT
2366                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2367                     log_info("testing_support: invalidating public key");
2368                     // flip single bit of public key coordinate
2369                     buffer[1] ^= 1;
2370                 }
2371 #endif
2372 
2373                 // stk generation method
2374                 // passkey entry: notify app to show passkey or to request passkey
2375                 switch (setup->sm_stk_generation_method){
2376                     case JUST_WORKS:
2377                     case NUMERIC_COMPARISON:
2378                         if (IS_RESPONDER(connection->sm_role)){
2379                             // responder
2380                             trigger_start_calculating_local_confirm = 1;
2381                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
2382                         } else {
2383                             // initiator
2384                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2385                         }
2386                         break;
2387                     case PK_INIT_INPUT:
2388                     case PK_RESP_INPUT:
2389                     case PK_BOTH_INPUT:
2390                         // use random TK for display
2391                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
2392                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
2393                         setup->sm_passkey_bit = 0;
2394 
2395                         if (IS_RESPONDER(connection->sm_role)){
2396                             // responder
2397                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2398                         } else {
2399                             // initiator
2400                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2401                         }
2402                         trigger_user_response = 1;
2403                         break;
2404                     case OOB:
2405                         if (IS_RESPONDER(connection->sm_role)){
2406                             // responder
2407                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2408                         } else {
2409                             // initiator
2410                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2411                         }
2412                         break;
2413                 }
2414 
2415                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2416                 sm_timeout_reset(connection);
2417 
2418                 // trigger user response and calc confirm after sending pdu
2419                 if (trigger_user_response){
2420                     sm_trigger_user_response(connection);
2421                 }
2422                 if (trigger_start_calculating_local_confirm){
2423                     sm_sc_start_calculating_local_confirm(connection);
2424                 }
2425                 break;
2426             }
2427             case SM_SC_SEND_CONFIRMATION: {
2428                 uint8_t buffer[17];
2429                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
2430                 reverse_128(setup->sm_local_confirm, &buffer[1]);
2431                 if (IS_RESPONDER(connection->sm_role)){
2432                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2433                 } else {
2434                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2435                 }
2436                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2437                 sm_timeout_reset(connection);
2438                 break;
2439             }
2440             case SM_SC_SEND_PAIRING_RANDOM: {
2441                 uint8_t buffer[17];
2442                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2443                 reverse_128(setup->sm_local_nonce, &buffer[1]);
2444                 log_info("stk method %u, num bits %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
2445                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
2446                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
2447                     if (IS_RESPONDER(connection->sm_role)){
2448                         // responder
2449                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2450                     } else {
2451                         // initiator
2452                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2453                     }
2454                 } else {
2455                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
2456                     if (IS_RESPONDER(connection->sm_role)){
2457                         // responder
2458                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
2459                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2460                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
2461                         } else {
2462                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
2463                             sm_sc_prepare_dhkey_check(connection);
2464                         }
2465                     } else {
2466                         // initiator
2467                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2468                     }
2469                 }
2470                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2471                 sm_timeout_reset(connection);
2472                 break;
2473             }
2474             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2475                 uint8_t buffer[17];
2476                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2477                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2478 
2479                 if (IS_RESPONDER(connection->sm_role)){
2480                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2481                 } else {
2482                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2483                 }
2484 
2485                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2486                 sm_timeout_reset(connection);
2487                 break;
2488             }
2489 
2490 #endif
2491 
2492 #ifdef ENABLE_LE_PERIPHERAL
2493             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
2494                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2495 
2496                 // start with initiator key dist flags
2497                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
2498 
2499 #ifdef ENABLE_LE_SECURE_CONNECTIONS
2500                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2501                 if (setup->sm_use_secure_connections){
2502                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2503                 }
2504 #endif
2505                 // setup in response
2506                 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);
2507                 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);
2508 
2509                 // update key distribution after ENC was dropped
2510                 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres));
2511 
2512                 if (setup->sm_use_secure_connections){
2513                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
2514                 } else {
2515                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
2516                 }
2517 
2518                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
2519                 sm_timeout_reset(connection);
2520                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2521                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
2522                     sm_trigger_user_response(connection);
2523                 }
2524                 return;
2525 #endif
2526 
2527             case SM_PH2_SEND_PAIRING_RANDOM: {
2528                 uint8_t buffer[17];
2529                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2530                 reverse_128(setup->sm_local_random, &buffer[1]);
2531                 if (IS_RESPONDER(connection->sm_role)){
2532                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
2533                 } else {
2534                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
2535                 }
2536                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2537                 sm_timeout_reset(connection);
2538                 break;
2539             }
2540 
2541             case SM_PH2_C1_GET_ENC_A:
2542                 // already busy?
2543                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2544                 // calculate confirm using aes128 engine - step 1
2545                 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);
2546                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2547                 sm_aes128_state = SM_AES128_ACTIVE;
2548                 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);
2549                 break;
2550 
2551             case SM_PH2_C1_GET_ENC_C:
2552                 // already busy?
2553                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2554                 // calculate m_confirm using aes128 engine - step 1
2555                 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);
2556                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2557                 sm_aes128_state = SM_AES128_ACTIVE;
2558                 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);
2559                 break;
2560 
2561             case SM_PH2_CALC_STK:
2562                 // already busy?
2563                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2564                 // calculate STK
2565                 if (IS_RESPONDER(connection->sm_role)){
2566                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
2567                 } else {
2568                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
2569                 }
2570                 connection->sm_engine_state = SM_PH2_W4_STK;
2571                 sm_aes128_state = SM_AES128_ACTIVE;
2572                 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);
2573                 break;
2574 
2575             case SM_PH3_Y_GET_ENC:
2576                 // already busy?
2577                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2578                 // PH3B2 - calculate Y from      - enc
2579 
2580                 // dm helper (was sm_dm_r_prime)
2581                 // r' = padding || r
2582                 // r - 64 bit value
2583                 memset(&sm_aes128_plaintext[0], 0, 8);
2584                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
2585 
2586                 // Y = dm(DHK, Rand)
2587                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2588                 sm_aes128_state = SM_AES128_ACTIVE;
2589                 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);
2590                 break;
2591 
2592             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
2593                 uint8_t buffer[17];
2594                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
2595                 reverse_128(setup->sm_local_confirm, &buffer[1]);
2596                 if (IS_RESPONDER(connection->sm_role)){
2597                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
2598                 } else {
2599                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
2600                 }
2601                 l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2602                 sm_timeout_reset(connection);
2603                 return;
2604             }
2605 #ifdef ENABLE_LE_PERIPHERAL
2606             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
2607                 sm_key_t stk_flipped;
2608                 reverse_128(setup->sm_ltk, stk_flipped);
2609                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
2610                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
2611                 return;
2612             }
2613             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
2614                 sm_key_t ltk_flipped;
2615                 reverse_128(setup->sm_ltk, ltk_flipped);
2616                 connection->sm_engine_state = SM_RESPONDER_IDLE;
2617                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
2618                 sm_done_for_handle(connection->sm_handle);
2619                 return;
2620             }
2621             case SM_RESPONDER_PH4_Y_GET_ENC:
2622                 // already busy?
2623                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2624                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
2625 
2626                 // dm helper (was sm_dm_r_prime)
2627                 // r' = padding || r
2628                 // r - 64 bit value
2629                 memset(&sm_aes128_plaintext[0], 0, 8);
2630                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
2631 
2632                 // Y = dm(DHK, Rand)
2633                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
2634                 sm_aes128_state = SM_AES128_ACTIVE;
2635                 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);
2636                 return;
2637 #endif
2638 #ifdef ENABLE_LE_CENTRAL
2639             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
2640                 sm_key_t stk_flipped;
2641                 reverse_128(setup->sm_ltk, stk_flipped);
2642                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
2643                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
2644                 return;
2645             }
2646 #endif
2647 
2648             case SM_PH3_DISTRIBUTE_KEYS:
2649                 if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2650                     setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2651                     setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2652                     uint8_t buffer[17];
2653                     buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2654                     reverse_128(setup->sm_ltk, &buffer[1]);
2655                     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2656                     sm_timeout_reset(connection);
2657                     return;
2658                 }
2659                 if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2660                     setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2661                     setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2662                     uint8_t buffer[11];
2663                     buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2664                     little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2665                     reverse_64(setup->sm_local_rand, &buffer[3]);
2666                     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2667                     sm_timeout_reset(connection);
2668                     return;
2669                 }
2670                 if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2671                     setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2672                     setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2673                     uint8_t buffer[17];
2674                     buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2675                     reverse_128(sm_persistent_irk, &buffer[1]);
2676                     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2677                     sm_timeout_reset(connection);
2678                     return;
2679                 }
2680                 if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2681                     setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2682                     setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2683                     bd_addr_t local_address;
2684                     uint8_t buffer[8];
2685                     buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2686                     switch (gap_random_address_get_mode()){
2687                         case GAP_RANDOM_ADDRESS_TYPE_OFF:
2688                         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2689                             // public or static random
2690                             gap_le_get_own_address(&buffer[1], local_address);
2691                             break;
2692                         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2693                         case GAP_RANDOM_ADDRESS_RESOLVABLE:
2694                             // fallback to public
2695                             gap_local_bd_addr(local_address);
2696                             buffer[1] = 0;
2697                             break;
2698                     }
2699                     reverse_bd_addr(local_address, &buffer[2]);
2700                     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2701                     sm_timeout_reset(connection);
2702                     return;
2703                 }
2704                 if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2705                     setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2706                     setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2707 
2708 #ifdef ENABLE_LE_SIGNED_WRITE
2709                     // hack to reproduce test runs
2710                     if (test_use_fixed_local_csrk){
2711                         memset(setup->sm_local_csrk, 0xcc, 16);
2712                     }
2713 
2714                     // store local CSRK
2715                     if (setup->sm_le_device_index >= 0){
2716                         log_info("sm: store local CSRK");
2717                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2718                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2719                     }
2720 #endif
2721 
2722                     uint8_t buffer[17];
2723                     buffer[0] = SM_CODE_SIGNING_INFORMATION;
2724                     reverse_128(setup->sm_local_csrk, &buffer[1]);
2725                     l2cap_send_connectionless(connection->sm_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, (uint8_t*) buffer, sizeof(buffer));
2726                     sm_timeout_reset(connection);
2727                     return;
2728                 }
2729 
2730                 // keys are sent
2731                 if (IS_RESPONDER(connection->sm_role)){
2732                     // slave -> receive master keys if any
2733                     if (sm_key_distribution_all_received(connection)){
2734                         sm_key_distribution_handle_all_received(connection);
2735                         connection->sm_engine_state = SM_RESPONDER_IDLE;
2736                         sm_notify_client_status_reason(connection, ERROR_CODE_SUCCESS, 0);
2737                         sm_done_for_handle(connection->sm_handle);
2738                     } else {
2739                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
2740                     }
2741                 } else {
2742                     sm_master_pairing_success(connection);
2743                 }
2744                 break;
2745 
2746             default:
2747                 break;
2748         }
2749 
2750         // check again if active connection was released
2751         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
2752     }
2753 }
2754 
2755 // sm_aes128_state stays active
2756 static void sm_handle_encryption_result_enc_a(void *arg){
2757     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2758     sm_aes128_state = SM_AES128_IDLE;
2759 
2760     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2761     if (connection == NULL) return;
2762 
2763     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
2764     sm_aes128_state = SM_AES128_ACTIVE;
2765     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);
2766 }
2767 
2768 static void sm_handle_encryption_result_enc_b(void *arg){
2769     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2770     sm_aes128_state = SM_AES128_IDLE;
2771 
2772     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2773     if (connection == NULL) return;
2774 
2775     log_info_key("c1!", setup->sm_local_confirm);
2776     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
2777     sm_run();
2778 }
2779 
2780 // sm_aes128_state stays active
2781 static void sm_handle_encryption_result_enc_c(void *arg){
2782     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2783     sm_aes128_state = SM_AES128_IDLE;
2784 
2785     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2786     if (connection == NULL) return;
2787 
2788     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
2789     sm_aes128_state = SM_AES128_ACTIVE;
2790     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);
2791 }
2792 
2793 static void sm_handle_encryption_result_enc_d(void * arg){
2794     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2795     sm_aes128_state = SM_AES128_IDLE;
2796 
2797     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2798     if (connection == NULL) return;
2799 
2800     log_info_key("c1!", sm_aes128_ciphertext);
2801     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
2802         setup->sm_pairing_failed_reason = SM_REASON_CONFIRM_VALUE_FAILED;
2803         connection->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
2804         sm_run();
2805         return;
2806     }
2807     if (IS_RESPONDER(connection->sm_role)){
2808         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
2809         sm_run();
2810     } else {
2811         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
2812         sm_aes128_state = SM_AES128_ACTIVE;
2813         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);
2814     }
2815 }
2816 
2817 static void sm_handle_encryption_result_enc_stk(void *arg){
2818     sm_aes128_state = SM_AES128_IDLE;
2819     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2820 
2821     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2822     if (connection == NULL) return;
2823 
2824     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
2825     log_info_key("stk", setup->sm_ltk);
2826     if (IS_RESPONDER(connection->sm_role)){
2827         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
2828     } else {
2829         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
2830     }
2831     sm_run();
2832 }
2833 
2834 // sm_aes128_state stays active
2835 static void sm_handle_encryption_result_enc_ph3_y(void *arg){
2836     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2837     sm_aes128_state = SM_AES128_IDLE;
2838 
2839     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2840     if (connection == NULL) return;
2841 
2842     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
2843     log_info_hex16("y", setup->sm_local_y);
2844     // PH3B3 - calculate EDIV
2845     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
2846     log_info_hex16("ediv", setup->sm_local_ediv);
2847     // PH3B4 - calculate LTK         - enc
2848     // LTK = d1(ER, DIV, 0))
2849     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
2850     sm_aes128_state = SM_AES128_ACTIVE;
2851     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);
2852 }
2853 
2854 #ifdef ENABLE_LE_PERIPHERAL
2855 // sm_aes128_state stays active
2856 static void sm_handle_encryption_result_enc_ph4_y(void *arg){
2857     sm_aes128_state = SM_AES128_IDLE;
2858     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2859 
2860     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2861     if (connection == NULL) return;
2862 
2863     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
2864     log_info_hex16("y", setup->sm_local_y);
2865 
2866     // PH3B3 - calculate DIV
2867     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
2868     log_info_hex16("ediv", setup->sm_local_ediv);
2869     // PH3B4 - calculate LTK         - enc
2870     // LTK = d1(ER, DIV, 0))
2871     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
2872     sm_aes128_state = SM_AES128_ACTIVE;
2873     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);
2874 }
2875 #endif
2876 
2877 // sm_aes128_state stays active
2878 static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
2879     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2880     sm_aes128_state = SM_AES128_IDLE;
2881 
2882     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2883     if (connection == NULL) return;
2884 
2885     log_info_key("ltk", setup->sm_ltk);
2886     // calc CSRK next
2887     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
2888     sm_aes128_state = SM_AES128_ACTIVE;
2889     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);
2890 }
2891 
2892 static void sm_handle_encryption_result_enc_csrk(void *arg){
2893     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2894     sm_aes128_state = SM_AES128_IDLE;
2895 
2896     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2897     if (connection == NULL) return;
2898 
2899     sm_aes128_state = SM_AES128_IDLE;
2900     log_info_key("csrk", setup->sm_local_csrk);
2901     if (setup->sm_key_distribution_send_set){
2902         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
2903     } else {
2904         // no keys to send, just continue
2905         if (IS_RESPONDER(connection->sm_role)){
2906             // slave -> receive master keys
2907             connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
2908         } else {
2909             if (setup->sm_use_secure_connections && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION)){
2910                 connection->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK;
2911             } else {
2912                 sm_master_pairing_success(connection);
2913             }
2914         }
2915     }
2916     sm_run();
2917 }
2918 
2919 #ifdef ENABLE_LE_PERIPHERAL
2920 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
2921     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2922     sm_aes128_state = SM_AES128_IDLE;
2923 
2924     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2925     if (connection == NULL) return;
2926 
2927     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
2928     log_info_key("ltk", setup->sm_ltk);
2929     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
2930     sm_run();
2931 }
2932 #endif
2933 
2934 static void sm_handle_encryption_result_address_resolution(void *arg){
2935     UNUSED(arg);
2936     sm_aes128_state = SM_AES128_IDLE;
2937 
2938     sm_address_resolution_ah_calculation_active = 0;
2939     // compare calulated address against connecting device
2940     uint8_t * hash = &sm_aes128_ciphertext[13];
2941     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
2942         log_info("LE Device Lookup: matched resolvable private address");
2943         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCEEDED);
2944         sm_run();
2945         return;
2946     }
2947     // no match, try next
2948     sm_address_resolution_test++;
2949     sm_run();
2950 }
2951 
2952 static void sm_handle_encryption_result_dkg_irk(void *arg){
2953     UNUSED(arg);
2954     sm_aes128_state = SM_AES128_IDLE;
2955 
2956     log_info_key("irk", sm_persistent_irk);
2957     dkg_state = DKG_CALC_DHK;
2958     sm_run();
2959 }
2960 
2961 static void sm_handle_encryption_result_dkg_dhk(void *arg){
2962     UNUSED(arg);
2963     sm_aes128_state = SM_AES128_IDLE;
2964 
2965     log_info_key("dhk", sm_persistent_dhk);
2966     dkg_state = DKG_READY;
2967     sm_run();
2968 }
2969 
2970 static void sm_handle_encryption_result_rau(void *arg){
2971     UNUSED(arg);
2972     sm_aes128_state = SM_AES128_IDLE;
2973 
2974     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
2975     rau_state = RAU_SET_ADDRESS;
2976     sm_run();
2977 }
2978 
2979 static void sm_handle_random_result_rau(void * arg){
2980     UNUSED(arg);
2981     // non-resolvable vs. resolvable
2982     switch (gap_random_adress_type){
2983         case GAP_RANDOM_ADDRESS_RESOLVABLE:
2984             // resolvable: use random as prand and calc address hash
2985             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
2986             sm_random_address[0u] &= 0x3fu;
2987             sm_random_address[0u] |= 0x40u;
2988             rau_state = RAU_GET_ENC;
2989             break;
2990         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2991         default:
2992             // "The two most significant bits of the address shall be equal to ‘0’""
2993             sm_random_address[0u] &= 0x3fu;
2994             rau_state = RAU_SET_ADDRESS;
2995             break;
2996     }
2997     sm_run();
2998 }
2999 
3000 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3001 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3002     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3003     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3004     if (connection == NULL) return;
3005 
3006     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
3007     sm_run();
3008 }
3009 
3010 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
3011     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3012     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3013     if (connection == NULL) return;
3014 
3015     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
3016     sm_run();
3017 }
3018 #endif
3019 
3020 static void sm_handle_random_result_ph2_random(void * arg){
3021     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3022     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3023     if (connection == NULL) return;
3024 
3025     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
3026     sm_run();
3027 }
3028 
3029 static void sm_handle_random_result_ph2_tk(void * arg){
3030     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3031     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3032     if (connection == NULL) return;
3033 
3034     sm_reset_tk();
3035     uint32_t tk;
3036     if (sm_fixed_passkey_in_display_role == 0xffffffff){
3037         // map random to 0-999999 without speding much cycles on a modulus operation
3038         tk = little_endian_read_32(sm_random_data,0);
3039         tk = tk & 0xfffff;  // 1048575
3040         if (tk >= 999999u){
3041             tk = tk - 999999u;
3042         }
3043     } else {
3044         // override with pre-defined passkey
3045         tk = sm_fixed_passkey_in_display_role;
3046     }
3047     big_endian_store_32(setup->sm_tk, 12, tk);
3048     if (IS_RESPONDER(connection->sm_role)){
3049         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
3050     } else {
3051         if (setup->sm_use_secure_connections){
3052             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3053         } else {
3054             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3055             sm_trigger_user_response(connection);
3056             // response_idle == nothing <--> sm_trigger_user_response() did not require response
3057             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3058                 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);
3059             }
3060         }
3061     }
3062     sm_run();
3063 }
3064 
3065 static void sm_handle_random_result_ph3_div(void * arg){
3066     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3067     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3068     if (connection == NULL) return;
3069 
3070     // use 16 bit from random value as div
3071     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3072     log_info_hex16("div", setup->sm_local_div);
3073     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
3074     sm_run();
3075 }
3076 
3077 static void sm_handle_random_result_ph3_random(void * arg){
3078     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3079     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3080     if (connection == NULL) return;
3081 
3082     reverse_64(sm_random_data, setup->sm_local_rand);
3083     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
3084     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
3085     // no db for authenticated flag hack: store flag in bit 4 of LSB
3086     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
3087     btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle);
3088 }
3089 static void sm_validate_er_ir(void){
3090     // warn about default ER/IR
3091     int warning = 0;
3092     if (sm_ir_is_default()){
3093         warning = 1;
3094         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3095     }
3096     if (sm_er_is_default()){
3097         warning = 1;
3098         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3099     }
3100     if (warning) {
3101         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3102     }
3103 }
3104 
3105 static void sm_handle_random_result_ir(void *arg){
3106     sm_persistent_keys_random_active = 0;
3107     if (arg){
3108         // key generated, store in tlv
3109         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3110         log_info("Generated IR key. Store in TLV status: %d", status);
3111     }
3112     log_info_key("IR", sm_persistent_ir);
3113     dkg_state = DKG_CALC_IRK;
3114 
3115     if (test_use_fixed_local_irk){
3116         log_info_key("IRK", sm_persistent_irk);
3117         dkg_state = DKG_CALC_DHK;
3118     }
3119 
3120     sm_run();
3121 }
3122 
3123 static void sm_handle_random_result_er(void *arg){
3124     sm_persistent_keys_random_active = 0;
3125     if (arg){
3126         // key generated, store in tlv
3127         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3128         log_info("Generated ER key. Store in TLV status: %d", status);
3129     }
3130     log_info_key("ER", sm_persistent_er);
3131 
3132     // try load ir
3133     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3134     if (key_size == 16){
3135         // ok, let's continue
3136         log_info("IR from TLV");
3137         sm_handle_random_result_ir( NULL );
3138     } else {
3139         // invalid, generate new random one
3140         sm_persistent_keys_random_active = 1;
3141         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3142     }
3143 }
3144 
3145 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3146 
3147     UNUSED(channel);    // ok: there is no channel
3148     UNUSED(size);       // ok: fixed format HCI events
3149 
3150     sm_connection_t  * sm_conn;
3151     hci_con_handle_t con_handle;
3152 
3153     switch (packet_type) {
3154 
3155 		case HCI_EVENT_PACKET:
3156 			switch (hci_event_packet_get_type(packet)) {
3157 
3158                 case BTSTACK_EVENT_STATE:
3159 					// bt stack activated, get started
3160 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
3161                         log_info("HCI Working!");
3162 
3163                         // setup IR/ER with TLV
3164                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
3165                         if (sm_tlv_impl){
3166                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3167                             if (key_size == 16){
3168                                 // ok, let's continue
3169                                 log_info("ER from TLV");
3170                                 sm_handle_random_result_er( NULL );
3171                             } else {
3172                                 // invalid, generate random one
3173                                 sm_persistent_keys_random_active = 1;
3174                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3175                             }
3176                         } else {
3177                             sm_validate_er_ir();
3178                             dkg_state = DKG_CALC_IRK;
3179 
3180                             if (test_use_fixed_local_irk){
3181                                 log_info_key("IRK", sm_persistent_irk);
3182                                 dkg_state = DKG_CALC_DHK;
3183                             }
3184                         }
3185 
3186                         // restart random address updates after power cycle
3187                         gap_random_address_set_mode(gap_random_adress_type);
3188 					}
3189 					break;
3190 
3191                 case HCI_EVENT_LE_META:
3192                     switch (packet[2]) {
3193                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3194 
3195                             log_info("sm: connected");
3196 
3197                             if (packet[3]) return; // connection failed
3198 
3199                             con_handle = little_endian_read_16(packet, 4);
3200                             sm_conn = sm_get_connection_for_handle(con_handle);
3201                             if (!sm_conn) break;
3202 
3203                             sm_conn->sm_handle = con_handle;
3204                             sm_conn->sm_role = packet[6];
3205                             sm_conn->sm_peer_addr_type = packet[7];
3206                             reverse_bd_addr(&packet[8], sm_conn->sm_peer_address);
3207 
3208                             log_info("New sm_conn, role %s", sm_conn->sm_role ? "slave" : "master");
3209 
3210                             // reset security properties
3211                             sm_conn->sm_connection_encrypted = 0;
3212                             sm_conn->sm_connection_authenticated = 0;
3213                             sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3214                             sm_conn->sm_le_db_index = -1;
3215 
3216                             // prepare CSRK lookup (does not involve setup)
3217                             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3218 
3219                             // just connected -> everything else happens in sm_run()
3220                             if (IS_RESPONDER(sm_conn->sm_role)){
3221                                 // slave - state already could be SM_RESPONDER_SEND_SECURITY_REQUEST instead
3222                                 if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){
3223                                     if (sm_slave_request_security) {
3224                                         // request security if requested by app
3225                                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
3226                                     } else {
3227                                         // otherwise, wait for pairing request
3228                                         sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3229                                     }
3230                                 }
3231                                 break;
3232                             } else {
3233                                 // master
3234                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3235                             }
3236                             break;
3237 
3238                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3239                             con_handle = little_endian_read_16(packet, 3);
3240                             sm_conn = sm_get_connection_for_handle(con_handle);
3241                             if (!sm_conn) break;
3242 
3243                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
3244                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
3245                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
3246                                 break;
3247                             }
3248                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3249                                 // PH2 SEND LTK as we need to exchange keys in PH3
3250                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3251                                 break;
3252                             }
3253 
3254                             // store rand and ediv
3255                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3256                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3257 
3258                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3259                             // potentially stored LTK is from the master
3260                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
3261                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
3262                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3263                                     break;
3264                                 }
3265                                 // additionally check if remote is in LE Device DB if requested
3266                                 switch(sm_conn->sm_irk_lookup_state){
3267                                     case IRK_LOOKUP_FAILED:
3268                                         log_info("LTK Request: device not in device db");
3269                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3270                                         break;
3271                                     case IRK_LOOKUP_SUCCEEDED:
3272                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3273                                         break;
3274                                     default:
3275                                         // wait for irk look doen
3276                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
3277                                         break;
3278                                 }
3279                                 break;
3280                             }
3281 
3282 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3283                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3284 #else
3285                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3286                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3287 #endif
3288                             break;
3289 
3290                         default:
3291                             break;
3292                     }
3293                     break;
3294 
3295                 case HCI_EVENT_ENCRYPTION_CHANGE:
3296                     con_handle = little_endian_read_16(packet, 3);
3297                     sm_conn = sm_get_connection_for_handle(con_handle);
3298                     if (!sm_conn) break;
3299 
3300                     sm_conn->sm_connection_encrypted = packet[5];
3301                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
3302                         sm_conn->sm_actual_encryption_key_size);
3303                     log_info("event handler, state %u", sm_conn->sm_engine_state);
3304 
3305                     // encryption change event concludes re-encryption for bonded devices (even if it fails)
3306                     if (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED){
3307                         sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3308                         // notify client, if pairing was requested before
3309                         if (sm_conn->sm_pairing_requested){
3310                             sm_conn->sm_pairing_requested = 0;
3311                             if (sm_conn->sm_connection_encrypted){
3312                                 sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
3313                             } else {
3314                                 sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, 0);
3315                             }
3316                         }
3317                         sm_done_for_handle(sm_conn->sm_handle);
3318                         break;
3319                     }
3320 
3321                     if (!sm_conn->sm_connection_encrypted) break;
3322                     sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
3323 
3324                     // continue pairing
3325                     switch (sm_conn->sm_engine_state){
3326                         case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED:
3327                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3328                             sm_done_for_handle(sm_conn->sm_handle);
3329                             break;
3330                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3331                             if (IS_RESPONDER(sm_conn->sm_role)){
3332                                 // slave
3333                                 if (setup->sm_use_secure_connections){
3334                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3335                                 } else {
3336                                     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);
3337                                 }
3338                             } else {
3339                                 // master
3340                                 if (sm_key_distribution_all_received(sm_conn)){
3341                                     // skip receiving keys as there are none
3342                                     sm_key_distribution_handle_all_received(sm_conn);
3343                                     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);
3344                                 } else {
3345                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3346                                 }
3347                             }
3348                             break;
3349                         default:
3350                             break;
3351                     }
3352                     break;
3353 
3354                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3355                     con_handle = little_endian_read_16(packet, 3);
3356                     sm_conn = sm_get_connection_for_handle(con_handle);
3357                     if (!sm_conn) break;
3358 
3359                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
3360                     log_info("event handler, state %u", sm_conn->sm_engine_state);
3361                     // continue if part of initial pairing
3362                     switch (sm_conn->sm_engine_state){
3363                         case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED:
3364                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3365                             sm_done_for_handle(sm_conn->sm_handle);
3366                             break;
3367                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3368                             if (IS_RESPONDER(sm_conn->sm_role)){
3369                                 // slave
3370                                 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);
3371                             } else {
3372                                 // master
3373                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3374                             }
3375                             break;
3376                         default:
3377                             break;
3378                     }
3379                     break;
3380 
3381 
3382                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3383                     con_handle = little_endian_read_16(packet, 3);
3384                     sm_done_for_handle(con_handle);
3385                     sm_conn = sm_get_connection_for_handle(con_handle);
3386                     if (!sm_conn) break;
3387 
3388                     // delete stored bonding on disconnect with authentication failure in ph0
3389                     if ((sm_conn->sm_role == 0u)
3390                         && (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED)
3391                         && (packet[2] == ERROR_CODE_AUTHENTICATION_FAILURE)){
3392                         le_device_db_remove(sm_conn->sm_le_db_index);
3393                     }
3394 
3395                     // pairing failed, if it was ongoing
3396                     switch (sm_conn->sm_engine_state){
3397                         case SM_GENERAL_IDLE:
3398                         case SM_INITIATOR_CONNECTED:
3399                         case SM_RESPONDER_IDLE:
3400                             break;
3401                         default:
3402                             sm_notify_client_status_reason(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
3403                             break;
3404                     }
3405 
3406                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3407                     sm_conn->sm_handle = 0;
3408                     break;
3409 
3410 				case HCI_EVENT_COMMAND_COMPLETE:
3411                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
3412                         // set local addr for le device db
3413                         bd_addr_t addr;
3414                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
3415                         le_device_db_set_local_bd_addr(addr);
3416                     }
3417                     break;
3418                 default:
3419                     break;
3420 			}
3421             break;
3422         default:
3423             break;
3424 	}
3425 
3426     sm_run();
3427 }
3428 
3429 static inline int sm_calc_actual_encryption_key_size(int other){
3430     if (other < sm_min_encryption_key_size) return 0;
3431     if (other < sm_max_encryption_key_size) return other;
3432     return sm_max_encryption_key_size;
3433 }
3434 
3435 
3436 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3437 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3438     switch (method){
3439         case JUST_WORKS:
3440         case NUMERIC_COMPARISON:
3441             return 1;
3442         default:
3443             return 0;
3444     }
3445 }
3446 // responder
3447 
3448 static int sm_passkey_used(stk_generation_method_t method){
3449     switch (method){
3450         case PK_RESP_INPUT:
3451             return 1;
3452         default:
3453             return 0;
3454     }
3455 }
3456 
3457 static int sm_passkey_entry(stk_generation_method_t method){
3458     switch (method){
3459         case PK_RESP_INPUT:
3460         case PK_INIT_INPUT:
3461         case PK_BOTH_INPUT:
3462             return 1;
3463         default:
3464             return 0;
3465     }
3466 }
3467 
3468 #endif
3469 
3470 /**
3471  * @return ok
3472  */
3473 static int sm_validate_stk_generation_method(void){
3474     // check if STK generation method is acceptable by client
3475     switch (setup->sm_stk_generation_method){
3476         case JUST_WORKS:
3477             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
3478         case PK_RESP_INPUT:
3479         case PK_INIT_INPUT:
3480         case PK_BOTH_INPUT:
3481             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
3482         case OOB:
3483             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
3484         case NUMERIC_COMPARISON:
3485             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
3486         default:
3487             return 0;
3488     }
3489 }
3490 
3491 static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
3492 
3493     // size of complete sm_pdu used to validate input
3494     static const uint8_t sm_pdu_size[] = {
3495             0,  // 0x00 invalid opcode
3496             7,  // 0x01 pairing request
3497             7,  // 0x02 pairing response
3498             17, // 0x03 pairing confirm
3499             17, // 0x04 pairing random
3500             2,  // 0x05 pairing failed
3501             17, // 0x06 encryption information
3502             11, // 0x07 master identification
3503             17, // 0x08 identification information
3504             8,  // 0x09 identify address information
3505             17, // 0x0a signing information
3506             2,  // 0x0b security request
3507             65, // 0x0c pairing public key
3508             17, // 0x0d pairing dhk check
3509             2,  // 0x0e keypress notification
3510     };
3511 
3512     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3513         sm_run();
3514     }
3515 
3516     if (packet_type != SM_DATA_PACKET) return;
3517     if (size == 0u) return;
3518 
3519     uint8_t sm_pdu_code = packet[0];
3520 
3521     // validate pdu size
3522     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
3523     if (sm_pdu_size[sm_pdu_code] != size)   return;
3524 
3525     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
3526     if (!sm_conn) return;
3527 
3528     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
3529         sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3530         sm_done_for_handle(con_handle);
3531         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
3532         return;
3533     }
3534 
3535     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
3536 
3537     int err;
3538     UNUSED(err);
3539 
3540     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
3541         uint8_t buffer[5];
3542         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
3543         buffer[1] = 3;
3544         little_endian_store_16(buffer, 2, con_handle);
3545         buffer[4] = packet[1];
3546         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
3547         return;
3548     }
3549 
3550     switch (sm_conn->sm_engine_state){
3551 
3552         // a sm timeout requries a new physical connection
3553         case SM_GENERAL_TIMEOUT:
3554             return;
3555 
3556 #ifdef ENABLE_LE_CENTRAL
3557 
3558         // Initiator
3559         case SM_INITIATOR_CONNECTED:
3560             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
3561                 sm_pdu_received_in_wrong_state(sm_conn);
3562                 break;
3563             }
3564 
3565             // IRK complete?
3566             int have_ltk;
3567             uint8_t ltk[16];
3568             switch (sm_conn->sm_irk_lookup_state){
3569                 case IRK_LOOKUP_FAILED:
3570                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3571                     break;
3572                 case IRK_LOOKUP_SUCCEEDED:
3573                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3574                     have_ltk = !sm_is_null_key(ltk);
3575                     log_info("central: security request - have_ltk %u", have_ltk);
3576                     if (have_ltk){
3577                         sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK;
3578                     } else {
3579                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3580                     }
3581                     break;
3582                 default:
3583                     break;
3584             }
3585 
3586             // otherwise, store security request
3587             sm_conn->sm_security_request_received = 1;
3588             break;
3589 
3590         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3591             // Core 5, Vol 3, Part H, 2.4.6:
3592             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3593             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3594             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3595                 log_info("Ignoring Security Request");
3596                 break;
3597             }
3598 
3599             // all other pdus are incorrect
3600             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
3601                 sm_pdu_received_in_wrong_state(sm_conn);
3602                 break;
3603             }
3604 
3605             // store pairing request
3606             (void)memcpy(&setup->sm_s_pres, packet,
3607                          sizeof(sm_pairing_packet_t));
3608             err = sm_stk_generation_init(sm_conn);
3609 
3610 #ifdef ENABLE_TESTING_SUPPORT
3611             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
3612                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
3613                 err = test_pairing_failure;
3614             }
3615 #endif
3616 
3617             if (err){
3618                 setup->sm_pairing_failed_reason = err;
3619                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
3620                 break;
3621             }
3622 
3623             // generate random number first, if we need to show passkey
3624             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3625                 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);
3626                 break;
3627             }
3628 
3629 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3630             if (setup->sm_use_secure_connections){
3631                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
3632                 if (setup->sm_stk_generation_method == JUST_WORKS){
3633                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3634                     sm_trigger_user_response(sm_conn);
3635                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3636                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3637                     }
3638                 } else {
3639                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3640                 }
3641                 break;
3642             }
3643 #endif
3644             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3645             sm_trigger_user_response(sm_conn);
3646             // response_idle == nothing <--> sm_trigger_user_response() did not require response
3647             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3648                 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);
3649             }
3650             break;
3651 
3652         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
3653             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3654                 sm_pdu_received_in_wrong_state(sm_conn);
3655                 break;
3656             }
3657 
3658             // store s_confirm
3659             reverse_128(&packet[1], setup->sm_peer_confirm);
3660 
3661 #ifdef ENABLE_TESTING_SUPPORT
3662             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3663                 log_info("testing_support: reset confirm value");
3664                 memset(setup->sm_peer_confirm, 0, 16);
3665             }
3666 #endif
3667             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
3668             break;
3669 
3670         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
3671             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3672                 sm_pdu_received_in_wrong_state(sm_conn);
3673                 break;;
3674             }
3675 
3676             // received random value
3677             reverse_128(&packet[1], setup->sm_peer_random);
3678             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
3679             break;
3680 #endif
3681 
3682 #ifdef ENABLE_LE_PERIPHERAL
3683         // Responder
3684         case SM_RESPONDER_IDLE:
3685         case SM_RESPONDER_SEND_SECURITY_REQUEST:
3686         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
3687             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
3688                 sm_pdu_received_in_wrong_state(sm_conn);
3689                 break;;
3690             }
3691 
3692             // store pairing request
3693             (void)memcpy(&sm_conn->sm_m_preq, packet,
3694                          sizeof(sm_pairing_packet_t));
3695             sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
3696             break;
3697 #endif
3698 
3699 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3700         case SM_SC_W4_PUBLIC_KEY_COMMAND:
3701             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
3702                 sm_pdu_received_in_wrong_state(sm_conn);
3703                 break;
3704             }
3705 
3706             // store public key for DH Key calculation
3707             reverse_256(&packet[01], &setup->sm_peer_q[0]);
3708             reverse_256(&packet[33], &setup->sm_peer_q[32]);
3709 
3710             // validate public key
3711             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
3712             if (err){
3713                 log_error("sm: peer public key invalid %x", err);
3714                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
3715                 break;
3716             }
3717 
3718             // start calculating dhkey
3719             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);
3720 
3721 
3722             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
3723             if (IS_RESPONDER(sm_conn->sm_role)){
3724                 // responder
3725                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3726             } else {
3727                 // initiator
3728                 // stk generation method
3729                 // passkey entry: notify app to show passkey or to request passkey
3730                 switch (setup->sm_stk_generation_method){
3731                     case JUST_WORKS:
3732                     case NUMERIC_COMPARISON:
3733                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
3734                         break;
3735                     case PK_RESP_INPUT:
3736                         sm_sc_start_calculating_local_confirm(sm_conn);
3737                         break;
3738                     case PK_INIT_INPUT:
3739                     case PK_BOTH_INPUT:
3740                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
3741                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
3742                             break;
3743                         }
3744                         sm_sc_start_calculating_local_confirm(sm_conn);
3745                         break;
3746                     case OOB:
3747                         // generate Nx
3748                         log_info("Generate Na");
3749                         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);
3750                         break;
3751                 }
3752             }
3753             break;
3754 
3755         case SM_SC_W4_CONFIRMATION:
3756             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3757                 sm_pdu_received_in_wrong_state(sm_conn);
3758                 break;
3759             }
3760             // received confirm value
3761             reverse_128(&packet[1], setup->sm_peer_confirm);
3762 
3763 #ifdef ENABLE_TESTING_SUPPORT
3764             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3765                 log_info("testing_support: reset confirm value");
3766                 memset(setup->sm_peer_confirm, 0, 16);
3767             }
3768 #endif
3769             if (IS_RESPONDER(sm_conn->sm_role)){
3770                 // responder
3771                 if (sm_passkey_used(setup->sm_stk_generation_method)){
3772                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
3773                         // still waiting for passkey
3774                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
3775                         break;
3776                     }
3777                 }
3778                 sm_sc_start_calculating_local_confirm(sm_conn);
3779             } else {
3780                 // initiator
3781                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
3782                     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);
3783                 } else {
3784                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
3785                 }
3786             }
3787             break;
3788 
3789         case SM_SC_W4_PAIRING_RANDOM:
3790             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3791                 sm_pdu_received_in_wrong_state(sm_conn);
3792                 break;
3793             }
3794 
3795             // received random value
3796             reverse_128(&packet[1], setup->sm_peer_nonce);
3797 
3798             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
3799             // only check for JUST WORK/NC in initiator role OR passkey entry
3800             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
3801                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
3802                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
3803             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
3804             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
3805                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
3806                  break;
3807             }
3808 
3809             // OOB
3810             if (setup->sm_stk_generation_method == OOB){
3811 
3812                 // setup local random, set to zero if remote did not receive our data
3813                 log_info("Received nonce, setup local random ra/rb for dhkey check");
3814                 if (IS_RESPONDER(sm_conn->sm_role)){
3815                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
3816                         log_info("Reset rb as A does not have OOB data");
3817                         memset(setup->sm_rb, 0, 16);
3818                     } else {
3819                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
3820                         log_info("Use stored rb");
3821                         log_info_hexdump(setup->sm_rb, 16);
3822                     }
3823                 }  else {
3824                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
3825                         log_info("Reset ra as B does not have OOB data");
3826                         memset(setup->sm_ra, 0, 16);
3827                     } else {
3828                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
3829                         log_info("Use stored ra");
3830                         log_info_hexdump(setup->sm_ra, 16);
3831                     }
3832                 }
3833 
3834                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
3835                 if (setup->sm_have_oob_data){
3836                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
3837                      break;
3838                 }
3839             }
3840 
3841             // TODO: we only get here for Responder role with JW/NC
3842             sm_sc_state_after_receiving_random(sm_conn);
3843             break;
3844 
3845         case SM_SC_W2_CALCULATE_G2:
3846         case SM_SC_W4_CALCULATE_G2:
3847         case SM_SC_W4_CALCULATE_DHKEY:
3848         case SM_SC_W2_CALCULATE_F5_SALT:
3849         case SM_SC_W4_CALCULATE_F5_SALT:
3850         case SM_SC_W2_CALCULATE_F5_MACKEY:
3851         case SM_SC_W4_CALCULATE_F5_MACKEY:
3852         case SM_SC_W2_CALCULATE_F5_LTK:
3853         case SM_SC_W4_CALCULATE_F5_LTK:
3854         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
3855         case SM_SC_W4_DHKEY_CHECK_COMMAND:
3856         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
3857         case SM_SC_W4_USER_RESPONSE:
3858             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
3859                 sm_pdu_received_in_wrong_state(sm_conn);
3860                 break;
3861             }
3862             // store DHKey Check
3863             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
3864             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
3865 
3866             // have we been only waiting for dhkey check command?
3867             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
3868                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
3869             }
3870             break;
3871 #endif
3872 
3873 #ifdef ENABLE_LE_PERIPHERAL
3874         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
3875             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3876                 sm_pdu_received_in_wrong_state(sm_conn);
3877                 break;
3878             }
3879 
3880             // received confirm value
3881             reverse_128(&packet[1], setup->sm_peer_confirm);
3882 
3883 #ifdef ENABLE_TESTING_SUPPORT
3884             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3885                 log_info("testing_support: reset confirm value");
3886                 memset(setup->sm_peer_confirm, 0, 16);
3887             }
3888 #endif
3889             // notify client to hide shown passkey
3890             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
3891                 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
3892             }
3893 
3894             // handle user cancel pairing?
3895             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
3896                 setup->sm_pairing_failed_reason = SM_REASON_PASSKEY_ENTRY_FAILED;
3897                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
3898                 break;
3899             }
3900 
3901             // wait for user action?
3902             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
3903                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3904                 break;
3905             }
3906 
3907             // calculate and send local_confirm
3908             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);
3909             break;
3910 
3911         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
3912             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3913                 sm_pdu_received_in_wrong_state(sm_conn);
3914                 break;;
3915             }
3916 
3917             // received random value
3918             reverse_128(&packet[1], setup->sm_peer_random);
3919             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
3920             break;
3921 #endif
3922 
3923         case SM_PH3_RECEIVE_KEYS:
3924             switch(sm_pdu_code){
3925                 case SM_CODE_ENCRYPTION_INFORMATION:
3926                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
3927                     reverse_128(&packet[1], setup->sm_peer_ltk);
3928                     break;
3929 
3930                 case SM_CODE_MASTER_IDENTIFICATION:
3931                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
3932                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
3933                     reverse_64(&packet[3], setup->sm_peer_rand);
3934                     break;
3935 
3936                 case SM_CODE_IDENTITY_INFORMATION:
3937                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
3938                     reverse_128(&packet[1], setup->sm_peer_irk);
3939                     break;
3940 
3941                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
3942                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
3943                     setup->sm_peer_addr_type = packet[1];
3944                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
3945                     break;
3946 
3947                 case SM_CODE_SIGNING_INFORMATION:
3948                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
3949                     reverse_128(&packet[1], setup->sm_peer_csrk);
3950                     break;
3951                 default:
3952                     // Unexpected PDU
3953                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
3954                     break;
3955             }
3956             // done with key distribution?
3957             if (sm_key_distribution_all_received(sm_conn)){
3958 
3959                 sm_key_distribution_handle_all_received(sm_conn);
3960 
3961                 if (IS_RESPONDER(sm_conn->sm_role)){
3962                     if (setup->sm_use_secure_connections && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION)){
3963                         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK;
3964                     } else {
3965                         sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3966                         sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
3967                         sm_done_for_handle(sm_conn->sm_handle);
3968                     }
3969                 } else {
3970                     if (setup->sm_use_secure_connections){
3971                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3972                     } else {
3973                         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);
3974                     }
3975                 }
3976             }
3977             break;
3978         default:
3979             // Unexpected PDU
3980             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
3981             break;
3982     }
3983 
3984     // try to send preparared packet
3985     sm_run();
3986 }
3987 
3988 // Security Manager Client API
3989 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
3990     sm_get_oob_data = get_oob_data_callback;
3991 }
3992 
3993 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)){
3994     sm_get_sc_oob_data = get_sc_oob_data_callback;
3995 }
3996 
3997 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
3998     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
3999 }
4000 
4001 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
4002     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
4003 }
4004 
4005 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
4006 	sm_min_encryption_key_size = min_size;
4007 	sm_max_encryption_key_size = max_size;
4008 }
4009 
4010 void sm_set_authentication_requirements(uint8_t auth_req){
4011 #ifndef ENABLE_LE_SECURE_CONNECTIONS
4012     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
4013         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
4014         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
4015     }
4016 #endif
4017     sm_auth_req = auth_req;
4018 }
4019 
4020 void sm_set_io_capabilities(io_capability_t io_capability){
4021     sm_io_capabilities = io_capability;
4022 }
4023 
4024 #ifdef ENABLE_LE_PERIPHERAL
4025 void sm_set_request_security(int enable){
4026     sm_slave_request_security = enable;
4027 }
4028 #endif
4029 
4030 void sm_set_er(sm_key_t er){
4031     (void)memcpy(sm_persistent_er, er, 16);
4032 }
4033 
4034 void sm_set_ir(sm_key_t ir){
4035     (void)memcpy(sm_persistent_ir, ir, 16);
4036 }
4037 
4038 // Testing support only
4039 void sm_test_set_irk(sm_key_t irk){
4040     (void)memcpy(sm_persistent_irk, irk, 16);
4041     dkg_state = DKG_CALC_DHK;
4042     test_use_fixed_local_irk = true;
4043 }
4044 
4045 void sm_test_use_fixed_local_csrk(void){
4046     test_use_fixed_local_csrk = true;
4047 }
4048 
4049 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4050 static void sm_ec_generated(void * arg){
4051     UNUSED(arg);
4052     ec_key_generation_state = EC_KEY_GENERATION_DONE;
4053     // trigger pairing if pending for ec key
4054     sm_run();
4055 }
4056 static void sm_ec_generate_new_key(void){
4057     log_info("sm: generate new ec key");
4058     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4059     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4060 }
4061 #endif
4062 
4063 #ifdef ENABLE_TESTING_SUPPORT
4064 void sm_test_set_pairing_failure(int reason){
4065     test_pairing_failure = reason;
4066 }
4067 #endif
4068 
4069 void sm_init(void){
4070     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4071     sm_er_ir_set_default();
4072 
4073     // defaults
4074     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
4075                                        | SM_STK_GENERATION_METHOD_OOB
4076                                        | SM_STK_GENERATION_METHOD_PASSKEY
4077                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4078 
4079     sm_max_encryption_key_size = 16;
4080     sm_min_encryption_key_size = 7;
4081 
4082     sm_fixed_passkey_in_display_role = 0xffffffff;
4083     sm_reconstruct_ltk_without_le_device_db_entry = 1;
4084 
4085 #ifdef USE_CMAC_ENGINE
4086     sm_cmac_active  = 0;
4087 #endif
4088     dkg_state = DKG_W4_WORKING;
4089     rau_state = RAU_IDLE;
4090     sm_aes128_state = SM_AES128_IDLE;
4091     sm_address_resolution_test = -1;    // no private address to resolve yet
4092     sm_address_resolution_ah_calculation_active = 0;
4093     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
4094     sm_address_resolution_general_queue = NULL;
4095 
4096     gap_random_adress_update_period = 15 * 60 * 1000L;
4097     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
4098 
4099     test_use_fixed_local_csrk = false;
4100 
4101     // register for HCI Events from HCI
4102     hci_event_callback_registration.callback = &sm_event_packet_handler;
4103     hci_add_event_handler(&hci_event_callback_registration);
4104 
4105     //
4106     btstack_crypto_init();
4107 
4108     // init le_device_db
4109     le_device_db_init();
4110 
4111     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4112     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4113 
4114 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4115     sm_ec_generate_new_key();
4116 #endif
4117 }
4118 
4119 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
4120     sm_fixed_passkey_in_display_role = passkey;
4121 }
4122 
4123 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
4124     sm_reconstruct_ltk_without_le_device_db_entry = allow;
4125 }
4126 
4127 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4128     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4129     if (!hci_con) return NULL;
4130     return &hci_con->sm_connection;
4131 }
4132 
4133 static void sm_send_security_request_for_connection(sm_connection_t * sm_conn){
4134     switch (sm_conn->sm_engine_state){
4135         case SM_GENERAL_IDLE:
4136         case SM_RESPONDER_IDLE:
4137             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
4138             sm_run();
4139             break;
4140         default:
4141             break;
4142     }
4143 }
4144 
4145 /**
4146  * @brief Trigger Security Request
4147  */
4148 void sm_send_security_request(hci_con_handle_t con_handle){
4149     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4150     if (!sm_conn) return;
4151     sm_send_security_request_for_connection(sm_conn);
4152 }
4153 
4154 // request pairing
4155 void sm_request_pairing(hci_con_handle_t con_handle){
4156     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4157     if (!sm_conn) return;     // wrong connection
4158 
4159     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
4160     if (IS_RESPONDER(sm_conn->sm_role)){
4161         sm_send_security_request_for_connection(sm_conn);
4162     } else {
4163         // used as a trigger to start central/master/initiator security procedures
4164         if (sm_conn->sm_engine_state == SM_INITIATOR_CONNECTED){
4165             uint8_t ltk[16];
4166             bool have_ltk;
4167             switch (sm_conn->sm_irk_lookup_state){
4168                 case IRK_LOOKUP_SUCCEEDED:
4169 #ifndef ENABLE_LE_CENTRAL_AUTO_ENCRYPTION
4170                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4171                     have_ltk = !sm_is_null_key(ltk);
4172                     log_info("have ltk %u", have_ltk);
4173                     if (have_ltk){
4174                         sm_conn->sm_pairing_requested = 1;
4175                         sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK;
4176                         break;
4177                     }
4178 #endif
4179                     /* fall through */
4180 
4181                 case IRK_LOOKUP_FAILED:
4182                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4183                     break;
4184                 default:
4185                     log_info("irk lookup pending");
4186                     sm_conn->sm_pairing_requested = 1;
4187                     break;
4188             }
4189         } else if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){
4190             sm_conn->sm_pairing_requested = 1;
4191         }
4192     }
4193     sm_run();
4194 }
4195 
4196 // called by client app on authorization request
4197 void sm_authorization_decline(hci_con_handle_t con_handle){
4198     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4199     if (!sm_conn) return;     // wrong connection
4200     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4201     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0);
4202 }
4203 
4204 void sm_authorization_grant(hci_con_handle_t con_handle){
4205     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4206     if (!sm_conn) return;     // wrong connection
4207     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4208     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1);
4209 }
4210 
4211 // GAP Bonding API
4212 
4213 void sm_bonding_decline(hci_con_handle_t con_handle){
4214     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4215     if (!sm_conn) return;     // wrong connection
4216     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
4217     log_info("decline, state %u", sm_conn->sm_engine_state);
4218     switch(sm_conn->sm_engine_state){
4219 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4220         case SM_SC_W4_USER_RESPONSE:
4221         case SM_SC_W4_CONFIRMATION:
4222         case SM_SC_W4_PUBLIC_KEY_COMMAND:
4223 #endif
4224         case SM_PH1_W4_USER_RESPONSE:
4225             switch (setup->sm_stk_generation_method){
4226                 case PK_RESP_INPUT:
4227                 case PK_INIT_INPUT:
4228                 case PK_BOTH_INPUT:
4229                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4230                     break;
4231                 case NUMERIC_COMPARISON:
4232                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4233                     break;
4234                 case JUST_WORKS:
4235                 case OOB:
4236                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4237                     break;
4238             }
4239             break;
4240         default:
4241             break;
4242     }
4243     sm_run();
4244 }
4245 
4246 void sm_just_works_confirm(hci_con_handle_t con_handle){
4247     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4248     if (!sm_conn) return;     // wrong connection
4249     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
4250     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4251         if (setup->sm_use_secure_connections){
4252             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4253         } else {
4254             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);
4255         }
4256     }
4257 
4258 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4259     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4260         sm_sc_prepare_dhkey_check(sm_conn);
4261     }
4262 #endif
4263 
4264     sm_run();
4265 }
4266 
4267 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4268     // for now, it's the same
4269     sm_just_works_confirm(con_handle);
4270 }
4271 
4272 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4273     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4274     if (!sm_conn) return;     // wrong connection
4275     sm_reset_tk();
4276     big_endian_store_32(setup->sm_tk, 12, passkey);
4277     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
4278     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4279         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);
4280     }
4281 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4282     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
4283     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
4284     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4285         sm_sc_start_calculating_local_confirm(sm_conn);
4286     }
4287 #endif
4288     sm_run();
4289 }
4290 
4291 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
4292     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4293     if (!sm_conn) return;     // wrong connection
4294     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4295     uint8_t num_actions = setup->sm_keypress_notification >> 5;
4296     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4297     switch (action){
4298         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4299         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
4300             flags |= (1u << action);
4301             break;
4302         case SM_KEYPRESS_PASSKEY_CLEARED:
4303             // clear counter, keypress & erased flags + set passkey cleared
4304             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4305             break;
4306         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
4307             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4308                 // erase actions queued
4309                 num_actions--;
4310                 if (num_actions == 0u){
4311                     // clear counter, keypress & erased flags
4312                     flags &= 0x19u;
4313                 }
4314                 break;
4315             }
4316             num_actions++;
4317             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4318             break;
4319         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
4320             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4321                 // enter actions queued
4322                 num_actions--;
4323                 if (num_actions == 0u){
4324                     // clear counter, keypress & erased flags
4325                     flags &= 0x19u;
4326                 }
4327                 break;
4328             }
4329             num_actions++;
4330             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4331             break;
4332         default:
4333             break;
4334     }
4335     setup->sm_keypress_notification = (num_actions << 5) | flags;
4336     sm_run();
4337 }
4338 
4339 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4340 static void sm_handle_random_result_oob(void * arg){
4341     UNUSED(arg);
4342     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
4343     sm_run();
4344 }
4345 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
4346 
4347     static btstack_crypto_random_t   sm_crypto_random_oob_request;
4348 
4349     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4350     sm_sc_oob_callback = callback;
4351     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4352     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4353     return 0;
4354 }
4355 #endif
4356 
4357 /**
4358  * @brief Get Identity Resolving state
4359  * @param con_handle
4360  * @return irk_lookup_state_t
4361  */
4362 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4363     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4364     if (!sm_conn) return IRK_LOOKUP_IDLE;
4365     return sm_conn->sm_irk_lookup_state;
4366 }
4367 
4368 /**
4369  * @brief Identify device in LE Device DB
4370  * @param handle
4371  * @returns index from le_device_db or -1 if not found/identified
4372  */
4373 int sm_le_device_index(hci_con_handle_t con_handle ){
4374     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4375     if (!sm_conn) return -1;
4376     return sm_conn->sm_le_db_index;
4377 }
4378 
4379 static int gap_random_address_type_requires_updates(void){
4380     switch (gap_random_adress_type){
4381         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4382         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
4383             return 0;
4384         default:
4385             return 1;
4386     }
4387 }
4388 
4389 static uint8_t own_address_type(void){
4390     switch (gap_random_adress_type){
4391         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4392             return BD_ADDR_TYPE_LE_PUBLIC;
4393         default:
4394             return BD_ADDR_TYPE_LE_RANDOM;
4395     }
4396 }
4397 
4398 // GAP LE API
4399 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
4400     gap_random_address_update_stop();
4401     gap_random_adress_type = random_address_type;
4402     hci_le_set_own_address_type(own_address_type());
4403     if (!gap_random_address_type_requires_updates()) return;
4404     gap_random_address_update_start();
4405     gap_random_address_trigger();
4406 }
4407 
4408 gap_random_address_type_t gap_random_address_get_mode(void){
4409     return gap_random_adress_type;
4410 }
4411 
4412 void gap_random_address_set_update_period(int period_ms){
4413     gap_random_adress_update_period = period_ms;
4414     if (!gap_random_address_type_requires_updates()) return;
4415     gap_random_address_update_stop();
4416     gap_random_address_update_start();
4417 }
4418 
4419 void gap_random_address_set(bd_addr_t addr){
4420     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
4421     (void)memcpy(sm_random_address, addr, 6);
4422     rau_state = RAU_SET_ADDRESS;
4423     sm_run();
4424 }
4425 
4426 #ifdef ENABLE_LE_PERIPHERAL
4427 /*
4428  * @brief Set Advertisement Paramters
4429  * @param adv_int_min
4430  * @param adv_int_max
4431  * @param adv_type
4432  * @param direct_address_type
4433  * @param direct_address
4434  * @param channel_map
4435  * @param filter_policy
4436  *
4437  * @note own_address_type is used from gap_random_address_set_mode
4438  */
4439 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4440     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4441     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
4442         direct_address_typ, direct_address, channel_map, filter_policy);
4443 }
4444 #endif
4445 
4446 int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4447     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4448      // wrong connection
4449     if (!sm_conn) return 0;
4450     // already encrypted
4451     if (sm_conn->sm_connection_encrypted) return 0;
4452     // only central can re-encrypt
4453     if (sm_conn->sm_role == HCI_ROLE_SLAVE) return 0;
4454     // irk status?
4455     switch(sm_conn->sm_irk_lookup_state){
4456         case IRK_LOOKUP_FAILED:
4457             // done, cannot setup encryption
4458             return 0;
4459         case IRK_LOOKUP_SUCCEEDED:
4460             break;
4461         default:
4462             // IR Lookup pending
4463             return 1;
4464     }
4465     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset
4466     return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4467 }
4468 
4469 void sm_set_secure_connections_only_mode(bool enable){
4470 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4471     sm_sc_only_mode = enable;
4472 #else
4473     // SC Only mode not possible without support for SC
4474     btstack_assert(enable == false);
4475 #endif
4476 }
4477