xref: /btstack/src/ble/sm.c (revision 55160b1c55a02046ff8051db6cd2e30b3d7958a5)
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 #endif
1540             if (IS_RESPONDER(sm_conn->sm_role)){
1541                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
1542             } else {
1543                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
1544             }
1545             sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
1546             sm_done_for_handle(sm_conn->sm_handle);
1547             break;
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(void){
2925 #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2926 	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;
2927 	bool have_identity_address_info = ((setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION) != 0);
2928 	return bonding_enabled && setup->sm_use_secure_connections && have_identity_address_info;
2929 #else
2930 	return false;
2931 #endif
2932 }
2933 
2934 static void sm_handle_encryption_result_enc_csrk(void *arg){
2935     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2936     sm_aes128_state = SM_AES128_IDLE;
2937 
2938     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2939     if (connection == NULL) return;
2940 
2941     sm_aes128_state = SM_AES128_IDLE;
2942     log_info_key("csrk", setup->sm_local_csrk);
2943     if (setup->sm_key_distribution_send_set){
2944         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
2945     } else {
2946         // no keys to send, just continue
2947         if (IS_RESPONDER(connection->sm_role)){
2948             // slave -> receive master keys
2949             connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
2950         } else {
2951 			if (sm_ctkd_from_le()){
2952                 connection->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK;
2953             } else {
2954                 sm_master_pairing_success(connection);
2955             }
2956         }
2957     }
2958     sm_trigger_run();
2959 }
2960 
2961 #ifdef ENABLE_LE_PERIPHERAL
2962 static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
2963     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
2964     sm_aes128_state = SM_AES128_IDLE;
2965 
2966     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
2967     if (connection == NULL) return;
2968 
2969     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
2970     log_info_key("ltk", setup->sm_ltk);
2971     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
2972     sm_trigger_run();
2973 }
2974 #endif
2975 
2976 static void sm_handle_encryption_result_address_resolution(void *arg){
2977     UNUSED(arg);
2978     sm_aes128_state = SM_AES128_IDLE;
2979 
2980     sm_address_resolution_ah_calculation_active = 0;
2981     // compare calulated address against connecting device
2982     uint8_t * hash = &sm_aes128_ciphertext[13];
2983     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
2984         log_info("LE Device Lookup: matched resolvable private address");
2985         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCEEDED);
2986         sm_trigger_run();
2987         return;
2988     }
2989     // no match, try next
2990     sm_address_resolution_test++;
2991     sm_trigger_run();
2992 }
2993 
2994 static void sm_handle_encryption_result_dkg_irk(void *arg){
2995     UNUSED(arg);
2996     sm_aes128_state = SM_AES128_IDLE;
2997 
2998     log_info_key("irk", sm_persistent_irk);
2999     dkg_state = DKG_CALC_DHK;
3000     sm_trigger_run();
3001 }
3002 
3003 static void sm_handle_encryption_result_dkg_dhk(void *arg){
3004     UNUSED(arg);
3005     sm_aes128_state = SM_AES128_IDLE;
3006 
3007     log_info_key("dhk", sm_persistent_dhk);
3008     dkg_state = DKG_READY;
3009     sm_trigger_run();
3010 }
3011 
3012 static void sm_handle_encryption_result_rau(void *arg){
3013     UNUSED(arg);
3014     sm_aes128_state = SM_AES128_IDLE;
3015 
3016     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3017     rau_state = RAU_SET_ADDRESS;
3018     sm_trigger_run();
3019 }
3020 
3021 static void sm_handle_random_result_rau(void * arg){
3022     UNUSED(arg);
3023     // non-resolvable vs. resolvable
3024     switch (gap_random_adress_type){
3025         case GAP_RANDOM_ADDRESS_RESOLVABLE:
3026             // resolvable: use random as prand and calc address hash
3027             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
3028             sm_random_address[0u] &= 0x3fu;
3029             sm_random_address[0u] |= 0x40u;
3030             rau_state = RAU_GET_ENC;
3031             break;
3032         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
3033         default:
3034             // "The two most significant bits of the address shall be equal to ‘0’""
3035             sm_random_address[0u] &= 0x3fu;
3036             rau_state = RAU_SET_ADDRESS;
3037             break;
3038     }
3039     sm_trigger_run();
3040 }
3041 
3042 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3043 static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3044     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3045     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3046     if (connection == NULL) return;
3047 
3048     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
3049     sm_trigger_run();
3050 }
3051 
3052 static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
3053     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3054     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3055     if (connection == NULL) return;
3056 
3057     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
3058     sm_trigger_run();
3059 }
3060 #endif
3061 
3062 static void sm_handle_random_result_ph2_random(void * arg){
3063     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3064     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3065     if (connection == NULL) return;
3066 
3067     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
3068     sm_trigger_run();
3069 }
3070 
3071 static void sm_handle_random_result_ph2_tk(void * arg){
3072     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3073     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3074     if (connection == NULL) return;
3075 
3076     sm_reset_tk();
3077     uint32_t tk;
3078     if (sm_fixed_passkey_in_display_role == 0xffffffff){
3079         // map random to 0-999999 without speding much cycles on a modulus operation
3080         tk = little_endian_read_32(sm_random_data,0);
3081         tk = tk & 0xfffff;  // 1048575
3082         if (tk >= 999999u){
3083             tk = tk - 999999u;
3084         }
3085     } else {
3086         // override with pre-defined passkey
3087         tk = sm_fixed_passkey_in_display_role;
3088     }
3089     big_endian_store_32(setup->sm_tk, 12, tk);
3090     if (IS_RESPONDER(connection->sm_role)){
3091         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
3092     } else {
3093         if (setup->sm_use_secure_connections){
3094             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3095         } else {
3096             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3097             sm_trigger_user_response(connection);
3098             // response_idle == nothing <--> sm_trigger_user_response() did not require response
3099             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3100                 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);
3101             }
3102         }
3103     }
3104     sm_trigger_run();
3105 }
3106 
3107 static void sm_handle_random_result_ph3_div(void * arg){
3108     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3109     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3110     if (connection == NULL) return;
3111 
3112     // use 16 bit from random value as div
3113     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3114     log_info_hex16("div", setup->sm_local_div);
3115     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
3116     sm_trigger_run();
3117 }
3118 
3119 static void sm_handle_random_result_ph3_random(void * arg){
3120     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3121     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3122     if (connection == NULL) return;
3123 
3124     reverse_64(sm_random_data, setup->sm_local_rand);
3125     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
3126     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
3127     // no db for authenticated flag hack: store flag in bit 4 of LSB
3128     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
3129     btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle);
3130 }
3131 static void sm_validate_er_ir(void){
3132     // warn about default ER/IR
3133     int warning = 0;
3134     if (sm_ir_is_default()){
3135         warning = 1;
3136         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3137     }
3138     if (sm_er_is_default()){
3139         warning = 1;
3140         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3141     }
3142     if (warning) {
3143         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3144     }
3145 }
3146 
3147 static void sm_handle_random_result_ir(void *arg){
3148     sm_persistent_keys_random_active = 0;
3149     if (arg){
3150         // key generated, store in tlv
3151         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3152         log_info("Generated IR key. Store in TLV status: %d", status);
3153     }
3154     log_info_key("IR", sm_persistent_ir);
3155     dkg_state = DKG_CALC_IRK;
3156 
3157     if (test_use_fixed_local_irk){
3158         log_info_key("IRK", sm_persistent_irk);
3159         dkg_state = DKG_CALC_DHK;
3160     }
3161 
3162     sm_trigger_run();
3163 }
3164 
3165 static void sm_handle_random_result_er(void *arg){
3166     sm_persistent_keys_random_active = 0;
3167     if (arg){
3168         // key generated, store in tlv
3169         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3170         log_info("Generated ER key. Store in TLV status: %d", status);
3171     }
3172     log_info_key("ER", sm_persistent_er);
3173 
3174     // try load ir
3175     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3176     if (key_size == 16){
3177         // ok, let's continue
3178         log_info("IR from TLV");
3179         sm_handle_random_result_ir( NULL );
3180     } else {
3181         // invalid, generate new random one
3182         sm_persistent_keys_random_active = 1;
3183         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3184     }
3185 }
3186 
3187 static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3188 
3189     UNUSED(channel);    // ok: there is no channel
3190     UNUSED(size);       // ok: fixed format HCI events
3191 
3192     sm_connection_t  * sm_conn;
3193     hci_con_handle_t con_handle;
3194 
3195     switch (packet_type) {
3196 
3197 		case HCI_EVENT_PACKET:
3198 			switch (hci_event_packet_get_type(packet)) {
3199 
3200                 case BTSTACK_EVENT_STATE:
3201 					// bt stack activated, get started
3202 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
3203                         log_info("HCI Working!");
3204 
3205                         // setup IR/ER with TLV
3206                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
3207                         if (sm_tlv_impl){
3208                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3209                             if (key_size == 16){
3210                                 // ok, let's continue
3211                                 log_info("ER from TLV");
3212                                 sm_handle_random_result_er( NULL );
3213                             } else {
3214                                 // invalid, generate random one
3215                                 sm_persistent_keys_random_active = 1;
3216                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3217                             }
3218                         } else {
3219                             sm_validate_er_ir();
3220                             dkg_state = DKG_CALC_IRK;
3221 
3222                             if (test_use_fixed_local_irk){
3223                                 log_info_key("IRK", sm_persistent_irk);
3224                                 dkg_state = DKG_CALC_DHK;
3225                             }
3226                         }
3227 
3228                         // restart random address updates after power cycle
3229                         gap_random_address_set_mode(gap_random_adress_type);
3230 					}
3231 					break;
3232 
3233                 case HCI_EVENT_LE_META:
3234                     switch (packet[2]) {
3235                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3236 
3237                             log_info("sm: connected");
3238 
3239                             if (packet[3]) return; // connection failed
3240 
3241                             con_handle = little_endian_read_16(packet, 4);
3242                             sm_conn = sm_get_connection_for_handle(con_handle);
3243                             if (!sm_conn) break;
3244 
3245                             sm_conn->sm_handle = con_handle;
3246                             sm_conn->sm_role = packet[6];
3247                             sm_conn->sm_peer_addr_type = packet[7];
3248                             reverse_bd_addr(&packet[8], sm_conn->sm_peer_address);
3249 
3250                             log_info("New sm_conn, role %s", sm_conn->sm_role ? "slave" : "master");
3251 
3252                             // reset security properties
3253                             sm_conn->sm_connection_encrypted = 0;
3254                             sm_conn->sm_connection_authenticated = 0;
3255                             sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3256                             sm_conn->sm_le_db_index = -1;
3257 
3258                             // prepare CSRK lookup (does not involve setup)
3259                             sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3260 
3261                             // just connected -> everything else happens in sm_run()
3262                             if (IS_RESPONDER(sm_conn->sm_role)){
3263                                 // slave - state already could be SM_RESPONDER_SEND_SECURITY_REQUEST instead
3264                                 if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){
3265                                     if (sm_slave_request_security) {
3266                                         // request security if requested by app
3267                                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
3268                                     } else {
3269                                         // otherwise, wait for pairing request
3270                                         sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3271                                     }
3272                                 }
3273                                 break;
3274                             } else {
3275                                 // master
3276                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3277                             }
3278                             break;
3279 
3280                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3281                             con_handle = little_endian_read_16(packet, 3);
3282                             sm_conn = sm_get_connection_for_handle(con_handle);
3283                             if (!sm_conn) break;
3284 
3285                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
3286                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
3287                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
3288                                 break;
3289                             }
3290                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3291                                 // PH2 SEND LTK as we need to exchange keys in PH3
3292                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3293                                 break;
3294                             }
3295 
3296                             // store rand and ediv
3297                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3298                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3299 
3300                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3301                             // potentially stored LTK is from the master
3302                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
3303                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
3304                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3305                                     break;
3306                                 }
3307                                 // additionally check if remote is in LE Device DB if requested
3308                                 switch(sm_conn->sm_irk_lookup_state){
3309                                     case IRK_LOOKUP_FAILED:
3310                                         log_info("LTK Request: device not in device db");
3311                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3312                                         break;
3313                                     case IRK_LOOKUP_SUCCEEDED:
3314                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3315                                         break;
3316                                     default:
3317                                         // wait for irk look doen
3318                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
3319                                         break;
3320                                 }
3321                                 break;
3322                             }
3323 
3324 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3325                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3326 #else
3327                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3328                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3329 #endif
3330                             break;
3331 
3332                         default:
3333                             break;
3334                     }
3335                     break;
3336 
3337                 case HCI_EVENT_ENCRYPTION_CHANGE:
3338                     con_handle = little_endian_read_16(packet, 3);
3339                     sm_conn = sm_get_connection_for_handle(con_handle);
3340                     if (!sm_conn) break;
3341 
3342                     sm_conn->sm_connection_encrypted = packet[5];
3343                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
3344                         sm_conn->sm_actual_encryption_key_size);
3345                     log_info("event handler, state %u", sm_conn->sm_engine_state);
3346 
3347                     // encryption change event concludes re-encryption for bonded devices (even if it fails)
3348                     if (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED){
3349                         sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3350                         // notify client, if pairing was requested before
3351                         if (sm_conn->sm_pairing_requested){
3352                             sm_conn->sm_pairing_requested = 0;
3353                             if (sm_conn->sm_connection_encrypted){
3354                                 sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
3355                             } else {
3356                                 sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, 0);
3357                             }
3358                         }
3359                         sm_done_for_handle(sm_conn->sm_handle);
3360                         break;
3361                     }
3362 
3363                     if (!sm_conn->sm_connection_encrypted) break;
3364                     sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
3365 
3366                     // continue pairing
3367                     switch (sm_conn->sm_engine_state){
3368                         case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED:
3369                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3370                             sm_done_for_handle(sm_conn->sm_handle);
3371                             break;
3372                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3373                             if (IS_RESPONDER(sm_conn->sm_role)){
3374                                 // slave
3375                                 if (setup->sm_use_secure_connections){
3376                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3377                                 } else {
3378                                     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);
3379                                 }
3380                             } else {
3381                                 // master
3382                                 if (sm_key_distribution_all_received(sm_conn)){
3383                                     // skip receiving keys as there are none
3384                                     sm_key_distribution_handle_all_received(sm_conn);
3385                                     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);
3386                                 } else {
3387                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3388                                 }
3389                             }
3390                             break;
3391                         default:
3392                             break;
3393                     }
3394                     break;
3395 
3396                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3397                     con_handle = little_endian_read_16(packet, 3);
3398                     sm_conn = sm_get_connection_for_handle(con_handle);
3399                     if (!sm_conn) break;
3400 
3401                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
3402                     log_info("event handler, state %u", sm_conn->sm_engine_state);
3403                     // continue if part of initial pairing
3404                     switch (sm_conn->sm_engine_state){
3405                         case SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED:
3406                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
3407                             sm_done_for_handle(sm_conn->sm_handle);
3408                             break;
3409                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3410                             if (IS_RESPONDER(sm_conn->sm_role)){
3411                                 // slave
3412                                 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);
3413                             } else {
3414                                 // master
3415                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3416                             }
3417                             break;
3418                         default:
3419                             break;
3420                     }
3421                     break;
3422 
3423 
3424                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3425                     con_handle = little_endian_read_16(packet, 3);
3426                     sm_done_for_handle(con_handle);
3427                     sm_conn = sm_get_connection_for_handle(con_handle);
3428                     if (!sm_conn) break;
3429 
3430                     // delete stored bonding on disconnect with authentication failure in ph0
3431                     if ((sm_conn->sm_role == 0u)
3432                         && (sm_conn->sm_engine_state == SM_INITIATOR_PH0_W4_CONNECTION_ENCRYPTED)
3433                         && (packet[2] == ERROR_CODE_AUTHENTICATION_FAILURE)){
3434                         le_device_db_remove(sm_conn->sm_le_db_index);
3435                     }
3436 
3437                     // pairing failed, if it was ongoing
3438                     switch (sm_conn->sm_engine_state){
3439                         case SM_GENERAL_IDLE:
3440                         case SM_INITIATOR_CONNECTED:
3441                         case SM_RESPONDER_IDLE:
3442                             break;
3443                         default:
3444                             sm_notify_client_status_reason(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
3445                             break;
3446                     }
3447 
3448                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3449                     sm_conn->sm_handle = 0;
3450                     break;
3451 
3452 				case HCI_EVENT_COMMAND_COMPLETE:
3453                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)){
3454                         // set local addr for le device db
3455                         bd_addr_t addr;
3456                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
3457                         le_device_db_set_local_bd_addr(addr);
3458                     }
3459                     break;
3460                 default:
3461                     break;
3462 			}
3463             break;
3464         default:
3465             break;
3466 	}
3467 
3468     sm_run();
3469 }
3470 
3471 static inline int sm_calc_actual_encryption_key_size(int other){
3472     if (other < sm_min_encryption_key_size) return 0;
3473     if (other < sm_max_encryption_key_size) return other;
3474     return sm_max_encryption_key_size;
3475 }
3476 
3477 
3478 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3479 static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3480     switch (method){
3481         case JUST_WORKS:
3482         case NUMERIC_COMPARISON:
3483             return 1;
3484         default:
3485             return 0;
3486     }
3487 }
3488 // responder
3489 
3490 static int sm_passkey_used(stk_generation_method_t method){
3491     switch (method){
3492         case PK_RESP_INPUT:
3493             return 1;
3494         default:
3495             return 0;
3496     }
3497 }
3498 
3499 static int sm_passkey_entry(stk_generation_method_t method){
3500     switch (method){
3501         case PK_RESP_INPUT:
3502         case PK_INIT_INPUT:
3503         case PK_BOTH_INPUT:
3504             return 1;
3505         default:
3506             return 0;
3507     }
3508 }
3509 
3510 #endif
3511 
3512 /**
3513  * @return ok
3514  */
3515 static int sm_validate_stk_generation_method(void){
3516     // check if STK generation method is acceptable by client
3517     switch (setup->sm_stk_generation_method){
3518         case JUST_WORKS:
3519             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
3520         case PK_RESP_INPUT:
3521         case PK_INIT_INPUT:
3522         case PK_BOTH_INPUT:
3523             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
3524         case OOB:
3525             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
3526         case NUMERIC_COMPARISON:
3527             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
3528         default:
3529             return 0;
3530     }
3531 }
3532 
3533 static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
3534 
3535     // size of complete sm_pdu used to validate input
3536     static const uint8_t sm_pdu_size[] = {
3537             0,  // 0x00 invalid opcode
3538             7,  // 0x01 pairing request
3539             7,  // 0x02 pairing response
3540             17, // 0x03 pairing confirm
3541             17, // 0x04 pairing random
3542             2,  // 0x05 pairing failed
3543             17, // 0x06 encryption information
3544             11, // 0x07 master identification
3545             17, // 0x08 identification information
3546             8,  // 0x09 identify address information
3547             17, // 0x0a signing information
3548             2,  // 0x0b security request
3549             65, // 0x0c pairing public key
3550             17, // 0x0d pairing dhk check
3551             2,  // 0x0e keypress notification
3552     };
3553 
3554     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
3555         sm_run();
3556     }
3557 
3558     if (packet_type != SM_DATA_PACKET) return;
3559     if (size == 0u) return;
3560 
3561     uint8_t sm_pdu_code = packet[0];
3562 
3563     // validate pdu size
3564     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
3565     if (sm_pdu_size[sm_pdu_code] != size)   return;
3566 
3567     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
3568     if (!sm_conn) return;
3569 
3570     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
3571         sm_notify_client_status_reason(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
3572         sm_done_for_handle(con_handle);
3573         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
3574         return;
3575     }
3576 
3577     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
3578 
3579     int err;
3580     UNUSED(err);
3581 
3582     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
3583         uint8_t buffer[5];
3584         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
3585         buffer[1] = 3;
3586         little_endian_store_16(buffer, 2, con_handle);
3587         buffer[4] = packet[1];
3588         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
3589         return;
3590     }
3591 
3592     switch (sm_conn->sm_engine_state){
3593 
3594         // a sm timeout requries a new physical connection
3595         case SM_GENERAL_TIMEOUT:
3596             return;
3597 
3598 #ifdef ENABLE_LE_CENTRAL
3599 
3600         // Initiator
3601         case SM_INITIATOR_CONNECTED:
3602             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
3603                 sm_pdu_received_in_wrong_state(sm_conn);
3604                 break;
3605             }
3606 
3607             // IRK complete?
3608             int have_ltk;
3609             uint8_t ltk[16];
3610             switch (sm_conn->sm_irk_lookup_state){
3611                 case IRK_LOOKUP_FAILED:
3612                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3613                     break;
3614                 case IRK_LOOKUP_SUCCEEDED:
3615                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
3616                     have_ltk = !sm_is_null_key(ltk);
3617                     log_info("central: security request - have_ltk %u", have_ltk);
3618                     if (have_ltk){
3619                         sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK;
3620                     } else {
3621                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
3622                     }
3623                     break;
3624                 default:
3625                     break;
3626             }
3627 
3628             // otherwise, store security request
3629             sm_conn->sm_security_request_received = 1;
3630             break;
3631 
3632         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
3633             // Core 5, Vol 3, Part H, 2.4.6:
3634             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
3635             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
3636             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
3637                 log_info("Ignoring Security Request");
3638                 break;
3639             }
3640 
3641             // all other pdus are incorrect
3642             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
3643                 sm_pdu_received_in_wrong_state(sm_conn);
3644                 break;
3645             }
3646 
3647             // store pairing request
3648             (void)memcpy(&setup->sm_s_pres, packet,
3649                          sizeof(sm_pairing_packet_t));
3650             err = sm_stk_generation_init(sm_conn);
3651 
3652 #ifdef ENABLE_TESTING_SUPPORT
3653             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
3654                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
3655                 err = test_pairing_failure;
3656             }
3657 #endif
3658 
3659             if (err){
3660                 setup->sm_pairing_failed_reason = err;
3661                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
3662                 break;
3663             }
3664 
3665             // generate random number first, if we need to show passkey
3666             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
3667                 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);
3668                 break;
3669             }
3670 
3671 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3672             if (setup->sm_use_secure_connections){
3673                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
3674                 if (setup->sm_stk_generation_method == JUST_WORKS){
3675                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3676                     sm_trigger_user_response(sm_conn);
3677                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3678                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3679                     }
3680                 } else {
3681                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3682                 }
3683                 break;
3684             }
3685 #endif
3686             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3687             sm_trigger_user_response(sm_conn);
3688             // response_idle == nothing <--> sm_trigger_user_response() did not require response
3689             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3690                 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);
3691             }
3692             break;
3693 
3694         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
3695             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3696                 sm_pdu_received_in_wrong_state(sm_conn);
3697                 break;
3698             }
3699 
3700             // store s_confirm
3701             reverse_128(&packet[1], setup->sm_peer_confirm);
3702 
3703 #ifdef ENABLE_TESTING_SUPPORT
3704             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3705                 log_info("testing_support: reset confirm value");
3706                 memset(setup->sm_peer_confirm, 0, 16);
3707             }
3708 #endif
3709             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
3710             break;
3711 
3712         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
3713             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3714                 sm_pdu_received_in_wrong_state(sm_conn);
3715                 break;;
3716             }
3717 
3718             // received random value
3719             reverse_128(&packet[1], setup->sm_peer_random);
3720             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
3721             break;
3722 #endif
3723 
3724 #ifdef ENABLE_LE_PERIPHERAL
3725         // Responder
3726         case SM_RESPONDER_IDLE:
3727         case SM_RESPONDER_SEND_SECURITY_REQUEST:
3728         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
3729             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
3730                 sm_pdu_received_in_wrong_state(sm_conn);
3731                 break;;
3732             }
3733 
3734             // store pairing request
3735             (void)memcpy(&sm_conn->sm_m_preq, packet,
3736                          sizeof(sm_pairing_packet_t));
3737             sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
3738             break;
3739 #endif
3740 
3741 #ifdef ENABLE_LE_SECURE_CONNECTIONS
3742         case SM_SC_W4_PUBLIC_KEY_COMMAND:
3743             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
3744                 sm_pdu_received_in_wrong_state(sm_conn);
3745                 break;
3746             }
3747 
3748             // store public key for DH Key calculation
3749             reverse_256(&packet[01], &setup->sm_peer_q[0]);
3750             reverse_256(&packet[33], &setup->sm_peer_q[32]);
3751 
3752             // validate public key
3753             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
3754             if (err){
3755                 log_error("sm: peer public key invalid %x", err);
3756                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
3757                 break;
3758             }
3759 
3760             // start calculating dhkey
3761             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);
3762 
3763 
3764             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
3765             if (IS_RESPONDER(sm_conn->sm_role)){
3766                 // responder
3767                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3768             } else {
3769                 // initiator
3770                 // stk generation method
3771                 // passkey entry: notify app to show passkey or to request passkey
3772                 switch (setup->sm_stk_generation_method){
3773                     case JUST_WORKS:
3774                     case NUMERIC_COMPARISON:
3775                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
3776                         break;
3777                     case PK_RESP_INPUT:
3778                         sm_sc_start_calculating_local_confirm(sm_conn);
3779                         break;
3780                     case PK_INIT_INPUT:
3781                     case PK_BOTH_INPUT:
3782                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
3783                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
3784                             break;
3785                         }
3786                         sm_sc_start_calculating_local_confirm(sm_conn);
3787                         break;
3788                     case OOB:
3789                         // generate Nx
3790                         log_info("Generate Na");
3791                         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);
3792                         break;
3793                 }
3794             }
3795             break;
3796 
3797         case SM_SC_W4_CONFIRMATION:
3798             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3799                 sm_pdu_received_in_wrong_state(sm_conn);
3800                 break;
3801             }
3802             // received confirm value
3803             reverse_128(&packet[1], setup->sm_peer_confirm);
3804 
3805 #ifdef ENABLE_TESTING_SUPPORT
3806             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3807                 log_info("testing_support: reset confirm value");
3808                 memset(setup->sm_peer_confirm, 0, 16);
3809             }
3810 #endif
3811             if (IS_RESPONDER(sm_conn->sm_role)){
3812                 // responder
3813                 if (sm_passkey_used(setup->sm_stk_generation_method)){
3814                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
3815                         // still waiting for passkey
3816                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
3817                         break;
3818                     }
3819                 }
3820                 sm_sc_start_calculating_local_confirm(sm_conn);
3821             } else {
3822                 // initiator
3823                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
3824                     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);
3825                 } else {
3826                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
3827                 }
3828             }
3829             break;
3830 
3831         case SM_SC_W4_PAIRING_RANDOM:
3832             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3833                 sm_pdu_received_in_wrong_state(sm_conn);
3834                 break;
3835             }
3836 
3837             // received random value
3838             reverse_128(&packet[1], setup->sm_peer_nonce);
3839 
3840             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
3841             // only check for JUST WORK/NC in initiator role OR passkey entry
3842             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
3843                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
3844                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
3845             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
3846             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
3847                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
3848                  break;
3849             }
3850 
3851             // OOB
3852             if (setup->sm_stk_generation_method == OOB){
3853 
3854                 // setup local random, set to zero if remote did not receive our data
3855                 log_info("Received nonce, setup local random ra/rb for dhkey check");
3856                 if (IS_RESPONDER(sm_conn->sm_role)){
3857                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
3858                         log_info("Reset rb as A does not have OOB data");
3859                         memset(setup->sm_rb, 0, 16);
3860                     } else {
3861                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
3862                         log_info("Use stored rb");
3863                         log_info_hexdump(setup->sm_rb, 16);
3864                     }
3865                 }  else {
3866                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
3867                         log_info("Reset ra as B does not have OOB data");
3868                         memset(setup->sm_ra, 0, 16);
3869                     } else {
3870                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
3871                         log_info("Use stored ra");
3872                         log_info_hexdump(setup->sm_ra, 16);
3873                     }
3874                 }
3875 
3876                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
3877                 if (setup->sm_have_oob_data){
3878                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
3879                      break;
3880                 }
3881             }
3882 
3883             // TODO: we only get here for Responder role with JW/NC
3884             sm_sc_state_after_receiving_random(sm_conn);
3885             break;
3886 
3887         case SM_SC_W2_CALCULATE_G2:
3888         case SM_SC_W4_CALCULATE_G2:
3889         case SM_SC_W4_CALCULATE_DHKEY:
3890         case SM_SC_W2_CALCULATE_F5_SALT:
3891         case SM_SC_W4_CALCULATE_F5_SALT:
3892         case SM_SC_W2_CALCULATE_F5_MACKEY:
3893         case SM_SC_W4_CALCULATE_F5_MACKEY:
3894         case SM_SC_W2_CALCULATE_F5_LTK:
3895         case SM_SC_W4_CALCULATE_F5_LTK:
3896         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
3897         case SM_SC_W4_DHKEY_CHECK_COMMAND:
3898         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
3899         case SM_SC_W4_USER_RESPONSE:
3900             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
3901                 sm_pdu_received_in_wrong_state(sm_conn);
3902                 break;
3903             }
3904             // store DHKey Check
3905             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
3906             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
3907 
3908             // have we been only waiting for dhkey check command?
3909             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
3910                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
3911             }
3912             break;
3913 #endif
3914 
3915 #ifdef ENABLE_LE_PERIPHERAL
3916         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
3917             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
3918                 sm_pdu_received_in_wrong_state(sm_conn);
3919                 break;
3920             }
3921 
3922             // received confirm value
3923             reverse_128(&packet[1], setup->sm_peer_confirm);
3924 
3925 #ifdef ENABLE_TESTING_SUPPORT
3926             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
3927                 log_info("testing_support: reset confirm value");
3928                 memset(setup->sm_peer_confirm, 0, 16);
3929             }
3930 #endif
3931             // notify client to hide shown passkey
3932             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
3933                 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
3934             }
3935 
3936             // handle user cancel pairing?
3937             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
3938                 setup->sm_pairing_failed_reason = SM_REASON_PASSKEY_ENTRY_FAILED;
3939                 sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
3940                 break;
3941             }
3942 
3943             // wait for user action?
3944             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
3945                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
3946                 break;
3947             }
3948 
3949             // calculate and send local_confirm
3950             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);
3951             break;
3952 
3953         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
3954             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
3955                 sm_pdu_received_in_wrong_state(sm_conn);
3956                 break;;
3957             }
3958 
3959             // received random value
3960             reverse_128(&packet[1], setup->sm_peer_random);
3961             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
3962             break;
3963 #endif
3964 
3965         case SM_PH3_RECEIVE_KEYS:
3966             switch(sm_pdu_code){
3967                 case SM_CODE_ENCRYPTION_INFORMATION:
3968                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
3969                     reverse_128(&packet[1], setup->sm_peer_ltk);
3970                     break;
3971 
3972                 case SM_CODE_MASTER_IDENTIFICATION:
3973                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
3974                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
3975                     reverse_64(&packet[3], setup->sm_peer_rand);
3976                     break;
3977 
3978                 case SM_CODE_IDENTITY_INFORMATION:
3979                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
3980                     reverse_128(&packet[1], setup->sm_peer_irk);
3981                     break;
3982 
3983                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
3984                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
3985                     setup->sm_peer_addr_type = packet[1];
3986                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
3987                     break;
3988 
3989                 case SM_CODE_SIGNING_INFORMATION:
3990                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
3991                     reverse_128(&packet[1], setup->sm_peer_csrk);
3992                     break;
3993                 default:
3994                     // Unexpected PDU
3995                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
3996                     break;
3997             }
3998             // done with key distribution?
3999             if (sm_key_distribution_all_received(sm_conn)){
4000 
4001                 sm_key_distribution_handle_all_received(sm_conn);
4002 
4003                 if (IS_RESPONDER(sm_conn->sm_role)){
4004                     if (sm_ctkd_from_le()){
4005                         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_H6_ILK;
4006                     } else {
4007                         sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
4008                         sm_notify_client_status_reason(sm_conn, ERROR_CODE_SUCCESS, 0);
4009                         sm_done_for_handle(sm_conn->sm_handle);
4010                     }
4011                 } else {
4012                     if (setup->sm_use_secure_connections){
4013                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4014                     } else {
4015                         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);
4016                     }
4017                 }
4018             }
4019             break;
4020         default:
4021             // Unexpected PDU
4022             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
4023             break;
4024     }
4025 
4026     // try to send next pdu
4027     sm_trigger_run();
4028 }
4029 
4030 // Security Manager Client API
4031 void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
4032     sm_get_oob_data = get_oob_data_callback;
4033 }
4034 
4035 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)){
4036     sm_get_sc_oob_data = get_sc_oob_data_callback;
4037 }
4038 
4039 void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
4040     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
4041 }
4042 
4043 void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
4044     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
4045 }
4046 
4047 void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
4048 	sm_min_encryption_key_size = min_size;
4049 	sm_max_encryption_key_size = max_size;
4050 }
4051 
4052 void sm_set_authentication_requirements(uint8_t auth_req){
4053 #ifndef ENABLE_LE_SECURE_CONNECTIONS
4054     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
4055         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
4056         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
4057     }
4058 #endif
4059     sm_auth_req = auth_req;
4060 }
4061 
4062 void sm_set_io_capabilities(io_capability_t io_capability){
4063     sm_io_capabilities = io_capability;
4064 }
4065 
4066 #ifdef ENABLE_LE_PERIPHERAL
4067 void sm_set_request_security(int enable){
4068     sm_slave_request_security = enable;
4069 }
4070 #endif
4071 
4072 void sm_set_er(sm_key_t er){
4073     (void)memcpy(sm_persistent_er, er, 16);
4074 }
4075 
4076 void sm_set_ir(sm_key_t ir){
4077     (void)memcpy(sm_persistent_ir, ir, 16);
4078 }
4079 
4080 // Testing support only
4081 void sm_test_set_irk(sm_key_t irk){
4082     (void)memcpy(sm_persistent_irk, irk, 16);
4083     dkg_state = DKG_CALC_DHK;
4084     test_use_fixed_local_irk = true;
4085 }
4086 
4087 void sm_test_use_fixed_local_csrk(void){
4088     test_use_fixed_local_csrk = true;
4089 }
4090 
4091 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4092 static void sm_ec_generated(void * arg){
4093     UNUSED(arg);
4094     ec_key_generation_state = EC_KEY_GENERATION_DONE;
4095     // trigger pairing if pending for ec key
4096     sm_trigger_run();
4097 }
4098 static void sm_ec_generate_new_key(void){
4099     log_info("sm: generate new ec key");
4100     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4101     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4102 }
4103 #endif
4104 
4105 #ifdef ENABLE_TESTING_SUPPORT
4106 void sm_test_set_pairing_failure(int reason){
4107     test_pairing_failure = reason;
4108 }
4109 #endif
4110 
4111 void sm_init(void){
4112     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4113     sm_er_ir_set_default();
4114 
4115     // defaults
4116     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
4117                                        | SM_STK_GENERATION_METHOD_OOB
4118                                        | SM_STK_GENERATION_METHOD_PASSKEY
4119                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4120 
4121     sm_max_encryption_key_size = 16;
4122     sm_min_encryption_key_size = 7;
4123 
4124     sm_fixed_passkey_in_display_role = 0xffffffff;
4125     sm_reconstruct_ltk_without_le_device_db_entry = 1;
4126 
4127 #ifdef USE_CMAC_ENGINE
4128     sm_cmac_active  = 0;
4129 #endif
4130     dkg_state = DKG_W4_WORKING;
4131     rau_state = RAU_IDLE;
4132     sm_aes128_state = SM_AES128_IDLE;
4133     sm_address_resolution_test = -1;    // no private address to resolve yet
4134     sm_address_resolution_ah_calculation_active = 0;
4135     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
4136     sm_address_resolution_general_queue = NULL;
4137 
4138     gap_random_adress_update_period = 15 * 60 * 1000L;
4139     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
4140 
4141     test_use_fixed_local_csrk = false;
4142 
4143     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
4144 
4145     // register for HCI Events from HCI
4146     hci_event_callback_registration.callback = &sm_event_packet_handler;
4147     hci_add_event_handler(&hci_event_callback_registration);
4148 
4149     //
4150     btstack_crypto_init();
4151 
4152     // init le_device_db
4153     le_device_db_init();
4154 
4155     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4156     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4157 
4158 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4159     sm_ec_generate_new_key();
4160 #endif
4161 }
4162 
4163 void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
4164     sm_fixed_passkey_in_display_role = passkey;
4165 }
4166 
4167 void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
4168     sm_reconstruct_ltk_without_le_device_db_entry = allow;
4169 }
4170 
4171 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4172     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4173     if (!hci_con) return NULL;
4174     return &hci_con->sm_connection;
4175 }
4176 
4177 static void sm_send_security_request_for_connection(sm_connection_t * sm_conn){
4178     switch (sm_conn->sm_engine_state){
4179         case SM_GENERAL_IDLE:
4180         case SM_RESPONDER_IDLE:
4181             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
4182             sm_trigger_run();
4183             break;
4184         default:
4185             break;
4186     }
4187 }
4188 
4189 /**
4190  * @brief Trigger Security Request
4191  */
4192 void sm_send_security_request(hci_con_handle_t con_handle){
4193     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4194     if (!sm_conn) return;
4195     sm_send_security_request_for_connection(sm_conn);
4196 }
4197 
4198 // request pairing
4199 void sm_request_pairing(hci_con_handle_t con_handle){
4200     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4201     if (!sm_conn) return;     // wrong connection
4202 
4203     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
4204     if (IS_RESPONDER(sm_conn->sm_role)){
4205         sm_send_security_request_for_connection(sm_conn);
4206     } else {
4207         // used as a trigger to start central/master/initiator security procedures
4208         if (sm_conn->sm_engine_state == SM_INITIATOR_CONNECTED){
4209             uint8_t ltk[16];
4210             bool have_ltk;
4211             switch (sm_conn->sm_irk_lookup_state){
4212                 case IRK_LOOKUP_SUCCEEDED:
4213 #ifndef ENABLE_LE_CENTRAL_AUTO_ENCRYPTION
4214                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4215                     have_ltk = !sm_is_null_key(ltk);
4216                     log_info("have ltk %u", have_ltk);
4217                     if (have_ltk){
4218                         sm_conn->sm_pairing_requested = 1;
4219                         sm_conn->sm_engine_state = SM_INITIATOR_PH0_HAS_LTK;
4220                         break;
4221                     }
4222 #endif
4223                     /* fall through */
4224 
4225                 case IRK_LOOKUP_FAILED:
4226                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4227                     break;
4228                 default:
4229                     log_info("irk lookup pending");
4230                     sm_conn->sm_pairing_requested = 1;
4231                     break;
4232             }
4233         } else if (sm_conn->sm_engine_state == SM_GENERAL_IDLE){
4234             sm_conn->sm_pairing_requested = 1;
4235         }
4236     }
4237     sm_trigger_run();
4238 }
4239 
4240 // called by client app on authorization request
4241 void sm_authorization_decline(hci_con_handle_t con_handle){
4242     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4243     if (!sm_conn) return;     // wrong connection
4244     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4245     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0);
4246 }
4247 
4248 void sm_authorization_grant(hci_con_handle_t con_handle){
4249     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4250     if (!sm_conn) return;     // wrong connection
4251     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4252     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1);
4253 }
4254 
4255 // GAP Bonding API
4256 
4257 void sm_bonding_decline(hci_con_handle_t con_handle){
4258     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4259     if (!sm_conn) return;     // wrong connection
4260     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
4261     log_info("decline, state %u", sm_conn->sm_engine_state);
4262     switch(sm_conn->sm_engine_state){
4263 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4264         case SM_SC_W4_USER_RESPONSE:
4265         case SM_SC_W4_CONFIRMATION:
4266         case SM_SC_W4_PUBLIC_KEY_COMMAND:
4267 #endif
4268         case SM_PH1_W4_USER_RESPONSE:
4269             switch (setup->sm_stk_generation_method){
4270                 case PK_RESP_INPUT:
4271                 case PK_INIT_INPUT:
4272                 case PK_BOTH_INPUT:
4273                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4274                     break;
4275                 case NUMERIC_COMPARISON:
4276                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4277                     break;
4278                 case JUST_WORKS:
4279                 case OOB:
4280                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4281                     break;
4282             }
4283             break;
4284         default:
4285             break;
4286     }
4287     sm_trigger_run();
4288 }
4289 
4290 void sm_just_works_confirm(hci_con_handle_t con_handle){
4291     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4292     if (!sm_conn) return;     // wrong connection
4293     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
4294     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4295         if (setup->sm_use_secure_connections){
4296             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4297         } else {
4298             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);
4299         }
4300     }
4301 
4302 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4303     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4304         sm_sc_prepare_dhkey_check(sm_conn);
4305     }
4306 #endif
4307 
4308     sm_trigger_run();
4309 }
4310 
4311 void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4312     // for now, it's the same
4313     sm_just_works_confirm(con_handle);
4314 }
4315 
4316 void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4317     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4318     if (!sm_conn) return;     // wrong connection
4319     sm_reset_tk();
4320     big_endian_store_32(setup->sm_tk, 12, passkey);
4321     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
4322     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4323         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);
4324     }
4325 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4326     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
4327     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
4328     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4329         sm_sc_start_calculating_local_confirm(sm_conn);
4330     }
4331 #endif
4332     sm_trigger_run();
4333 }
4334 
4335 void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
4336     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4337     if (!sm_conn) return;     // wrong connection
4338     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4339     uint8_t num_actions = setup->sm_keypress_notification >> 5;
4340     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4341     switch (action){
4342         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4343         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
4344             flags |= (1u << action);
4345             break;
4346         case SM_KEYPRESS_PASSKEY_CLEARED:
4347             // clear counter, keypress & erased flags + set passkey cleared
4348             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4349             break;
4350         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
4351             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4352                 // erase actions queued
4353                 num_actions--;
4354                 if (num_actions == 0u){
4355                     // clear counter, keypress & erased flags
4356                     flags &= 0x19u;
4357                 }
4358                 break;
4359             }
4360             num_actions++;
4361             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
4362             break;
4363         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
4364             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
4365                 // enter actions queued
4366                 num_actions--;
4367                 if (num_actions == 0u){
4368                     // clear counter, keypress & erased flags
4369                     flags &= 0x19u;
4370                 }
4371                 break;
4372             }
4373             num_actions++;
4374             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
4375             break;
4376         default:
4377             break;
4378     }
4379     setup->sm_keypress_notification = (num_actions << 5) | flags;
4380     sm_trigger_run();
4381 }
4382 
4383 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4384 static void sm_handle_random_result_oob(void * arg){
4385     UNUSED(arg);
4386     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
4387     sm_trigger_run();
4388 }
4389 uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
4390 
4391     static btstack_crypto_random_t   sm_crypto_random_oob_request;
4392 
4393     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4394     sm_sc_oob_callback = callback;
4395     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
4396     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
4397     return 0;
4398 }
4399 #endif
4400 
4401 /**
4402  * @brief Get Identity Resolving state
4403  * @param con_handle
4404  * @return irk_lookup_state_t
4405  */
4406 irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
4407     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4408     if (!sm_conn) return IRK_LOOKUP_IDLE;
4409     return sm_conn->sm_irk_lookup_state;
4410 }
4411 
4412 /**
4413  * @brief Identify device in LE Device DB
4414  * @param handle
4415  * @returns index from le_device_db or -1 if not found/identified
4416  */
4417 int sm_le_device_index(hci_con_handle_t con_handle ){
4418     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4419     if (!sm_conn) return -1;
4420     return sm_conn->sm_le_db_index;
4421 }
4422 
4423 static int gap_random_address_type_requires_updates(void){
4424     switch (gap_random_adress_type){
4425         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4426         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
4427             return 0;
4428         default:
4429             return 1;
4430     }
4431 }
4432 
4433 static uint8_t own_address_type(void){
4434     switch (gap_random_adress_type){
4435         case GAP_RANDOM_ADDRESS_TYPE_OFF:
4436             return BD_ADDR_TYPE_LE_PUBLIC;
4437         default:
4438             return BD_ADDR_TYPE_LE_RANDOM;
4439     }
4440 }
4441 
4442 // GAP LE API
4443 void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
4444     gap_random_address_update_stop();
4445     gap_random_adress_type = random_address_type;
4446     hci_le_set_own_address_type(own_address_type());
4447     if (!gap_random_address_type_requires_updates()) return;
4448     gap_random_address_update_start();
4449     gap_random_address_trigger();
4450 }
4451 
4452 gap_random_address_type_t gap_random_address_get_mode(void){
4453     return gap_random_adress_type;
4454 }
4455 
4456 void gap_random_address_set_update_period(int period_ms){
4457     gap_random_adress_update_period = period_ms;
4458     if (!gap_random_address_type_requires_updates()) return;
4459     gap_random_address_update_stop();
4460     gap_random_address_update_start();
4461 }
4462 
4463 void gap_random_address_set(const bd_addr_t addr){
4464     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
4465     (void)memcpy(sm_random_address, addr, 6);
4466     rau_state = RAU_SET_ADDRESS;
4467     sm_trigger_run();
4468 }
4469 
4470 #ifdef ENABLE_LE_PERIPHERAL
4471 /*
4472  * @brief Set Advertisement Paramters
4473  * @param adv_int_min
4474  * @param adv_int_max
4475  * @param adv_type
4476  * @param direct_address_type
4477  * @param direct_address
4478  * @param channel_map
4479  * @param filter_policy
4480  *
4481  * @note own_address_type is used from gap_random_address_set_mode
4482  */
4483 void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4484     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
4485     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
4486         direct_address_typ, direct_address, channel_map, filter_policy);
4487 }
4488 #endif
4489 
4490 int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
4491     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4492      // wrong connection
4493     if (!sm_conn) return 0;
4494     // already encrypted
4495     if (sm_conn->sm_connection_encrypted) return 0;
4496     // only central can re-encrypt
4497     if (sm_conn->sm_role == HCI_ROLE_SLAVE) return 0;
4498     // irk status?
4499     switch(sm_conn->sm_irk_lookup_state){
4500         case IRK_LOOKUP_FAILED:
4501             // done, cannot setup encryption
4502             return 0;
4503         case IRK_LOOKUP_SUCCEEDED:
4504             break;
4505         default:
4506             // IR Lookup pending
4507             return 1;
4508     }
4509     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset
4510     return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
4511 }
4512 
4513 void sm_set_secure_connections_only_mode(bool enable){
4514 #ifdef ENABLE_LE_SECURE_CONNECTIONS
4515     sm_sc_only_mode = enable;
4516 #else
4517     // SC Only mode not possible without support for SC
4518     btstack_assert(enable == false);
4519 #endif
4520 }
4521 
4522 const uint8_t * gap_get_persistent_irk(void){
4523     return sm_persistent_irk;
4524 }
4525