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