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