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