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