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