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