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