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