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