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