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