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