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