xref: /btstack/src/ble/sm.c (revision f82b8f4bf298eb90da2419f58d7aeb355e687200)
13deb3ec6SMatthias Ringwald /*
23deb3ec6SMatthias Ringwald  * Copyright (C) 2014 BlueKitchen GmbH
33deb3ec6SMatthias Ringwald  *
43deb3ec6SMatthias Ringwald  * Redistribution and use in source and binary forms, with or without
53deb3ec6SMatthias Ringwald  * modification, are permitted provided that the following conditions
63deb3ec6SMatthias Ringwald  * are met:
73deb3ec6SMatthias Ringwald  *
83deb3ec6SMatthias Ringwald  * 1. Redistributions of source code must retain the above copyright
93deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer.
103deb3ec6SMatthias Ringwald  * 2. Redistributions in binary form must reproduce the above copyright
113deb3ec6SMatthias Ringwald  *    notice, this list of conditions and the following disclaimer in the
123deb3ec6SMatthias Ringwald  *    documentation and/or other materials provided with the distribution.
133deb3ec6SMatthias Ringwald  * 3. Neither the name of the copyright holders nor the names of
143deb3ec6SMatthias Ringwald  *    contributors may be used to endorse or promote products derived
153deb3ec6SMatthias Ringwald  *    from this software without specific prior written permission.
163deb3ec6SMatthias Ringwald  * 4. Any redistribution, use, or modification is done solely for
173deb3ec6SMatthias Ringwald  *    personal benefit and not for any commercial purpose or for
183deb3ec6SMatthias Ringwald  *    monetary gain.
193deb3ec6SMatthias Ringwald  *
203deb3ec6SMatthias Ringwald  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
213deb3ec6SMatthias Ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
223deb3ec6SMatthias Ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
232fca4dadSMilanka Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
242fca4dadSMilanka Ringwald  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
253deb3ec6SMatthias Ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
263deb3ec6SMatthias Ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
273deb3ec6SMatthias Ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
283deb3ec6SMatthias Ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
293deb3ec6SMatthias Ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
303deb3ec6SMatthias Ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
313deb3ec6SMatthias Ringwald  * SUCH DAMAGE.
323deb3ec6SMatthias Ringwald  *
333deb3ec6SMatthias Ringwald  * Please inquire about commercial licensing options at
343deb3ec6SMatthias Ringwald  * [email protected]
353deb3ec6SMatthias Ringwald  *
363deb3ec6SMatthias Ringwald  */
37ab2c6ae4SMatthias Ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "sm.c"
393deb3ec6SMatthias Ringwald 
403deb3ec6SMatthias Ringwald #include <string.h>
413deb3ec6SMatthias Ringwald #include <inttypes.h>
423deb3ec6SMatthias Ringwald 
433edc84c5SMatthias Ringwald #include "ble/le_device_db.h"
4459c6af15SMatthias Ringwald #include "ble/core.h"
453edc84c5SMatthias Ringwald #include "ble/sm.h"
4661f37892SMatthias Ringwald #include "bluetooth_company_id.h"
47d7f1c72eSMatthias Ringwald #include "btstack_bool.h"
48d1a1f6a4SMatthias Ringwald #include "btstack_crypto.h"
490e2df43fSMatthias Ringwald #include "btstack_debug.h"
500e2df43fSMatthias Ringwald #include "btstack_event.h"
510e2df43fSMatthias Ringwald #include "btstack_linked_list.h"
520e2df43fSMatthias Ringwald #include "btstack_memory.h"
53899e6e02SMatthias Ringwald #include "btstack_tlv.h"
54f7a05cdaSMatthias Ringwald #include "gap.h"
550e2df43fSMatthias Ringwald #include "hci.h"
5613377825SMatthias Ringwald #include "hci_dump.h"
570e2df43fSMatthias Ringwald #include "l2cap.h"
583deb3ec6SMatthias Ringwald 
591a682202SMatthias Ringwald #if !defined(ENABLE_LE_PERIPHERAL) && !defined(ENABLE_LE_CENTRAL)
601a682202SMatthias Ringwald #error "LE Security Manager used, but neither ENABLE_LE_PERIPHERAL nor ENABLE_LE_CENTRAL defined. Please add at least one to btstack_config.h."
611a682202SMatthias Ringwald #endif
621a682202SMatthias Ringwald 
637ece0eaaSMatthias Ringwald #if defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION) && (!defined(ENABLE_CLASSIC) || !defined(ENABLE_LE_SECURE_CONNECTIONS))
647ece0eaaSMatthias Ringwald #error "Cross Transport Key Derivation requires support for LE Secure Connections and BR/EDR (Classic)"
656857ad8fSMatthias Ringwald #endif
666857ad8fSMatthias Ringwald 
67d1a1f6a4SMatthias Ringwald // assert SM Public Key can be sent/received
68d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
69d1a1f6a4SMatthias Ringwald #if HCI_ACL_PAYLOAD_SIZE < 69
70d1a1f6a4SMatthias Ringwald #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"
71d1a1f6a4SMatthias Ringwald #endif
72d1a1f6a4SMatthias Ringwald #endif
73d1a1f6a4SMatthias Ringwald 
7442134bc6SMatthias Ringwald #if defined(ENABLE_LE_PERIPHERAL) && defined(ENABLE_LE_CENTRAL)
7542134bc6SMatthias Ringwald #define IS_RESPONDER(role) (role)
7642134bc6SMatthias Ringwald #else
7742134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
7842134bc6SMatthias Ringwald // only central - never responder (avoid 'unused variable' warnings)
7942134bc6SMatthias Ringwald #define IS_RESPONDER(role) (0 && role)
8042134bc6SMatthias Ringwald #else
8142134bc6SMatthias Ringwald // only peripheral - always responder (avoid 'unused variable' warnings)
8242134bc6SMatthias Ringwald #define IS_RESPONDER(role) (1 || role)
8342134bc6SMatthias Ringwald #endif
8442134bc6SMatthias Ringwald #endif
8542134bc6SMatthias Ringwald 
867a766ebfSMatthias Ringwald #if defined(ENABLE_LE_SIGNED_WRITE) || defined(ENABLE_LE_SECURE_CONNECTIONS)
87d1a1f6a4SMatthias Ringwald #define USE_CMAC_ENGINE
887a766ebfSMatthias Ringwald #endif
897a766ebfSMatthias Ringwald 
906857ad8fSMatthias Ringwald 
91968b2eafSMatthias Ringwald #define BTSTACK_TAG32(A,B,C,D) (((A) << 24) | ((B) << 16) | ((C) << 8) | (D))
92899e6e02SMatthias Ringwald 
933deb3ec6SMatthias Ringwald //
943deb3ec6SMatthias Ringwald // SM internal types and globals
953deb3ec6SMatthias Ringwald //
963deb3ec6SMatthias Ringwald 
973deb3ec6SMatthias Ringwald typedef enum {
983deb3ec6SMatthias Ringwald     DKG_W4_WORKING,
993deb3ec6SMatthias Ringwald     DKG_CALC_IRK,
1003deb3ec6SMatthias Ringwald     DKG_CALC_DHK,
1013deb3ec6SMatthias Ringwald     DKG_READY
1023deb3ec6SMatthias Ringwald } derived_key_generation_t;
1033deb3ec6SMatthias Ringwald 
1043deb3ec6SMatthias Ringwald typedef enum {
1053deb3ec6SMatthias Ringwald     RAU_IDLE,
106fbd4e238SMatthias Ringwald     RAU_GET_RANDOM,
1073deb3ec6SMatthias Ringwald     RAU_W4_RANDOM,
1083deb3ec6SMatthias Ringwald     RAU_GET_ENC,
1093deb3ec6SMatthias Ringwald     RAU_W4_ENC,
1103deb3ec6SMatthias Ringwald } random_address_update_t;
1113deb3ec6SMatthias Ringwald 
1123deb3ec6SMatthias Ringwald typedef enum {
1133deb3ec6SMatthias Ringwald     CMAC_IDLE,
1143deb3ec6SMatthias Ringwald     CMAC_CALC_SUBKEYS,
1153deb3ec6SMatthias Ringwald     CMAC_W4_SUBKEYS,
1163deb3ec6SMatthias Ringwald     CMAC_CALC_MI,
1173deb3ec6SMatthias Ringwald     CMAC_W4_MI,
1183deb3ec6SMatthias Ringwald     CMAC_CALC_MLAST,
1193deb3ec6SMatthias Ringwald     CMAC_W4_MLAST
1203deb3ec6SMatthias Ringwald } cmac_state_t;
1213deb3ec6SMatthias Ringwald 
1223deb3ec6SMatthias Ringwald typedef enum {
1233deb3ec6SMatthias Ringwald     JUST_WORKS,
12427c32905SMatthias Ringwald     PK_RESP_INPUT,       // Initiator displays PK, responder inputs PK
12527c32905SMatthias Ringwald     PK_INIT_INPUT,       // Responder displays PK, initiator inputs PK
12647fb4255SMatthias Ringwald     PK_BOTH_INPUT,       // Only input on both, both input PK
12747fb4255SMatthias Ringwald     NUMERIC_COMPARISON,  // Only numerical compparison (yes/no) on on both sides
12847fb4255SMatthias Ringwald     OOB                  // OOB available on one (SC) or both sides (legacy)
1293deb3ec6SMatthias Ringwald } stk_generation_method_t;
1303deb3ec6SMatthias Ringwald 
1313deb3ec6SMatthias Ringwald typedef enum {
1323deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_IDLE,
1333deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PENDING,
1343deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_CONFIRM,
1353deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_PASSKEY,
1363deb3ec6SMatthias Ringwald     SM_USER_RESPONSE_DECLINE
1373deb3ec6SMatthias Ringwald } sm_user_response_t;
1383deb3ec6SMatthias Ringwald 
1393deb3ec6SMatthias Ringwald typedef enum {
1403deb3ec6SMatthias Ringwald     SM_AES128_IDLE,
1413deb3ec6SMatthias Ringwald     SM_AES128_ACTIVE
1423deb3ec6SMatthias Ringwald } sm_aes128_state_t;
1433deb3ec6SMatthias Ringwald 
1443deb3ec6SMatthias Ringwald typedef enum {
1453deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_IDLE,
1463deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_GENERAL,
1473deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FOR_CONNECTION,
1483deb3ec6SMatthias Ringwald } address_resolution_mode_t;
1493deb3ec6SMatthias Ringwald 
1503deb3ec6SMatthias Ringwald typedef enum {
151a66b030fSMatthias Ringwald     ADDRESS_RESOLUTION_SUCCEEDED,
1523deb3ec6SMatthias Ringwald     ADDRESS_RESOLUTION_FAILED,
1533deb3ec6SMatthias Ringwald } address_resolution_event_t;
154901c000fSMatthias Ringwald 
155901c000fSMatthias Ringwald typedef enum {
15634b6528fSMatthias Ringwald     EC_KEY_GENERATION_IDLE,
1577df18c15SMatthias Ringwald     EC_KEY_GENERATION_ACTIVE,
1587df18c15SMatthias Ringwald     EC_KEY_GENERATION_DONE,
1597df18c15SMatthias Ringwald } ec_key_generation_state_t;
1607df18c15SMatthias Ringwald 
1617df18c15SMatthias Ringwald typedef enum {
1623cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_NEEDED = 1 << 0,
1633cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_CALCULATED = 1 << 1,
1643cf37b8cSMatthias Ringwald     SM_STATE_VAR_DHKEY_COMMAND_RECEIVED = 1 << 2,
165901c000fSMatthias Ringwald } sm_state_var_t;
166901c000fSMatthias Ringwald 
167c59d0c92SMatthias Ringwald typedef enum {
168c59d0c92SMatthias Ringwald     SM_SC_OOB_IDLE,
169d1a1f6a4SMatthias Ringwald     SM_SC_OOB_W4_RANDOM,
170c59d0c92SMatthias Ringwald     SM_SC_OOB_W2_CALC_CONFIRM,
171c59d0c92SMatthias Ringwald     SM_SC_OOB_W4_CONFIRM,
172c59d0c92SMatthias Ringwald } sm_sc_oob_state_t;
173c59d0c92SMatthias Ringwald 
1746420f61eSMatthias Ringwald typedef uint8_t sm_key24_t[3];
1756420f61eSMatthias Ringwald typedef uint8_t sm_key56_t[7];
1766420f61eSMatthias Ringwald typedef uint8_t sm_key256_t[32];
1776420f61eSMatthias Ringwald 
1783deb3ec6SMatthias Ringwald //
1793deb3ec6SMatthias Ringwald // GLOBAL DATA
1803deb3ec6SMatthias Ringwald //
1813deb3ec6SMatthias Ringwald 
1822d2d4d3cSMatthias Ringwald static bool sm_initialized;
1832d2d4d3cSMatthias Ringwald 
184841468bbSMatthias Ringwald static bool test_use_fixed_local_csrk;
185841468bbSMatthias Ringwald static bool test_use_fixed_local_irk;
1863deb3ec6SMatthias Ringwald 
187192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
188192365feSMatthias Ringwald static uint8_t test_pairing_failure;
189192365feSMatthias Ringwald #endif
190192365feSMatthias Ringwald 
1913deb3ec6SMatthias Ringwald // configuration
1923deb3ec6SMatthias Ringwald static uint8_t sm_accepted_stk_generation_methods;
1933deb3ec6SMatthias Ringwald static uint8_t sm_max_encryption_key_size;
1943deb3ec6SMatthias Ringwald static uint8_t sm_min_encryption_key_size;
1953deb3ec6SMatthias Ringwald static uint8_t sm_auth_req = 0;
1963deb3ec6SMatthias Ringwald static uint8_t sm_io_capabilities = IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1974b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
1981979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
1993deb3ec6SMatthias Ringwald 
200b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
201b6f39a74SMatthias Ringwald static uint8_t sm_slave_request_security;
202b6f39a74SMatthias Ringwald #endif
203b6f39a74SMatthias Ringwald 
204c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
205c123d999SMatthias Ringwald static bool sm_sc_only_mode;
206c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
207c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
208c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
209c59d0c92SMatthias Ringwald #endif
210c59d0c92SMatthias Ringwald 
211899e6e02SMatthias Ringwald 
2121979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
213899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
214899e6e02SMatthias Ringwald static void *                sm_tlv_context;
215899e6e02SMatthias Ringwald 
2163deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2173deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2183deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2193deb3ec6SMatthias Ringwald 
2203deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2213deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2223deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2233deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2243deb3ec6SMatthias Ringwald 
2253deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2263deb3ec6SMatthias Ringwald // ..
2273deb3ec6SMatthias Ringwald 
2283deb3ec6SMatthias Ringwald // random address update
2293deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2303deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2313deb3ec6SMatthias Ringwald 
232d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
233514d35fcSMatthias Ringwald // CMAC Calculation: General
234d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
235d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
236d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
237d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2387a766ebfSMatthias Ringwald #endif
239514d35fcSMatthias Ringwald 
240514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2417a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
242d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
243d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
244d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
245d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2467a766ebfSMatthias Ringwald #endif
247514d35fcSMatthias Ringwald 
248514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
249514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
250aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
251514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
252514d35fcSMatthias Ringwald #endif
2533deb3ec6SMatthias Ringwald 
2543deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2553deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2563deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2573deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2583deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2593deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2608f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2613deb3ec6SMatthias Ringwald 
262d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2633deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2643deb3ec6SMatthias Ringwald 
265d1a1f6a4SMatthias Ringwald // crypto
266d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
267d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
268d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
269d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2707df1ef2fSMatthias Ringwald #endif
2717df1ef2fSMatthias Ringwald 
272d1a1f6a4SMatthias Ringwald // temp storage for random data
273d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
274d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
275d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
276d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2773deb3ec6SMatthias Ringwald 
278a036ae12SMatthias Ringwald // to receive events
279e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
280a036ae12SMatthias Ringwald static btstack_packet_callback_registration_t l2cap_event_callback_registration;
281e03e489aSMatthias Ringwald 
28289a78d34SMatthias Ringwald /* to dispatch sm event */
28389a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28489a78d34SMatthias Ringwald 
285ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
286ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
287ece00d2dSMatthias Ringwald 
28809e4d397SMatthias Ringwald // LE Secure Connections
28909e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
29009e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
291fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
29209e4d397SMatthias Ringwald #endif
293df86eb96SMatthias Ringwald 
2943deb3ec6SMatthias Ringwald //
2953deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2963deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2973deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2983deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2993deb3ec6SMatthias Ringwald //
3003deb3ec6SMatthias Ringwald 
3013deb3ec6SMatthias Ringwald // data needed for security setup
3023deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3033deb3ec6SMatthias Ringwald 
304ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3053deb3ec6SMatthias Ringwald 
3063deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3073deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
308dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3093deb3ec6SMatthias Ringwald 
3103deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
312715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3139a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
314715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3153deb3ec6SMatthias Ringwald 
3163deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3173deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3183deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
319a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
32027c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3213deb3ec6SMatthias Ringwald 
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3233deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3243deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3263deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3273deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3283deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3293deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3303deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3313deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3323deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3333deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3343deb3ec6SMatthias Ringwald 
33568437d83SMatthias Ringwald     uint8_t   sm_state_vars;
336e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
337fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
338446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
339446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
340d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
341e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
342e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
343446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
344446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3452bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
346a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3477df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
348e53be891SMatthias Ringwald #endif
34927c32905SMatthias Ringwald 
3503deb3ec6SMatthias Ringwald     // Phase 3
3513deb3ec6SMatthias Ringwald 
3523deb3ec6SMatthias Ringwald     // key distribution, we generate
3533deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3543deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3553deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3563deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3573deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3583deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3593deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3603deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3613deb3ec6SMatthias Ringwald 
3623deb3ec6SMatthias Ringwald     // key distribution, received from peer
3633deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3643deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3653deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3663deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3673deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3683deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3693deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3703deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3713deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
372715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
373715a43d1SMatthias Ringwald     int       sm_le_device_index;
374715a43d1SMatthias Ringwald #endif
375e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
376e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
377e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
378e0a03c85SMatthias Ringwald #endif
3793deb3ec6SMatthias Ringwald } sm_setup_context_t;
3803deb3ec6SMatthias Ringwald 
3813deb3ec6SMatthias Ringwald //
3823deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3833deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3843deb3ec6SMatthias Ringwald 
3853deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3867149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3873deb3ec6SMatthias Ringwald 
3886b65794dSMilanka Ringwald // @return 1 if oob data is available
3893deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3903deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3914acf7b7bSMatthias Ringwald 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);
392b96d60a6SMatthias Ringwald static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk);
3933deb3ec6SMatthias Ringwald 
3943deb3ec6SMatthias Ringwald static void sm_run(void);
3957887cd92SMatthias Ringwald static void sm_state_reset(void);
396711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
397711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
398916ea5b2SMatthias Ringwald static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk);
39977e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
40077e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
40177e2e5edSMatthias Ringwald #endif
4023deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
4033deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
412d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4142a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
415d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
416d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4172a526f21SMatthias Ringwald #endif
418d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
419d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
420d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
421d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
422d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4236d80b495SMatthias Ringwald 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));
42434b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4256ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4266ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4272a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
428d1a1f6a4SMatthias Ringwald #endif
4290ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4303deb3ec6SMatthias Ringwald 
4313deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4323deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4333deb3ec6SMatthias Ringwald }
4343deb3ec6SMatthias Ringwald 
4351fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4361fbd72c5SMatthias Ringwald //     return packet[0];
4371fbd72c5SMatthias Ringwald // }
4381fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4391fbd72c5SMatthias Ringwald     return packet[1];
4401fbd72c5SMatthias Ringwald }
4411fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4421fbd72c5SMatthias Ringwald     return packet[2];
4431fbd72c5SMatthias Ringwald }
4441fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4451fbd72c5SMatthias Ringwald     return packet[3];
4461fbd72c5SMatthias Ringwald }
4471fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4481fbd72c5SMatthias Ringwald     return packet[4];
4491fbd72c5SMatthias Ringwald }
4501fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4511fbd72c5SMatthias Ringwald     return packet[5];
4521fbd72c5SMatthias Ringwald }
4531fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4541fbd72c5SMatthias Ringwald     return packet[6];
4551fbd72c5SMatthias Ringwald }
4561fbd72c5SMatthias Ringwald 
4571fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4581fbd72c5SMatthias Ringwald     packet[0] = code;
4591fbd72c5SMatthias Ringwald }
4601fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4611fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4621fbd72c5SMatthias Ringwald }
4631fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4641fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4651fbd72c5SMatthias Ringwald }
4661fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4671fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4681fbd72c5SMatthias Ringwald }
4691fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4701fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4711fbd72c5SMatthias Ringwald }
4721fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4731fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4741fbd72c5SMatthias Ringwald }
4751fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4761fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4771fbd72c5SMatthias Ringwald }
4781fbd72c5SMatthias Ringwald 
4791979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
48024c4191dSMatthias Ringwald     return btstack_is_null(random, 8);
4813764b551SMatthias Ringwald }
4823764b551SMatthias Ringwald 
4831979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
48424c4191dSMatthias Ringwald     return btstack_is_null(key, 16);
4853764b551SMatthias Ringwald }
4863764b551SMatthias Ringwald 
48770b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
48870b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
48970b44dd4SMatthias Ringwald 	UNUSED(ts);
49070b44dd4SMatthias Ringwald 	sm_run();
49170b44dd4SMatthias Ringwald }
49270b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4932d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49484c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
49570b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
49670b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
49770b44dd4SMatthias Ringwald }
49870b44dd4SMatthias Ringwald 
4993deb3ec6SMatthias Ringwald // Key utils
5003deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5013deb3ec6SMatthias Ringwald     int i;
5023deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5033deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5043deb3ec6SMatthias Ringwald     }
5053deb3ec6SMatthias Ringwald }
5063deb3ec6SMatthias Ringwald 
5073deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5083deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5093deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5103deb3ec6SMatthias Ringwald     int i;
5113deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5123deb3ec6SMatthias Ringwald         key[15-i] = 0;
5133deb3ec6SMatthias Ringwald     }
5143deb3ec6SMatthias Ringwald }
5153deb3ec6SMatthias Ringwald 
516899e6e02SMatthias Ringwald // ER / IR checks
51721045273SMatthias Ringwald static void sm_er_ir_set_default(void){
518899e6e02SMatthias Ringwald     int i;
519899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
520899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
521899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
522899e6e02SMatthias Ringwald     }
523899e6e02SMatthias Ringwald }
524899e6e02SMatthias Ringwald 
525899e6e02SMatthias Ringwald static int sm_er_is_default(void){
526899e6e02SMatthias Ringwald     int i;
527899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
528899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
529899e6e02SMatthias Ringwald     }
530899e6e02SMatthias Ringwald     return 1;
531899e6e02SMatthias Ringwald }
532899e6e02SMatthias Ringwald 
533899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
534899e6e02SMatthias Ringwald     int i;
535899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
536899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
537899e6e02SMatthias Ringwald     }
538899e6e02SMatthias Ringwald     return 1;
539899e6e02SMatthias Ringwald }
540899e6e02SMatthias Ringwald 
54173102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54273102768SMatthias Ringwald     UNUSED(channel);
54373102768SMatthias Ringwald 
54473102768SMatthias Ringwald     // log event
54573102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
54673102768SMatthias Ringwald     // dispatch to all event handlers
54773102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
54873102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
54973102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55073102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55173102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55273102768SMatthias Ringwald     }
55373102768SMatthias Ringwald }
55473102768SMatthias Ringwald 
55573102768SMatthias Ringwald 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){
55673102768SMatthias Ringwald     event[0] = type;
55773102768SMatthias Ringwald     event[1] = event_size - 2;
55873102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
55973102768SMatthias Ringwald     event[4] = addr_type;
56073102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56173102768SMatthias Ringwald }
56273102768SMatthias Ringwald 
56373102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56473102768SMatthias Ringwald     uint8_t event[11];
56573102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
56673102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
56773102768SMatthias Ringwald }
56873102768SMatthias Ringwald 
56973102768SMatthias Ringwald 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){
57073102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
57173102768SMatthias Ringwald     bd_addr_t identity_address;
57273102768SMatthias Ringwald     int identity_address_type;
57373102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
57473102768SMatthias Ringwald 
57573102768SMatthias Ringwald     uint8_t event[20];
57673102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57773102768SMatthias Ringwald     event[11] = identity_address_type;
57873102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
57973102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
58073102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58173102768SMatthias Ringwald }
58273102768SMatthias Ringwald 
58373102768SMatthias Ringwald 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){
58473102768SMatthias Ringwald     uint8_t event[12];
58573102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58673102768SMatthias Ringwald     event[11] = status;
58773102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
58873102768SMatthias Ringwald }
58973102768SMatthias Ringwald 
59073102768SMatthias Ringwald 
59173102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
59273102768SMatthias Ringwald 
5933ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
5943ab61f77SMatthias Ringwald 
5957b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
59673102768SMatthias Ringwald 
59773102768SMatthias Ringwald     int       identity_addr_type;
59873102768SMatthias Ringwald     bd_addr_t identity_addr;
5993c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6003c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
60173102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6023c0e26deSMatthias Ringwald     } else {
6033c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6043c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6053c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6063c0e26deSMatthias Ringwald     }
60773102768SMatthias Ringwald 
60873102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
60973102768SMatthias Ringwald }
61073102768SMatthias Ringwald 
61173102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
61273102768SMatthias Ringwald 
61360be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
61460be5b21SMatthias Ringwald 
6157b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
61673102768SMatthias Ringwald 
61773102768SMatthias Ringwald     int       identity_addr_type;
61873102768SMatthias Ringwald     bd_addr_t identity_addr;
6193c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6203c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
62173102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6223c0e26deSMatthias Ringwald     } else {
6233c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6243c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6253c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6263c0e26deSMatthias Ringwald     }
62773102768SMatthias Ringwald 
62873102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
62973102768SMatthias Ringwald }
63073102768SMatthias Ringwald 
631d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
632d3c12277SMatthias Ringwald 
633d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
634d3c12277SMatthias Ringwald 
635d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
636d3c12277SMatthias Ringwald 
637d3c12277SMatthias Ringwald     uint8_t event[11];
638d3c12277SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_STARTED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
639d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
640d3c12277SMatthias Ringwald }
641d3c12277SMatthias Ringwald 
6420ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
643f61072f5SMatthias Ringwald 
644d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
645d77906ffSMatthias Ringwald 
64669f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
64769f82ad8SMatthias Ringwald 
6480ccf6c9cSMatthias Ringwald     uint8_t event[13];
6490ccf6c9cSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), SM_EVENT_PAIRING_COMPLETE, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address);
6500ccf6c9cSMatthias Ringwald     event[11] = status;
6510ccf6c9cSMatthias Ringwald     event[12] = reason;
6520ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6530ccf6c9cSMatthias Ringwald }
6540ccf6c9cSMatthias Ringwald 
6553deb3ec6SMatthias Ringwald // SMP Timeout implementation
6563deb3ec6SMatthias Ringwald 
6573deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6583deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6593deb3ec6SMatthias Ringwald //
6603deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6613deb3ec6SMatthias Ringwald //
6623deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6633deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6643deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6653deb3ec6SMatthias Ringwald // established.
6663deb3ec6SMatthias Ringwald 
667ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6683deb3ec6SMatthias Ringwald     log_info("SM timeout");
669c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6703deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
67168a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6720ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6733deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6743deb3ec6SMatthias Ringwald 
6753deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6763deb3ec6SMatthias Ringwald     sm_run();
6773deb3ec6SMatthias Ringwald }
6783deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
679528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
68091a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
681528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
682528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
683528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6843deb3ec6SMatthias Ringwald }
6853deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
686528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6873deb3ec6SMatthias Ringwald }
6883deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
6893deb3ec6SMatthias Ringwald     sm_timeout_stop();
6903deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
6913deb3ec6SMatthias Ringwald }
6923deb3ec6SMatthias Ringwald 
6933deb3ec6SMatthias Ringwald // end of sm timeout
6943deb3ec6SMatthias Ringwald 
6953deb3ec6SMatthias Ringwald // GAP Random Address updates
6963deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
697ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
6983deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
6993deb3ec6SMatthias Ringwald 
7003deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
701899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
702d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
703fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
70470b44dd4SMatthias Ringwald     sm_trigger_run();
7053deb3ec6SMatthias Ringwald }
7063deb3ec6SMatthias Ringwald 
707ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7089ec2630cSMatthias Ringwald     UNUSED(timer);
7099ec2630cSMatthias Ringwald 
7103deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
711528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
712528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7133deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7143deb3ec6SMatthias Ringwald }
7153deb3ec6SMatthias Ringwald 
7163deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
717528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
718528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
719528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7203deb3ec6SMatthias Ringwald }
7213deb3ec6SMatthias Ringwald 
7223deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
723528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7243deb3ec6SMatthias Ringwald }
7253deb3ec6SMatthias Ringwald 
7263deb3ec6SMatthias Ringwald // ah(k,r) helper
7273deb3ec6SMatthias Ringwald // r = padding || r
7283deb3ec6SMatthias Ringwald // r - 24 bit value
7294a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7303deb3ec6SMatthias Ringwald     // r'= padding || r
7313deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7326535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7333deb3ec6SMatthias Ringwald }
7343deb3ec6SMatthias Ringwald 
7353deb3ec6SMatthias Ringwald // d1 helper
7363deb3ec6SMatthias Ringwald // d' = padding || r || d
7373deb3ec6SMatthias Ringwald // d,r - 16 bit values
7384a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7393deb3ec6SMatthias Ringwald     // d'= padding || r || d
7403deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
741f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
742f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7433deb3ec6SMatthias Ringwald }
7443deb3ec6SMatthias Ringwald 
7453deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7464a6806f3SMatthias Ringwald 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){
7473deb3ec6SMatthias Ringwald 
7483deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7493deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7503deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7513deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7523deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7533deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7543deb3ec6SMatthias Ringwald 
7553deb3ec6SMatthias Ringwald     sm_key_t p1;
7569c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7579c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7583deb3ec6SMatthias Ringwald     p1[14] = rat;
7593deb3ec6SMatthias Ringwald     p1[15] = iat;
7608314c363SMatthias Ringwald     log_info_key("p1", p1);
7618314c363SMatthias Ringwald     log_info_key("r", r);
7623deb3ec6SMatthias Ringwald 
7633deb3ec6SMatthias Ringwald     // t1 = r xor p1
7643deb3ec6SMatthias Ringwald     int i;
7653deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7663deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7673deb3ec6SMatthias Ringwald     }
7688314c363SMatthias Ringwald     log_info_key("t1", t1);
7693deb3ec6SMatthias Ringwald }
7703deb3ec6SMatthias Ringwald 
7713deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7724a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7733deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7743deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7753deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7763deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7773deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7783deb3ec6SMatthias Ringwald 
7793deb3ec6SMatthias Ringwald     sm_key_t p2;
7803deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7816535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7826535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7838314c363SMatthias Ringwald     log_info_key("p2", p2);
7843deb3ec6SMatthias Ringwald 
7853deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7863deb3ec6SMatthias Ringwald     int i;
7873deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7883deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
7893deb3ec6SMatthias Ringwald     }
7908314c363SMatthias Ringwald     log_info_key("t3", t3);
7913deb3ec6SMatthias Ringwald }
7923deb3ec6SMatthias Ringwald 
7934a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
7948314c363SMatthias Ringwald     log_info_key("r1", r1);
7958314c363SMatthias Ringwald     log_info_key("r2", r2);
7966535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
7976535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
7983deb3ec6SMatthias Ringwald }
7993deb3ec6SMatthias Ringwald 
800fbe050beSMatthias Ringwald 
8013deb3ec6SMatthias Ringwald // decide on stk generation based on
8023deb3ec6SMatthias Ringwald // - pairing request
8033deb3ec6SMatthias Ringwald // - io capabilities
8043deb3ec6SMatthias Ringwald // - OOB data availability
8053deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8063deb3ec6SMatthias Ringwald 
8078334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8088334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8098334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8108334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8118334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8128334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8138334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8148334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8158334d3d8SMatthias Ringwald     };
8168334d3d8SMatthias Ringwald 
8178334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8188334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8198334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8208334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8218334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8228334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8238334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8248334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8258334d3d8SMatthias Ringwald     };
8268334d3d8SMatthias Ringwald #endif
8278334d3d8SMatthias Ringwald 
8283deb3ec6SMatthias Ringwald     // default: just works
8293deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8303deb3ec6SMatthias Ringwald 
83127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
83227c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
83327c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8344ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
83527c32905SMatthias Ringwald #else
83627c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
83727c32905SMatthias Ringwald #endif
83898d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
83927c32905SMatthias Ringwald 
84065a9a04eSMatthias Ringwald 
84165a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8421979f09cSMatthias Ringwald     bool use_oob;
84365a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
84465a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
84565a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8461979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) | sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
84765a9a04eSMatthias Ringwald     } else {
84865a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
84965a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8501979f09cSMatthias Ringwald         use_oob = (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) & sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres)) != 0;
85165a9a04eSMatthias Ringwald     }
85265a9a04eSMatthias Ringwald     if (use_oob){
85365a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
85465a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
85565a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
85665a9a04eSMatthias Ringwald         return;
85765a9a04eSMatthias Ringwald     }
85865a9a04eSMatthias Ringwald 
85927c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
86027c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
86127c32905SMatthias Ringwald     // model shall be used.
8624ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8634ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
86427c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
86527c32905SMatthias Ringwald         return;
86627c32905SMatthias Ringwald     }
86727c32905SMatthias Ringwald 
8683deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8693deb3ec6SMatthias Ringwald     sm_reset_tk();
8703deb3ec6SMatthias Ringwald 
8713deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8728da2e96dSMatthias Ringwald     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)){
8733deb3ec6SMatthias Ringwald         return;
8743deb3ec6SMatthias Ringwald     }
8753deb3ec6SMatthias Ringwald 
8763deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8773deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
87827c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
87927c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
88027c32905SMatthias Ringwald 
88127c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
882c6b7cbd9SMatthias Ringwald     // table not define by default
88327c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
88427c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
88527c32905SMatthias Ringwald     }
88627c32905SMatthias Ringwald #endif
88727c32905SMatthias Ringwald     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)];
88827c32905SMatthias Ringwald 
8893deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
8901ad129beSMatthias Ringwald         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);
8913deb3ec6SMatthias Ringwald }
8923deb3ec6SMatthias Ringwald 
8933deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
8943deb3ec6SMatthias Ringwald     int flags = 0;
8953deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
8963deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
8973deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
8983deb3ec6SMatthias Ringwald     }
8993deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9003deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9013deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9023deb3ec6SMatthias Ringwald     }
9033deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9043deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9053deb3ec6SMatthias Ringwald     }
9063deb3ec6SMatthias Ringwald     return flags;
9073deb3ec6SMatthias Ringwald }
9083deb3ec6SMatthias Ringwald 
9099a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9103deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9119a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9129a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
913715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9149790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
915715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9169790be5fSMatthias Ringwald #endif
9173deb3ec6SMatthias Ringwald }
9183deb3ec6SMatthias Ringwald 
9193deb3ec6SMatthias Ringwald // CSRK Key Lookup
9203deb3ec6SMatthias Ringwald 
9213deb3ec6SMatthias Ringwald 
9223deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9233deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9243deb3ec6SMatthias Ringwald }
9253deb3ec6SMatthias Ringwald 
926711e6c80SMatthias Ringwald 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){
9276535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9283deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9293deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9303deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9313deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
932711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9333deb3ec6SMatthias Ringwald }
9343deb3ec6SMatthias Ringwald 
9353deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9363deb3ec6SMatthias Ringwald     // check if already in list
937665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9383deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
939665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
940665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
941665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9423deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9433deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9443deb3ec6SMatthias Ringwald         // already in list
9453deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9463deb3ec6SMatthias Ringwald     }
9473deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9483deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9493deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9506535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
951665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
95270b44dd4SMatthias Ringwald     sm_trigger_run();
9533deb3ec6SMatthias Ringwald     return 0;
9543deb3ec6SMatthias Ringwald }
9553deb3ec6SMatthias Ringwald 
956d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
957d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
958514d35fcSMatthias Ringwald 
959d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
960d1a1f6a4SMatthias Ringwald     UNUSED(arg);
961d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
962d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
96370b44dd4SMatthias Ringwald     sm_trigger_run();
9643deb3ec6SMatthias Ringwald }
965514d35fcSMatthias Ringwald 
9664dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9674ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9683deb3ec6SMatthias Ringwald }
9696d80b495SMatthias Ringwald #endif
9703deb3ec6SMatthias Ringwald 
9716d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
972514d35fcSMatthias Ringwald // generic cmac calculation
973d1a1f6a4SMatthias Ringwald 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)){
974d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
975d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
976d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9773deb3ec6SMatthias Ringwald }
9787a766ebfSMatthias Ringwald #endif
9793deb3ec6SMatthias Ringwald 
980514d35fcSMatthias Ringwald // cmac for ATT Message signing
9817a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
982d1a1f6a4SMatthias Ringwald 
983d1a1f6a4SMatthias Ringwald 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)){
984d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
985d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
986d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
987d1a1f6a4SMatthias Ringwald }
988d1a1f6a4SMatthias Ringwald 
9894dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
990d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
991d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
9924dfd504aSMatthias Ringwald         return 0;
9934dfd504aSMatthias Ringwald     }
9944dfd504aSMatthias Ringwald 
995d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
9964dfd504aSMatthias Ringwald 
997d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
9984dfd504aSMatthias Ringwald     if (offset < 3){
999d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10004dfd504aSMatthias Ringwald     }
1001d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10024dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1003d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10044dfd504aSMatthias Ringwald     }
1005d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10064dfd504aSMatthias Ringwald }
10074dfd504aSMatthias Ringwald 
10084dfd504aSMatthias Ringwald 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)){
1009514d35fcSMatthias Ringwald     // ATT Message Signing
1010d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1011d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1012d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1013514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1014d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1015d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1016d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10173deb3ec6SMatthias Ringwald }
10187a766ebfSMatthias Ringwald #endif
10193deb3ec6SMatthias Ringwald 
1020ea9b6796SMatthias Ringwald static void sm_trigger_user_response_basic(sm_connection_t * sm_conn, uint8_t event_type){
1021ea9b6796SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10225baa755bSMatthias Ringwald     uint8_t event[12];
1023f6a153d5SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10245baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
1025f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1026ea9b6796SMatthias Ringwald }
1027ea9b6796SMatthias Ringwald 
102874b4d42aSMatthias Ringwald static void sm_trigger_user_response_passkey(sm_connection_t * sm_conn, uint8_t event_type){
10295baa755bSMatthias Ringwald     uint8_t event[16];
1030f6a153d5SMatthias Ringwald     uint32_t passkey = big_endian_read_32(setup->sm_tk, 12);
103174b4d42aSMatthias Ringwald     sm_setup_event_base(event, sizeof(event), event_type, sm_conn->sm_handle,
1032f6a153d5SMatthias Ringwald                         sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10335baa755bSMatthias Ringwald     event[11] = setup->sm_use_secure_connections ? 1 : 0;
10345baa755bSMatthias Ringwald     little_endian_store_32(event, 12, passkey);
1035f6a153d5SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
1036ea9b6796SMatthias Ringwald }
1037ea9b6796SMatthias Ringwald 
10383deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1039446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10403deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1041d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10423deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10433deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
104442134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1045ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10463deb3ec6SMatthias Ringwald             } else {
104774b4d42aSMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER);
10483deb3ec6SMatthias Ringwald             }
10493deb3ec6SMatthias Ringwald             break;
10503deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
105142134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
105274b4d42aSMatthias Ringwald                 sm_trigger_user_response_passkey(sm_conn, SM_EVENT_PASSKEY_DISPLAY_NUMBER);
10533deb3ec6SMatthias Ringwald             } else {
1054ea9b6796SMatthias Ringwald                 sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10553deb3ec6SMatthias Ringwald             }
10563deb3ec6SMatthias Ringwald             break;
105747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
1058ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_PASSKEY_INPUT_NUMBER);
10593deb3ec6SMatthias Ringwald             break;
106047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
106174b4d42aSMatthias Ringwald             sm_trigger_user_response_passkey(sm_conn, SM_EVENT_NUMERIC_COMPARISON_REQUEST);
106227c32905SMatthias Ringwald             break;
10633deb3ec6SMatthias Ringwald         case JUST_WORKS:
1064ea9b6796SMatthias Ringwald             sm_trigger_user_response_basic(sm_conn, SM_EVENT_JUST_WORKS_REQUEST);
10653deb3ec6SMatthias Ringwald             break;
10663deb3ec6SMatthias Ringwald         case OOB:
10673deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10683deb3ec6SMatthias Ringwald             break;
10697bbeb3adSMilanka Ringwald         default:
10707bbeb3adSMilanka Ringwald             btstack_assert(false);
10717bbeb3adSMilanka Ringwald             break;
10723deb3ec6SMatthias Ringwald     }
10733deb3ec6SMatthias Ringwald }
10743deb3ec6SMatthias Ringwald 
107561d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
10765fa700b1SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, setup->sm_key_distribution_expected_set);
1077b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10783deb3ec6SMatthias Ringwald }
10793deb3ec6SMatthias Ringwald 
1080711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10817149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10823deb3ec6SMatthias Ringwald         sm_timeout_stop();
10837149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1084711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1085c085d9ffSMatthias Ringwald 
1086c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1087c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1088c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1089c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1090c085d9ffSMatthias Ringwald         }
1091c085d9ffSMatthias Ringwald #endif
10923deb3ec6SMatthias Ringwald     }
10933deb3ec6SMatthias Ringwald }
10943deb3ec6SMatthias Ringwald 
10957d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
10961dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
10970ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
10981dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
10991dca9d8aSMatthias Ringwald }
11001dca9d8aSMatthias Ringwald 
11013deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1102bb09604fSMatthias Ringwald 
1103bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11043deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1105bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11063deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1107bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1108bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1109bb09604fSMatthias Ringwald #endif
11107ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11117ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11127ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11137ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11147ece0eaaSMatthias Ringwald         }
11157ece0eaaSMatthias Ringwald #endif
11163deb3ec6SMatthias Ringwald     }
11173deb3ec6SMatthias Ringwald     return flags;
11183deb3ec6SMatthias Ringwald }
11193deb3ec6SMatthias Ringwald 
1120d7471931SMatthias Ringwald static void sm_reset_setup(void){
11213deb3ec6SMatthias Ringwald     // fill in sm setup
1122901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1123dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1124d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11253deb3ec6SMatthias Ringwald     sm_reset_tk();
1126d7471931SMatthias Ringwald }
1127d7471931SMatthias Ringwald 
1128d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1129d7471931SMatthias Ringwald     // fill in sm setup
11303deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11316535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11323deb3ec6SMatthias Ringwald 
1133a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11349305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1135a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11363deb3ec6SMatthias Ringwald     }
11373deb3ec6SMatthias Ringwald 
1138a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1139a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11404acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11414acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1142a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11439305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11444acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1145a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1146a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1147a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1148a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11494acf7b7bSMatthias Ringwald                     setup->sm_ra);
11504acf7b7bSMatthias Ringwald             } else {
11514acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11524acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11534acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11544acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11554acf7b7bSMatthias Ringwald                     setup->sm_rb);
11564acf7b7bSMatthias Ringwald             }
1157a680ba6bSMatthias Ringwald         } else {
1158a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1159a680ba6bSMatthias Ringwald         }
1160a680ba6bSMatthias Ringwald     }
1161a680ba6bSMatthias Ringwald #endif
1162a680ba6bSMatthias Ringwald 
11633deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
116442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11653deb3ec6SMatthias Ringwald         // slave
11663deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11673deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1168d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11696535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1170d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11713deb3ec6SMatthias Ringwald     } else {
11723deb3ec6SMatthias Ringwald         // master
11733deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11743deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1175d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11766535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1177d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11783deb3ec6SMatthias Ringwald 
1179d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11801ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11811ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11823deb3ec6SMatthias Ringwald     }
11833deb3ec6SMatthias Ringwald 
118457132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1185d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11862c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11872c041b42SMatthias Ringwald     // enable SC for SC only mode
11882c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11892c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1190d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
11912c041b42SMatthias Ringwald     }
11922c041b42SMatthias Ringwald #endif
119357132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
119457132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
119557132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
119657132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
119757132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
119857132f12SMatthias Ringwald 	}
119957132f12SMatthias Ringwald #endif
12001ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1201a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1202df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1203d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12043deb3ec6SMatthias Ringwald }
12053deb3ec6SMatthias Ringwald 
12063deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12073deb3ec6SMatthias Ringwald 
12083deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12099a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12109a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
121142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121252f9cf63SMatthias Ringwald         // slave / responder
12133deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12149a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12159a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12163deb3ec6SMatthias Ringwald     } else {
12173deb3ec6SMatthias Ringwald         // master / initiator
12183deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12199a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12209a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12213deb3ec6SMatthias Ringwald     }
12223deb3ec6SMatthias Ringwald 
12233deb3ec6SMatthias Ringwald     // check key size
12242c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12252c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12262c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12272c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12282c041b42SMatthias Ringwald     }
12292c041b42SMatthias Ringwald #endif
12301ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12314ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12323deb3ec6SMatthias Ringwald 
1233eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12343deb3ec6SMatthias Ringwald     sm_setup_tk();
12353deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12363deb3ec6SMatthias Ringwald 
12373deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12383deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12393deb3ec6SMatthias Ringwald 
1240eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12412c041b42SMatthias Ringwald     // Check LE SC Only mode
12423cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12433cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12443cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12453cdbe9dbSMatthias Ringwald     }
12463cdbe9dbSMatthias Ringwald 
12479a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1248eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12499a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12509a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1251eddc894fSMatthias Ringwald     }
1252eddc894fSMatthias Ringwald #endif
1253eddc894fSMatthias Ringwald 
125452f9cf63SMatthias Ringwald     // identical to responder
12559a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
125652f9cf63SMatthias Ringwald 
12573deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1258c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12593deb3ec6SMatthias Ringwald 
12603deb3ec6SMatthias Ringwald     return 0;
12613deb3ec6SMatthias Ringwald }
12623deb3ec6SMatthias Ringwald 
12633deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12643deb3ec6SMatthias Ringwald 
12653deb3ec6SMatthias Ringwald     // cache and reset context
12663deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12673deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12683deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12693deb3ec6SMatthias Ringwald 
12703deb3ec6SMatthias Ringwald     // reset context
12713deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12723deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12733deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1274711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12753deb3ec6SMatthias Ringwald 
12763deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1277d2e90122SMatthias Ringwald     sm_key_t ltk;
12781979f09cSMatthias Ringwald     bool have_ltk;
12796c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12801979f09cSMatthias Ringwald     bool trigger_pairing;
128142134bc6SMatthias Ringwald #endif
12823deb3ec6SMatthias Ringwald     switch (mode){
12833deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12843deb3ec6SMatthias Ringwald             break;
12853deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12863deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1287711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12886c44b759SMatthias Ringwald 
12896c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12906c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12916c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12926c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12936c44b759SMatthias Ringwald 
12943deb3ec6SMatthias Ringwald             switch (event){
1295a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
12963deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
12973deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1298a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
12996c44b759SMatthias Ringwald 
13006c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13016c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13026c44b759SMatthias Ringwald 
13036c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13046c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1305212d735eSMatthias Ringwald                         // IRK required before, continue
13066c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13076c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13086c39055aSMatthias Ringwald                             break;
13096c39055aSMatthias Ringwald                         }
1310212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1311212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1312212d735eSMatthias Ringwald                             break;
1313212d735eSMatthias Ringwald                         }
13147af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13157af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13166c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13177af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13187af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13196c44b759SMatthias Ringwald #endif
13207af5dcd5SMatthias Ringwald 
13217af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13221979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13237af5dcd5SMatthias Ringwald 
13247af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13257af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13267af5dcd5SMatthias Ringwald                             if (have_ltk){
13277af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13287af5dcd5SMatthias Ringwald                             } else {
13297af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13307af5dcd5SMatthias Ringwald                             }
13317af5dcd5SMatthias Ringwald                             sm_trigger_run();
13326c44b759SMatthias Ringwald                         }
13336c44b759SMatthias Ringwald #endif
13346c44b759SMatthias Ringwald                     } else {
13356c44b759SMatthias Ringwald 
133642134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13376c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13386c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13396c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13401979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13413deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134209ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134332bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1344c245ca32SMatthias Ringwald 
1345d4af1595SMatthias Ringwald                         if (have_ltk){
13466a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1347b187cc61SMatthias Ringwald                             trigger_reencryption = true;
134832bc5d65SMatthias Ringwald #else
134932bc5d65SMatthias Ringwald                             if (trigger_pairing){
135032bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135132bc5d65SMatthias Ringwald                             } else {
135232bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135332bc5d65SMatthias Ringwald                             }
135432bc5d65SMatthias Ringwald #endif
135532bc5d65SMatthias Ringwald                         }
135632bc5d65SMatthias Ringwald 
135732bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13586c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13595567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1360d4af1595SMatthias Ringwald                             break;
1361d4af1595SMatthias Ringwald                         }
13626c44b759SMatthias Ringwald 
13636c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13646c44b759SMatthias Ringwald                         if (trigger_pairing){
13653deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1366d4af1595SMatthias Ringwald                             break;
13673deb3ec6SMatthias Ringwald                         }
136842134bc6SMatthias Ringwald #endif
1369298ab52bSMatthias Ringwald                     }
13703deb3ec6SMatthias Ringwald                     break;
13713deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13723deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13736c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13747af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13756c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13766c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13776c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13786c39055aSMatthias Ringwald                         }
13797af5dcd5SMatthias Ringwald                         // send security request if requested
13807af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13817af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13827af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13837af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13847af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13857af5dcd5SMatthias Ringwald                         }
13866c39055aSMatthias Ringwald                         break;
13877af5dcd5SMatthias Ringwald #endif
13886c39055aSMatthias Ringwald                     }
138942134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
139009ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13913deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139209ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13933deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139442134bc6SMatthias Ringwald #endif
13953deb3ec6SMatthias Ringwald                     break;
13967bbeb3adSMilanka Ringwald 
13977bbeb3adSMilanka Ringwald                 default:
13987bbeb3adSMilanka Ringwald                     btstack_assert(false);
13997bbeb3adSMilanka Ringwald                     break;
14003deb3ec6SMatthias Ringwald             }
14013deb3ec6SMatthias Ringwald             break;
14023deb3ec6SMatthias Ringwald         default:
14033deb3ec6SMatthias Ringwald             break;
14043deb3ec6SMatthias Ringwald     }
14053deb3ec6SMatthias Ringwald 
14063deb3ec6SMatthias Ringwald     switch (event){
1407a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1408711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14093deb3ec6SMatthias Ringwald             break;
14103deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1411711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14123deb3ec6SMatthias Ringwald             break;
14137bbeb3adSMilanka Ringwald         default:
14147bbeb3adSMilanka Ringwald             btstack_assert(false);
14157bbeb3adSMilanka Ringwald             break;
14163deb3ec6SMatthias Ringwald     }
14173deb3ec6SMatthias Ringwald }
14183deb3ec6SMatthias Ringwald 
141955f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14203deb3ec6SMatthias Ringwald     int le_db_index = -1;
14213deb3ec6SMatthias Ringwald 
14223deb3ec6SMatthias Ringwald     // lookup device based on IRK
14233deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14243deb3ec6SMatthias Ringwald         int i;
1425092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14263deb3ec6SMatthias Ringwald             sm_key_t irk;
14273deb3ec6SMatthias Ringwald             bd_addr_t address;
1428c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14293deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1430adf5eaa9SMatthias Ringwald             // skip unused entries
1431c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
143211d10bdaSMatthias Ringwald             // compare Identity Address
143311d10bdaSMatthias Ringwald             if (memcmp(address, setup->sm_peer_address, 6) != 0) continue;
143411d10bdaSMatthias Ringwald             // compare Identity Resolving Key
1435c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1436c7e2c1a5SMatthias Ringwald 
14373deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14383deb3ec6SMatthias Ringwald             le_db_index = i;
14393deb3ec6SMatthias Ringwald             break;
14403deb3ec6SMatthias Ringwald         }
1441c7e2c1a5SMatthias Ringwald     } else {
1442c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1443c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14443deb3ec6SMatthias Ringwald     }
14453deb3ec6SMatthias Ringwald 
14463deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14473deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1448c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14493deb3ec6SMatthias Ringwald         int i;
1450092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14513deb3ec6SMatthias Ringwald             bd_addr_t address;
1452adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14533deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1454adf5eaa9SMatthias Ringwald             // skip unused entries
1455adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14563deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14575df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14583deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14593deb3ec6SMatthias Ringwald                 le_db_index = i;
14603deb3ec6SMatthias Ringwald                 break;
14613deb3ec6SMatthias Ringwald             }
14623deb3ec6SMatthias Ringwald         }
14633deb3ec6SMatthias Ringwald     }
14643deb3ec6SMatthias Ringwald 
14653deb3ec6SMatthias Ringwald     // if not found, add to db
146602b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14673deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14683deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
146902b02cffSMatthias Ringwald         new_to_le_device_db = true;
14703deb3ec6SMatthias Ringwald     }
14713deb3ec6SMatthias Ringwald 
14723deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14733deb3ec6SMatthias Ringwald 
147402b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
147502b02cffSMatthias Ringwald         if (!new_to_le_device_db){
147602b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
147702b02cffSMatthias Ringwald         }
147802b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
147902b02cffSMatthias Ringwald #else
148002b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
148102b02cffSMatthias Ringwald #endif
148202b02cffSMatthias Ringwald 
148348163929SMatthias Ringwald         sm_notify_client_index(SM_EVENT_IDENTITY_CREATED, sm_conn->sm_handle, setup->sm_peer_addr_type, setup->sm_peer_address, le_db_index);
1484e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14857710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
148648163929SMatthias Ringwald 
1487eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14883deb3ec6SMatthias Ringwald         // store local CSRK
1489715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1490715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14913deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
14923deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14933deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
14943deb3ec6SMatthias Ringwald         }
14953deb3ec6SMatthias Ringwald 
14963deb3ec6SMatthias Ringwald         // store remote CSRK
14973deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14983deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
14993deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
15003deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
15013deb3ec6SMatthias Ringwald         }
1502eda85fbfSMatthias Ringwald #endif
150378f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
150478f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1505e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
150678f44163SMatthias Ringwald             uint8_t zero_rand[8];
150778f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
150878f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15093dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
151078f44163SMatthias Ringwald         }
151178f44163SMatthias Ringwald 
1512e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151378f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151478f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1515e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15163deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15173dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
151878f44163SMatthias Ringwald 
15193deb3ec6SMatthias Ringwald         }
15203deb3ec6SMatthias Ringwald     }
152155f09f49SMatthias Ringwald }
152255f09f49SMatthias Ringwald 
15238980298aSMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
15248980298aSMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
15258980298aSMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
15268980298aSMatthias Ringwald }
15278980298aSMatthias Ringwald 
1528321397a4SMatthias Ringwald static int sm_lookup_by_address(void) {
15291a55487aSMatthias Ringwald     int i;
15301a55487aSMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
15311a55487aSMatthias Ringwald         bd_addr_t address;
15321a55487aSMatthias Ringwald         int address_type = BD_ADDR_TYPE_UNKNOWN;
15331a55487aSMatthias Ringwald         le_device_db_info(i, &address_type, address, NULL);
15341a55487aSMatthias Ringwald         // skip unused entries
15351a55487aSMatthias Ringwald         if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
15361a55487aSMatthias Ringwald         if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
15371a55487aSMatthias Ringwald             return i;
15381a55487aSMatthias Ringwald         }
15391a55487aSMatthias Ringwald     }
15401a55487aSMatthias Ringwald     return -1;
15411a55487aSMatthias Ringwald }
15421a55487aSMatthias Ringwald 
15432e08b70bSMatthias Ringwald static void sm_remove_le_device_db_entry(uint16_t i) {
15442e08b70bSMatthias Ringwald     le_device_db_remove(i);
1545672dc582SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
1546672dc582SMatthias Ringwald     // to remove an entry from the resolving list requires its identity address, which was already deleted
1547672dc582SMatthias Ringwald     // fully reload resolving list instead
1548672dc582SMatthias Ringwald     gap_load_resolving_list_from_le_device_db();
1549672dc582SMatthias Ringwald #endif
15502e08b70bSMatthias Ringwald }
15512e08b70bSMatthias Ringwald 
15528980298aSMatthias Ringwald static uint8_t sm_key_distribution_validate_received(sm_connection_t * sm_conn){
15531a55487aSMatthias Ringwald     // if identity is provided, abort if we have bonding with same address but different irk
15541a55487aSMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
1555321397a4SMatthias Ringwald         int index = sm_lookup_by_address();
15561a55487aSMatthias Ringwald         if (index >= 0){
15571a55487aSMatthias Ringwald             sm_key_t irk;
15581a55487aSMatthias Ringwald             le_device_db_info(index, NULL, NULL, irk);
15591a55487aSMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0){
15601a55487aSMatthias Ringwald                 // IRK doesn't match, delete bonding information
15611a55487aSMatthias Ringwald                 log_info("New IRK for %s (type %u) does not match stored IRK -> delete bonding information", bd_addr_to_str(sm_conn->sm_peer_address), sm_conn->sm_peer_addr_type);
15629202d845SMatthias Ringwald                 sm_remove_le_device_db_entry(index);
15631a55487aSMatthias Ringwald             }
15641a55487aSMatthias Ringwald         }
15651a55487aSMatthias Ringwald     }
15668980298aSMatthias Ringwald     return 0;
15678980298aSMatthias Ringwald }
15688980298aSMatthias Ringwald 
156955f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
157055f09f49SMatthias Ringwald 
15718980298aSMatthias Ringwald     // abort pairing if received keys are not valid
15728980298aSMatthias Ringwald     uint8_t reason = sm_key_distribution_validate_received(sm_conn);
15738980298aSMatthias Ringwald     if (reason != 0){
15748980298aSMatthias Ringwald         sm_pairing_error(sm_conn, reason);
15758980298aSMatthias Ringwald         return;
15768980298aSMatthias Ringwald     }
15778980298aSMatthias Ringwald 
157855f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
157955f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
158055f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
158155f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
158255f09f49SMatthias Ringwald 
158355f09f49SMatthias Ringwald     if (bonding_enabled){
158455f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
158527ef8bc8SMatthias Ringwald     } else {
158627ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
158727ef8bc8SMatthias Ringwald     }
15883deb3ec6SMatthias Ringwald }
15893deb3ec6SMatthias Ringwald 
1590688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1591688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1592688a08f9SMatthias Ringwald }
1593688a08f9SMatthias Ringwald 
15949af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1595688a08f9SMatthias Ringwald 
1596dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1597945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1598f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1599dc300847SMatthias Ringwald 
1600b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1601b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
16021f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1603b90c4e75SMatthias Ringwald     } else {
1604b90c4e75SMatthias Ringwald         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);
1605b35a3de2SMatthias Ringwald     }
1606b35a3de2SMatthias Ringwald }
1607b35a3de2SMatthias Ringwald 
1608688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
160942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1610688a08f9SMatthias Ringwald         // Responder
16114acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
16124acf7b7bSMatthias Ringwald             // generate Nb
16134acf7b7bSMatthias Ringwald             log_info("Generate Nb");
16146ca80073SMatthias Ringwald             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);
16154acf7b7bSMatthias Ringwald         } else {
1616688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
16174acf7b7bSMatthias Ringwald         }
1618688a08f9SMatthias Ringwald     } else {
1619688a08f9SMatthias Ringwald         // Initiator role
1620688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1621688a08f9SMatthias Ringwald             case JUST_WORKS:
1622dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1623688a08f9SMatthias Ringwald                 break;
1624688a08f9SMatthias Ringwald 
162547fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1626bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1627688a08f9SMatthias Ringwald                 break;
1628688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1629688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
163047fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
16314ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1632b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1633688a08f9SMatthias Ringwald                 } else {
1634dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1635688a08f9SMatthias Ringwald                 }
1636688a08f9SMatthias Ringwald                 break;
1637688a08f9SMatthias Ringwald             case OOB:
163865a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1639688a08f9SMatthias Ringwald                 break;
16407bbeb3adSMilanka Ringwald             default:
16417bbeb3adSMilanka Ringwald                 btstack_assert(false);
16427bbeb3adSMilanka Ringwald                 break;
1643688a08f9SMatthias Ringwald         }
1644688a08f9SMatthias Ringwald     }
1645688a08f9SMatthias Ringwald }
1646688a08f9SMatthias Ringwald 
1647aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1648688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1649688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1650688a08f9SMatthias Ringwald 
1651c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1652c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1653a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1654c59d0c92SMatthias Ringwald         return;
1655c59d0c92SMatthias Ringwald     }
1656c59d0c92SMatthias Ringwald 
1657bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1658bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16596857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16602bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1661b4f65634SMatthias Ringwald #endif
1662bd57ffebSMatthias Ringwald 
1663bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1664aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16656535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1666bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1667aec94140SMatthias Ringwald             break;
1668688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1669688a08f9SMatthias Ringwald             // check
1670688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1671bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1672688a08f9SMatthias Ringwald                 break;
1673688a08f9SMatthias Ringwald             }
1674bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1675688a08f9SMatthias Ringwald             break;
1676901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1677901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1678901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1679901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1680901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1681019005a0SMatthias Ringwald             break;
1682019005a0SMatthias Ringwald         }
16830346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16846535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1685bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16860346c37cSMatthias Ringwald             break;
16870346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16886535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1689bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16900346c37cSMatthias Ringwald             break;
16910346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1692b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1693b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1694b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1695b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16966535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16976535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1698893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1699bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1700019005a0SMatthias Ringwald             break;
1701901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
17026535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
170342134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1704901c000fSMatthias Ringwald                 // responder
1705901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1706901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1707901c000fSMatthias Ringwald                 } else {
1708901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1709901c000fSMatthias Ringwald                 }
1710901c000fSMatthias Ringwald             } else {
1711901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1712901c000fSMatthias Ringwald             }
1713901c000fSMatthias Ringwald             break;
1714901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1715901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1716901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1717aec94140SMatthias Ringwald                 break;
1718aec94140SMatthias Ringwald             }
171942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1720901c000fSMatthias Ringwald                 // responder
1721901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1722901c000fSMatthias Ringwald             } else {
1723901c000fSMatthias Ringwald                 // initiator
1724901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1725bd57ffebSMatthias Ringwald             }
1726901c000fSMatthias Ringwald             break;
17276857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
172857132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
17296535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
173057132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
17312bacf595SMatthias Ringwald             break;
173257132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
17332bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
17342bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
17352bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
17368974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
173755160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
17388974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
17392bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
17402bacf595SMatthias Ringwald             } else {
17412bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
17422bacf595SMatthias Ringwald             }
17430ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
17442bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
17452bacf595SMatthias Ringwald             break;
1746e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1747e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1748e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1749e0a03c85SMatthias Ringwald             break;
1750e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1751e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1752e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1753e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1754e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1755e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1756e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1757c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1758e0a03c85SMatthias Ringwald             break;
1759bdb14b0eSMatthias Ringwald #endif
1760bd57ffebSMatthias Ringwald         default:
1761bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1762bd57ffebSMatthias Ringwald             break;
1763bd57ffebSMatthias Ringwald     }
176470b44dd4SMatthias Ringwald     sm_trigger_run();
1765aec94140SMatthias Ringwald }
1766aec94140SMatthias Ringwald 
1767688a08f9SMatthias Ringwald 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){
1768dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1769aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17706535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17716535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1772aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1773aec94140SMatthias Ringwald     log_info("f4 key");
1774aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1775aec94140SMatthias Ringwald     log_info("f4 message");
1776dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1777d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1778aec94140SMatthias Ringwald }
1779aec94140SMatthias Ringwald 
17800346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17810346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17820346c37cSMatthias Ringwald 
17830346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17848334d3d8SMatthias Ringwald 
17858334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17868334d3d8SMatthias Ringwald 
178740c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17880346c37cSMatthias Ringwald     // calculate salt for f5
17890346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17900346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17916535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1792d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17930346c37cSMatthias Ringwald }
17940346c37cSMatthias Ringwald 
17950346c37cSMatthias Ringwald 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){
17960346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17970346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17980346c37cSMatthias Ringwald 
17990346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
18000346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
18026535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
18036535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
18046535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
18056535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
18066535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
18070346c37cSMatthias Ringwald     log_info("f5 key");
18080346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18090346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
18100346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1811d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18120346c37cSMatthias Ringwald }
18130346c37cSMatthias Ringwald 
18140346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
18150346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
18160346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
18170346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
18186535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
18196535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
182042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
18210346c37cSMatthias Ringwald         // responder
18220346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
18230346c37cSMatthias Ringwald     } else {
18240346c37cSMatthias Ringwald         // initiator
18250346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
18260346c37cSMatthias Ringwald     }
18270346c37cSMatthias Ringwald }
18280346c37cSMatthias Ringwald 
18290346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
18300346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
18310346c37cSMatthias Ringwald     const uint16_t message_len = 53;
18320346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
18330346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
18340346c37cSMatthias Ringwald     // 1..52 setup before
18350346c37cSMatthias Ringwald     log_info("f5 key");
18360346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
18370346c37cSMatthias Ringwald     log_info("f5 message for LTK");
18380346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1839d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
18400346c37cSMatthias Ringwald }
1841f92edc8eSMatthias Ringwald 
18420346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
18430346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
18440346c37cSMatthias Ringwald }
18450346c37cSMatthias Ringwald 
184631f061fbSMatthias Ringwald 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){
18476535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18486535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18496535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18506535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18516535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
185331f061fbSMatthias Ringwald }
185431f061fbSMatthias Ringwald 
185531f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
185631f061fbSMatthias Ringwald     const uint16_t message_len = 65;
185731f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1858dc300847SMatthias Ringwald     log_info("f6 key");
1859dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1860dc300847SMatthias Ringwald     log_info("f6 message");
1861dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1862d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1863dc300847SMatthias Ringwald }
1864dc300847SMatthias Ringwald 
1865f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1866f92edc8eSMatthias Ringwald // - U is 256 bits
1867f92edc8eSMatthias Ringwald // - V is 256 bits
1868f92edc8eSMatthias Ringwald // - X is 128 bits
1869f92edc8eSMatthias Ringwald // - Y is 128 bits
1870bd57ffebSMatthias Ringwald 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){
1871bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1872bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18736535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18746535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18756535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1876f92edc8eSMatthias Ringwald     log_info("g2 key");
1877f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1878f92edc8eSMatthias Ringwald     log_info("g2 message");
18792bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1880d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1881f92edc8eSMatthias Ringwald }
1882f92edc8eSMatthias Ringwald 
1883b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1884f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
188542134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1886f92edc8eSMatthias Ringwald         // responder
1887fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1888f92edc8eSMatthias Ringwald     } else {
1889f92edc8eSMatthias Ringwald         // initiator
1890fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1891f92edc8eSMatthias Ringwald     }
1892f92edc8eSMatthias Ringwald }
1893f92edc8eSMatthias Ringwald 
1894945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18959af0f475SMatthias Ringwald     uint8_t z = 0;
189640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18979af0f475SMatthias Ringwald         // some form of passkey
18989af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18994ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
19009af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
19019af0f475SMatthias Ringwald     }
1902fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
19039af0f475SMatthias Ringwald }
1904688a08f9SMatthias Ringwald 
1905688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1906a680ba6bSMatthias Ringwald     // OOB
1907a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
19084acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
19094acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
19104acf7b7bSMatthias Ringwald         } else {
19114acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
19124acf7b7bSMatthias Ringwald         }
1913a680ba6bSMatthias Ringwald         return;
1914a680ba6bSMatthias Ringwald     }
1915a680ba6bSMatthias Ringwald 
1916688a08f9SMatthias Ringwald     uint8_t z = 0;
191740c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1918688a08f9SMatthias Ringwald         // some form of passkey
1919688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1920688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
19214ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1922688a08f9SMatthias Ringwald     }
1923fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1924688a08f9SMatthias Ringwald }
1925688a08f9SMatthias Ringwald 
19260346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1927505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
19283cf37b8cSMatthias Ringwald 
19293cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
19303cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
19313cf37b8cSMatthias Ringwald         return;
19323cf37b8cSMatthias Ringwald     } else {
19333cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
19343cf37b8cSMatthias Ringwald     }
1935d1a1f6a4SMatthias Ringwald }
19363cf37b8cSMatthias Ringwald 
1937d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1938f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1939f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1940f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1941f3582630SMatthias Ringwald 
1942d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1943d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1944d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1945d1a1f6a4SMatthias Ringwald     // trigger next step
1946d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1947d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1948d1a1f6a4SMatthias Ringwald     }
194970b44dd4SMatthias Ringwald     sm_trigger_run();
1950dc300847SMatthias Ringwald }
1951dc300847SMatthias Ringwald 
1952dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1953dc300847SMatthias Ringwald     // calculate DHKCheck
1954dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1955dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1956dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19576535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19586535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1959dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1960dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1961dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1962dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1963dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1964dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1965dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1966dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
196742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1968dc300847SMatthias Ringwald         // responder
196931f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
197031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1971dc300847SMatthias Ringwald     } else {
1972dc300847SMatthias Ringwald         // initiator
197331f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
197431f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1975dc300847SMatthias Ringwald     }
1976dc300847SMatthias Ringwald }
1977dc300847SMatthias Ringwald 
1978019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1979019005a0SMatthias Ringwald     // validate E = f6()
1980019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1981019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1982019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19836535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19846535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1985019005a0SMatthias Ringwald 
1986019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1987019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1988019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1989019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1990019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1991019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1992019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1993019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
199442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1995019005a0SMatthias Ringwald         // responder
199631f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
199731f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1998019005a0SMatthias Ringwald     } else {
1999019005a0SMatthias Ringwald         // initiator
200031f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
200131f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
2002019005a0SMatthias Ringwald     }
2003019005a0SMatthias Ringwald }
20042bacf595SMatthias Ringwald 
200555c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
20062bacf595SMatthias Ringwald 
20072bacf595SMatthias Ringwald //
20082bacf595SMatthias Ringwald // Link Key Conversion Function h6
20092bacf595SMatthias Ringwald //
201057132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
20112bacf595SMatthias Ringwald // - W is 128 bits
20122bacf595SMatthias Ringwald // - keyID is 32 bits
20132bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
20142bacf595SMatthias Ringwald     const uint16_t message_len = 4;
20152bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
20162bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
20172bacf595SMatthias Ringwald     log_info("h6 key");
20182bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
20192bacf595SMatthias Ringwald     log_info("h6 message");
20202bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
2021d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
20222bacf595SMatthias Ringwald }
202357132f12SMatthias Ringwald //
202457132f12SMatthias Ringwald // Link Key Conversion Function h7
202557132f12SMatthias Ringwald //
202657132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
202757132f12SMatthias Ringwald // - SALT is 128 bits
202857132f12SMatthias Ringwald // - W    is 128 bits
202957132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
203057132f12SMatthias Ringwald 	const uint16_t message_len = 16;
203157132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
203257132f12SMatthias Ringwald 	log_info("h7 key");
203357132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
203457132f12SMatthias Ringwald 	log_info("h7 message");
203557132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
203657132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
203757132f12SMatthias Ringwald }
20382bacf595SMatthias Ringwald 
2039b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
2040b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
2041b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
2042b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
204357132f12SMatthias Ringwald 
2044c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
2045b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
20462bacf595SMatthias Ringwald }
20472bacf595SMatthias Ringwald 
2048e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2049e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2050e0a03c85SMatthias Ringwald }
2051e0a03c85SMatthias Ringwald 
20522bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20532bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20542bacf595SMatthias Ringwald }
20552bacf595SMatthias Ringwald 
2056e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2057e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2058e0a03c85SMatthias Ringwald }
2059e0a03c85SMatthias Ringwald 
2060c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
206157132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
206257132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
206357132f12SMatthias Ringwald }
2064e0a03c85SMatthias Ringwald 
2065e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2066e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2067e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2068e0a03c85SMatthias Ringwald }
2069e0a03c85SMatthias Ringwald 
2070c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2071e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2072e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2073e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2074e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2075e0a03c85SMatthias Ringwald }
2076e0a03c85SMatthias Ringwald 
2077c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2078c18be159SMatthias Ringwald     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;
2079c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2080c18be159SMatthias Ringwald }
2081c18be159SMatthias Ringwald 
20829af0f475SMatthias Ringwald #endif
20839af0f475SMatthias Ringwald 
208455c62cf5SMatthias Ringwald #endif
208555c62cf5SMatthias Ringwald 
2086613da3deSMatthias Ringwald // key management legacy connections:
2087613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2088613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2089613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2090613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2091613da3deSMatthias Ringwald 
2092613da3deSMatthias Ringwald // key management secure connections:
2093613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2094613da3deSMatthias Ringwald 
209542134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20965829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20975829ebe2SMatthias Ringwald     int encryption_key_size;
20985829ebe2SMatthias Ringwald     int authenticated;
20995829ebe2SMatthias Ringwald     int authorized;
21003dc3a67dSMatthias Ringwald     int secure_connection;
21015829ebe2SMatthias Ringwald 
21025829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
21035829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
21043dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
21053dc3a67dSMatthias Ringwald     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);
21065829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
21075829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
21085829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
21093dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
21105829ebe2SMatthias Ringwald }
211142134bc6SMatthias Ringwald #endif
2112bd57ffebSMatthias Ringwald 
211342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
211459066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
21156535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
211659066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
211759066796SMatthias Ringwald     // re-establish used key encryption size
211859066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
21194ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
212059066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
21214ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
21223dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
21233dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
212459066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
212559066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
212659066796SMatthias Ringwald }
212742134bc6SMatthias Ringwald #endif
212859066796SMatthias Ringwald 
21293deb3ec6SMatthias Ringwald // distributed key generation
2130d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
21313deb3ec6SMatthias Ringwald     switch (dkg_state){
21323deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
21333deb3ec6SMatthias Ringwald             // already busy?
21343deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2135d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
21363deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2137d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2138d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2139d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_irk, sm_handle_encryption_result_dkg_irk, NULL);
2140d7f1c72eSMatthias Ringwald                 return true;
21413deb3ec6SMatthias Ringwald             }
21423deb3ec6SMatthias Ringwald             break;
21433deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
21443deb3ec6SMatthias Ringwald             // already busy?
21453deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2146d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
21473deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2148d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2149d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2150d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_ir, sm_aes128_plaintext, sm_persistent_dhk, sm_handle_encryption_result_dkg_dhk, NULL);
2151d7f1c72eSMatthias Ringwald                 return true;
21523deb3ec6SMatthias Ringwald             }
21533deb3ec6SMatthias Ringwald             break;
21543deb3ec6SMatthias Ringwald         default:
21553deb3ec6SMatthias Ringwald             break;
21563deb3ec6SMatthias Ringwald     }
2157d7f1c72eSMatthias Ringwald     return false;
2158d7f1c72eSMatthias Ringwald }
21593deb3ec6SMatthias Ringwald 
21603deb3ec6SMatthias Ringwald // random address updates
2161d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21623deb3ec6SMatthias Ringwald     switch (rau_state){
2163fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2164fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21655b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2166d7f1c72eSMatthias Ringwald             return true;
21673deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21683deb3ec6SMatthias Ringwald             // already busy?
21693deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2170d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2171d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2172d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2173d7f1c72eSMatthias Ringwald                 return true;
21743deb3ec6SMatthias Ringwald             }
21753deb3ec6SMatthias Ringwald             break;
21763deb3ec6SMatthias Ringwald         default:
21773deb3ec6SMatthias Ringwald             break;
21783deb3ec6SMatthias Ringwald     }
2179d7f1c72eSMatthias Ringwald     return false;
2180d7f1c72eSMatthias Ringwald }
21813deb3ec6SMatthias Ringwald 
21823deb3ec6SMatthias Ringwald // CSRK Lookup
2183d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2184d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2185d7f1c72eSMatthias Ringwald 
21863deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21873deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21883deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2189665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2190665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21913deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21923deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21933deb3ec6SMatthias Ringwald                 // and start lookup
21943deb3ec6SMatthias Ringwald                 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);
21953deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21963deb3ec6SMatthias Ringwald                 break;
21973deb3ec6SMatthias Ringwald             }
21983deb3ec6SMatthias Ringwald         }
21993deb3ec6SMatthias Ringwald     }
22003deb3ec6SMatthias Ringwald 
22013deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
22023deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2203665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
22043deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2205665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
22063deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
22073deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
22083deb3ec6SMatthias Ringwald         }
22093deb3ec6SMatthias Ringwald     }
22103deb3ec6SMatthias Ringwald 
2211ca685291SMatthias Ringwald     // -- Continue with device lookup by public or resolvable private address
22123deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2213092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2214adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
22153deb3ec6SMatthias Ringwald             bd_addr_t addr;
22163deb3ec6SMatthias Ringwald             sm_key_t irk;
22173deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
22183deb3ec6SMatthias Ringwald 
2219adf5eaa9SMatthias Ringwald             // skip unused entries
2220adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2221adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2222adf5eaa9SMatthias Ringwald                 continue;
2223adf5eaa9SMatthias Ringwald             }
2224adf5eaa9SMatthias Ringwald 
2225ca685291SMatthias Ringwald             log_info("LE Device Lookup: device %u of %u", sm_address_resolution_test, le_device_db_max_count());
2226ca685291SMatthias Ringwald 
22275df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
2228ca685291SMatthias Ringwald                 log_info("LE Device Lookup: found by { addr_type, address} ");
2229a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
22303deb3ec6SMatthias Ringwald                 break;
22313deb3ec6SMatthias Ringwald             }
22323deb3ec6SMatthias Ringwald 
2233a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2234a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
22353deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
22363deb3ec6SMatthias Ringwald                 continue;
22373deb3ec6SMatthias Ringwald             }
22383deb3ec6SMatthias Ringwald 
22398cc81b50SMatthias Ringwald             // skip AH if no IRK
22408cc81b50SMatthias Ringwald             if (sm_is_null_key(irk)){
22418cc81b50SMatthias Ringwald                 sm_address_resolution_test++;
22428cc81b50SMatthias Ringwald                 continue;
22438cc81b50SMatthias Ringwald             }
22448cc81b50SMatthias Ringwald 
22453deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
22463deb3ec6SMatthias Ringwald 
22473deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
22488314c363SMatthias Ringwald             log_info_key("IRK", irk);
22493deb3ec6SMatthias Ringwald 
22506535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2251d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
2252d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2253d1a1f6a4SMatthias Ringwald             btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_aes128_key, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_address_resolution, NULL);
2254d7f1c72eSMatthias Ringwald             return true;
22553deb3ec6SMatthias Ringwald         }
22563deb3ec6SMatthias Ringwald 
2257092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22583deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22593deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22603deb3ec6SMatthias Ringwald         }
22613deb3ec6SMatthias Ringwald     }
2262d7f1c72eSMatthias Ringwald     return false;
2263d7f1c72eSMatthias Ringwald }
22643deb3ec6SMatthias Ringwald 
2265d7f1c72eSMatthias Ringwald // SC OOB
2266d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2267c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2268c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2269c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2270c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2271c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2272c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2273d7f1c72eSMatthias Ringwald             return true;
2274c59d0c92SMatthias Ringwald         default:
2275c59d0c92SMatthias Ringwald             break;
2276c59d0c92SMatthias Ringwald     }
2277c59d0c92SMatthias Ringwald #endif
2278d7f1c72eSMatthias Ringwald     return false;
2279d7f1c72eSMatthias Ringwald }
2280275aafe8SMatthias Ringwald 
2281687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2282687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2283687a03c8SMatthias Ringwald }
2284687a03c8SMatthias Ringwald 
228541d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2286d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2287d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
228841d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2289e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
229041d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
229141d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
229241d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2293f4935286SMatthias Ringwald 
2294f4935286SMatthias Ringwald             // general
2295f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2296f4935286SMatthias Ringwald                 uint8_t buffer[2];
2297f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2298f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2299f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2300687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2301f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2302f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2303f4935286SMatthias Ringwald                 break;
2304f4935286SMatthias Ringwald             }
2305f4935286SMatthias Ringwald 
230641d32297SMatthias Ringwald             // responder side
230741d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
230841d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
230941d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2310d7f1c72eSMatthias Ringwald                 return true;
23114b8b5afeSMatthias Ringwald 
23124b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
23134b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
23144b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
23154b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2316e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
23174b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
23184b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2319d7f1c72eSMatthias Ringwald                         return true;
23204b8b5afeSMatthias Ringwald                     default:
23214b8b5afeSMatthias Ringwald                         break;
23224b8b5afeSMatthias Ringwald                 }
23234b8b5afeSMatthias Ringwald                 break;
23244b8b5afeSMatthias Ringwald #endif
232541d32297SMatthias Ringwald             default:
232641d32297SMatthias Ringwald                 break;
232741d32297SMatthias Ringwald         }
232841d32297SMatthias Ringwald     }
2329d7f1c72eSMatthias Ringwald     return false;
2330d7f1c72eSMatthias Ringwald }
23313deb3ec6SMatthias Ringwald 
2332d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
23333deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2334d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
23353deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
23367149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2337665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
23383deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
23393deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
23401979f09cSMatthias Ringwald         bool done = true;
23413deb3ec6SMatthias Ringwald         int err;
234242134bc6SMatthias Ringwald         UNUSED(err);
234334b6528fSMatthias Ringwald 
234434b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
234534b6528fSMatthias Ringwald         // assert ec key is ready
2346505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2347178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2348178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
234934b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
235034b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
235134b6528fSMatthias Ringwald             }
235234b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
235334b6528fSMatthias Ringwald                 continue;
235434b6528fSMatthias Ringwald             }
235534b6528fSMatthias Ringwald         }
235634b6528fSMatthias Ringwald #endif
235734b6528fSMatthias Ringwald 
23583deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
235942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23603deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23613deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
236242134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2363549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
236406cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
236587014f74SMatthias Ringwald #endif
236687014f74SMatthias Ringwald #endif
236734c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23685567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
236934c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2370549ad5d2SMatthias Ringwald #endif
2371c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2372c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2373c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2374c18be159SMatthias Ringwald #endif
237587014f74SMatthias Ringwald 				// just lock context
237687014f74SMatthias Ringwald 				break;
23773deb3ec6SMatthias Ringwald             default:
23781979f09cSMatthias Ringwald                 done = false;
23793deb3ec6SMatthias Ringwald                 break;
23803deb3ec6SMatthias Ringwald         }
23813deb3ec6SMatthias Ringwald         if (done){
23827149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23837149bde5SMatthias Ringwald             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);
23843deb3ec6SMatthias Ringwald         }
23853deb3ec6SMatthias Ringwald     }
2386d7f1c72eSMatthias Ringwald }
2387d7f1c72eSMatthias Ringwald 
2388403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2389403280b9SMatthias Ringwald     int i;
2390403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2391403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2392403280b9SMatthias Ringwald     uint8_t action = 0;
2393403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2394403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2395403280b9SMatthias Ringwald             bool clear_flag = true;
2396403280b9SMatthias Ringwald             switch (i){
2397403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2398403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2399403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2400403280b9SMatthias Ringwald                 default:
2401403280b9SMatthias Ringwald                     break;
2402403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2403403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2404403280b9SMatthias Ringwald                     num_actions--;
2405403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2406403280b9SMatthias Ringwald                     break;
2407403280b9SMatthias Ringwald             }
2408403280b9SMatthias Ringwald             if (clear_flag){
2409403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2410403280b9SMatthias Ringwald             }
2411403280b9SMatthias Ringwald             action = i;
2412403280b9SMatthias Ringwald             break;
2413403280b9SMatthias Ringwald         }
2414403280b9SMatthias Ringwald     }
2415403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2416403280b9SMatthias Ringwald 
2417403280b9SMatthias Ringwald     // send keypress notification
2418403280b9SMatthias Ringwald     uint8_t buffer[2];
2419403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2420403280b9SMatthias Ringwald     buffer[1] = action;
2421687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2422403280b9SMatthias Ringwald 
2423403280b9SMatthias Ringwald     // try
2424384eabd3SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2425403280b9SMatthias Ringwald }
2426403280b9SMatthias Ringwald 
2427403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2428403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2429403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2430403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2431403280b9SMatthias Ringwald         uint8_t buffer[17];
2432403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2433403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2434687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2435403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2436403280b9SMatthias Ringwald         return;
2437403280b9SMatthias Ringwald     }
2438403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2439403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2440403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2441403280b9SMatthias Ringwald         uint8_t buffer[11];
2442403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2443403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2444403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2445687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2446403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2447403280b9SMatthias Ringwald         return;
2448403280b9SMatthias Ringwald     }
2449403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2450403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2451403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2452403280b9SMatthias Ringwald         uint8_t buffer[17];
2453403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2454403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2455687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2456403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2457403280b9SMatthias Ringwald         return;
2458403280b9SMatthias Ringwald     }
2459403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2460403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2461403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2462403280b9SMatthias Ringwald         bd_addr_t local_address;
2463403280b9SMatthias Ringwald         uint8_t buffer[8];
2464403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2465403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2466403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2467403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2468403280b9SMatthias Ringwald                 // public or static random
2469403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2470403280b9SMatthias Ringwald                 break;
2471403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2472403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2473403280b9SMatthias Ringwald                 // fallback to public
2474403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2475403280b9SMatthias Ringwald                 buffer[1] = 0;
2476403280b9SMatthias Ringwald                 break;
2477403280b9SMatthias Ringwald             default:
2478403280b9SMatthias Ringwald                 btstack_assert(false);
2479403280b9SMatthias Ringwald                 break;
2480403280b9SMatthias Ringwald         }
2481403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2482687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2483403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2484403280b9SMatthias Ringwald         return;
2485403280b9SMatthias Ringwald     }
2486403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2487403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2488403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2489403280b9SMatthias Ringwald 
2490403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2491403280b9SMatthias Ringwald         // hack to reproduce test runs
2492403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2493403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2494403280b9SMatthias Ringwald                     }
2495403280b9SMatthias Ringwald 
2496403280b9SMatthias Ringwald                     // store local CSRK
2497403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2498403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2499403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2500403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2501403280b9SMatthias Ringwald                     }
2502403280b9SMatthias Ringwald #endif
2503403280b9SMatthias Ringwald 
2504403280b9SMatthias Ringwald         uint8_t buffer[17];
2505403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2506403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2507687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2508403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2509403280b9SMatthias Ringwald         return;
2510403280b9SMatthias Ringwald     }
2511403280b9SMatthias Ringwald     btstack_assert(false);
2512403280b9SMatthias Ringwald }
2513403280b9SMatthias Ringwald 
2514bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2515bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2516bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2517bbd73538SMatthias Ringwald     // - use secure connections
2518bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2519bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2520bbd73538SMatthias Ringwald     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;
2521bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2522bbd73538SMatthias Ringwald     // - need identity address / public addr
2523bbd73538SMatthias Ringwald     bool have_identity_address_info = ((setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION) != 0) || (setup->sm_peer_addr_type == 0);
2524bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2525bbd73538SMatthias Ringwald     // - 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)
2526bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2527bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2528bbd73538SMatthias Ringwald     //      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.
2529bbd73538SMatthias Ringwald     uint8_t link_key[16];
2530bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2531bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
25327040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2533bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2534bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2535bbd73538SMatthias Ringwald         return false;
2536bbd73538SMatthias Ringwald     }
2537bbd73538SMatthias Ringwald     // get started (all of the above are true)
2538bbd73538SMatthias Ringwald     return true;
2539bbd73538SMatthias Ringwald #else
2540bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2541bbd73538SMatthias Ringwald 	return false;
2542bbd73538SMatthias Ringwald #endif
2543bbd73538SMatthias Ringwald }
2544bbd73538SMatthias Ringwald 
25456f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
25466f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
25476f7422f1SMatthias Ringwald         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;
25486f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
25496f7422f1SMatthias Ringwald     } else {
25506f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
25516f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
25526f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25536f7422f1SMatthias Ringwald     }
25546f7422f1SMatthias Ringwald }
25556f7422f1SMatthias Ringwald 
2556af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2557af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2558af7ef9d1SMatthias Ringwald         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;
2559af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2560af7ef9d1SMatthias Ringwald     } else {
2561af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2562af7ef9d1SMatthias Ringwald     }
2563af7ef9d1SMatthias Ringwald }
2564af7ef9d1SMatthias Ringwald 
2565d7f1c72eSMatthias Ringwald static void sm_run(void){
2566d7f1c72eSMatthias Ringwald 
2567d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2568d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2569d7f1c72eSMatthias Ringwald 
2570d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2571d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2572d7f1c72eSMatthias Ringwald 
2573d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2574d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2575d7f1c72eSMatthias Ringwald 
2576d7f1c72eSMatthias Ringwald     bool done;
2577d7f1c72eSMatthias Ringwald 
2578d7f1c72eSMatthias Ringwald     //
2579d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2580d7f1c72eSMatthias Ringwald     //
2581d7f1c72eSMatthias Ringwald 
2582d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2583d7f1c72eSMatthias Ringwald     if (done) return;
2584d7f1c72eSMatthias Ringwald 
2585d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2586d7f1c72eSMatthias Ringwald     if (done) return;
2587d7f1c72eSMatthias Ringwald 
2588d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2589d7f1c72eSMatthias Ringwald     if (done) return;
2590d7f1c72eSMatthias Ringwald 
2591d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2592d7f1c72eSMatthias Ringwald     if (done) return;
2593d7f1c72eSMatthias Ringwald 
2594d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2595d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2596d7f1c72eSMatthias Ringwald 
2597d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2598d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2599d7f1c72eSMatthias Ringwald     if (done) return;
2600d7f1c72eSMatthias Ringwald 
2601d7f1c72eSMatthias Ringwald     //
2602d7f1c72eSMatthias Ringwald     // active connection handling
2603d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2604d7f1c72eSMatthias Ringwald 
2605d7f1c72eSMatthias Ringwald     while (true) {
2606d7f1c72eSMatthias Ringwald 
2607d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2608d7f1c72eSMatthias Ringwald 
2609d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
26103deb3ec6SMatthias Ringwald 
26113deb3ec6SMatthias Ringwald         //
26123deb3ec6SMatthias Ringwald         // active connection handling
26133deb3ec6SMatthias Ringwald         //
26143deb3ec6SMatthias Ringwald 
26153cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
26163cf37b8cSMatthias Ringwald         if (!connection) {
26173cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
26183cf37b8cSMatthias Ringwald             return;
26193cf37b8cSMatthias Ringwald         }
26203cf37b8cSMatthias Ringwald 
26213deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
2622384eabd3SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, connection->sm_cid)) {
26237149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
2624384eabd3SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, connection->sm_cid);
2625b170b20fSMatthias Ringwald             return;
2626b170b20fSMatthias Ringwald         }
26273deb3ec6SMatthias Ringwald 
26283d7fe1e9SMatthias Ringwald         // send keypress notifications
2629dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2630403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2631d7471931SMatthias Ringwald             return;
26323d7fe1e9SMatthias Ringwald         }
26333d7fe1e9SMatthias Ringwald 
2634f7ea4423SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2635234022e5SMatthias Ringwald         // assert that sm cmac engine is ready
2636234022e5SMatthias Ringwald         if (sm_cmac_ready() == false){
2637234022e5SMatthias Ringwald             break;
2638234022e5SMatthias Ringwald         }
2639f7ea4423SMatthias Ringwald #endif
2640234022e5SMatthias Ringwald 
26413deb3ec6SMatthias Ringwald         int key_distribution_flags;
264242134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2643b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2644b6afa23eSMatthias Ringwald         int err;
26459b75de03SMatthias Ringwald         bool have_ltk;
26469b75de03SMatthias Ringwald         uint8_t ltk[16];
2647b6f39a74SMatthias Ringwald #endif
26483deb3ec6SMatthias Ringwald 
26493deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
26503deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
26513deb3ec6SMatthias Ringwald 
2652f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2653aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2654aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2655aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2656aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2657aec94140SMatthias Ringwald                 break;
2658688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2659688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2660688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2661688a08f9SMatthias Ringwald                 break;
2662dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2663dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2664dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2665dc300847SMatthias Ringwald                 break;
2666019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2667019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26680346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26690346c37cSMatthias Ringwald                 break;
26700346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
26710346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26720346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26730346c37cSMatthias Ringwald                 break;
26740346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
26750346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26760346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26770346c37cSMatthias Ringwald                 break;
26780346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
26790346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26800346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2681019005a0SMatthias Ringwald                 break;
2682bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2683bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2684b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2685bd57ffebSMatthias Ringwald                 break;
2686e0a03c85SMatthias Ringwald #endif
2687e0a03c85SMatthias Ringwald 
268842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26893deb3ec6SMatthias Ringwald             // initiator side
2690f32b7a88SMatthias Ringwald 
26915567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2692f32b7a88SMatthias Ringwald 				sm_reset_setup();
2693f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2694f32b7a88SMatthias Ringwald 
26953deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26969c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26975567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26983deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2699c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2700c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
27013deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
270249c9e430SMatthias Ringwald 
270349c9e430SMatthias Ringwald                 // notify after sending
270449c9e430SMatthias Ringwald                 sm_reencryption_started(connection);
27053deb3ec6SMatthias Ringwald                 return;
27063deb3ec6SMatthias Ringwald             }
27073deb3ec6SMatthias Ringwald 
2708b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2709b26f445fSMatthias Ringwald 				sm_reset_setup();
2710b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2711b26f445fSMatthias Ringwald 
27121ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
27133deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2714687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
27153deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
271649c9e430SMatthias Ringwald 
271749c9e430SMatthias Ringwald                 // notify after sending
271849c9e430SMatthias Ringwald                 sm_pairing_started(connection);
27193deb3ec6SMatthias Ringwald                 break;
272042134bc6SMatthias Ringwald #endif
27213deb3ec6SMatthias Ringwald 
272227c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
272341d32297SMatthias Ringwald 
2724c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
27251979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
27261979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
272727c32905SMatthias Ringwald                 uint8_t buffer[65];
272827c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
272927c32905SMatthias Ringwald                 //
2730fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2731fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2732e53be891SMatthias Ringwald 
2733349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2734349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2735349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2736349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2737349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2738349d0adbSMatthias Ringwald                 }
2739349d0adbSMatthias Ringwald #endif
2740349d0adbSMatthias Ringwald 
274145a61d50SMatthias Ringwald                 // stk generation method
274245a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
274345a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
274445a61d50SMatthias Ringwald                     case JUST_WORKS:
274547fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
274642134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
274707036a04SMatthias Ringwald                             // responder
27481979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2749b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
275027c32905SMatthias Ringwald                         } else {
275107036a04SMatthias Ringwald                             // initiator
2752c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
275327c32905SMatthias Ringwald                         }
275445a61d50SMatthias Ringwald                         break;
275545a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
275645a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
275747fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
275807036a04SMatthias Ringwald                         // use random TK for display
27596535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27606535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
276145a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
276207036a04SMatthias Ringwald 
276342134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
276445a61d50SMatthias Ringwald                             // responder
2765c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
276645a61d50SMatthias Ringwald                         } else {
276745a61d50SMatthias Ringwald                             // initiator
2768c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
276945a61d50SMatthias Ringwald                         }
27701979f09cSMatthias Ringwald                         trigger_user_response = true;
277145a61d50SMatthias Ringwald                         break;
277245a61d50SMatthias Ringwald                     case OOB:
277365a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
277465a9a04eSMatthias Ringwald                             // responder
277565a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
277665a9a04eSMatthias Ringwald                         } else {
277765a9a04eSMatthias Ringwald                             // initiator
277865a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
277965a9a04eSMatthias Ringwald                         }
278045a61d50SMatthias Ringwald                         break;
27817bbeb3adSMilanka Ringwald                     default:
27827bbeb3adSMilanka Ringwald                         btstack_assert(false);
27837bbeb3adSMilanka Ringwald                         break;
278445a61d50SMatthias Ringwald                 }
278545a61d50SMatthias Ringwald 
2786687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
278727c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2788644c6a1dSMatthias Ringwald 
2789b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2790644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2791644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2792644c6a1dSMatthias Ringwald                 }
2793b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2794b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2795b90c4e75SMatthias Ringwald                 }
279627c32905SMatthias Ringwald                 break;
279727c32905SMatthias Ringwald             }
2798c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2799e53be891SMatthias Ringwald                 uint8_t buffer[17];
2800e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
28019af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
280242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2803c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2804e53be891SMatthias Ringwald                 } else {
2805c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2806e53be891SMatthias Ringwald                 }
2807687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2808e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2809e53be891SMatthias Ringwald                 break;
2810e53be891SMatthias Ringwald             }
2811c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2812e53be891SMatthias Ringwald                 uint8_t buffer[17];
2813e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2814e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
28159d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
28164ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
281740c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
281842134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
281945a61d50SMatthias Ringwald                         // responder
2820c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
282145a61d50SMatthias Ringwald                     } else {
282245a61d50SMatthias Ringwald                         // initiator
2823c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
282445a61d50SMatthias Ringwald                     }
282545a61d50SMatthias Ringwald                 } else {
282640c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
282742134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2828e53be891SMatthias Ringwald                         // responder
282947fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
283040c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2831901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
28322886623dSMatthias Ringwald                         } else {
283340c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
28342886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2835446a8c36SMatthias Ringwald                         }
2836e53be891SMatthias Ringwald                     } else {
2837136d331aSMatthias Ringwald                         // initiator
2838c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2839e53be891SMatthias Ringwald                     }
284045a61d50SMatthias Ringwald                 }
2841687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2842e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2843e53be891SMatthias Ringwald                 break;
2844e53be891SMatthias Ringwald             }
2845c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2846e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2847e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2848e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2849dc300847SMatthias Ringwald 
285042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2851c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2852e53be891SMatthias Ringwald                 } else {
2853c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2854e53be891SMatthias Ringwald                 }
2855e083ca23SMatthias Ringwald 
2856687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2857e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2858e53be891SMatthias Ringwald                 break;
2859e53be891SMatthias Ringwald             }
2860e53be891SMatthias Ringwald 
2861e53be891SMatthias Ringwald #endif
286242134bc6SMatthias Ringwald 
286342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2864dd12a62bSMatthias Ringwald 
286587014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
286687014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
286787014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2868687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2869c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
287087014f74SMatthias Ringwald 				break;
287187014f74SMatthias Ringwald 			}
287287014f74SMatthias Ringwald 
287338196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
287438196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
287538196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
287638196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
287738196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
287838196718SMatthias Ringwald 						// start using context by loading security info
287938196718SMatthias Ringwald 						sm_reset_setup();
288038196718SMatthias Ringwald 						sm_load_security_info(connection);
288138196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
288238196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
288338196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
288442646f38SMatthias Ringwald                             sm_reencryption_started(connection);
288538196718SMatthias Ringwald                             sm_trigger_run();
288638196718SMatthias Ringwald 							break;
288738196718SMatthias Ringwald 						}
288838196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
288938196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
289038196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
289138196718SMatthias Ringwald 						return;
289238196718SMatthias Ringwald 					default:
289338196718SMatthias Ringwald 						// just wait until IRK lookup is completed
289438196718SMatthias Ringwald 						break;
289538196718SMatthias Ringwald 				}
289638196718SMatthias Ringwald 				break;
289738196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
289838196718SMatthias Ringwald 
2899b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2900b6afa23eSMatthias Ringwald                 sm_reset_setup();
29019b75de03SMatthias Ringwald 
29029b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
29039b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
29049b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
29059b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
29069b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
29079b75de03SMatthias Ringwald                         if (have_ltk){
29089b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
290919a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
29109b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
29119b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
29129b75de03SMatthias Ringwald                         }
29139b75de03SMatthias Ringwald                         break;
29149b75de03SMatthias Ringwald                     default:
29159b75de03SMatthias Ringwald                         break;
29169b75de03SMatthias Ringwald                 }
29179b75de03SMatthias Ringwald 
2918b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
291939543d07SMatthias Ringwald 
2920b6afa23eSMatthias Ringwald 				// recover pairing request
2921b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2922b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2923b6afa23eSMatthias Ringwald 
2924b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2925b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2926b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2927b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2928b6afa23eSMatthias Ringwald                     }
2929b6afa23eSMatthias Ringwald #endif
29309305033eSMatthias Ringwald 				if (err != 0){
293149c9e430SMatthias Ringwald                     // emit pairing started/failed sequence
293249c9e430SMatthias Ringwald                     sm_pairing_started(connection);
2933f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2934b6afa23eSMatthias Ringwald 					sm_trigger_run();
2935b6afa23eSMatthias Ringwald 					break;
2936b6afa23eSMatthias Ringwald 				}
2937b6afa23eSMatthias Ringwald 
2938b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2939b6afa23eSMatthias Ringwald 
2940b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2941b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2942b6afa23eSMatthias Ringwald 					btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 8, &sm_handle_random_result_ph2_tk, (void *)(uintptr_t) connection->sm_handle);
2943b6afa23eSMatthias Ringwald 					break;
2944b6afa23eSMatthias Ringwald 				}
2945b6afa23eSMatthias Ringwald 
2946b6afa23eSMatthias Ringwald 				/* fall through */
2947b6afa23eSMatthias Ringwald 
29483deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
29491ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2950f55bd529SMatthias Ringwald 
2951f55bd529SMatthias Ringwald                 // start with initiator key dist flags
29523deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
29531ad129beSMatthias Ringwald 
2954f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2955f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2956f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2957f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2958f55bd529SMatthias Ringwald                 }
2959f55bd529SMatthias Ringwald #endif
2960f55bd529SMatthias Ringwald                 // setup in response
2961f55bd529SMatthias Ringwald                 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);
2962f55bd529SMatthias Ringwald                 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);
2963f55bd529SMatthias Ringwald 
2964f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29659a90d41aSMatthias Ringwald                 sm_setup_key_distribution(sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres), sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres));
2966f55bd529SMatthias Ringwald 
296727c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2968c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29690b8af2a5SMatthias Ringwald                 } else {
29700b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
297127c32905SMatthias Ringwald                 }
29720b8af2a5SMatthias Ringwald 
2973687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29743deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
297549c9e430SMatthias Ringwald 
297649c9e430SMatthias Ringwald                 // notify after sending
297749c9e430SMatthias Ringwald                 sm_pairing_started(connection);
297849c9e430SMatthias Ringwald 
2979446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2980c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29813deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2982446a8c36SMatthias Ringwald                 }
29833deb3ec6SMatthias Ringwald                 return;
298442134bc6SMatthias Ringwald #endif
29853deb3ec6SMatthias Ringwald 
29863deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29873deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29883deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29899c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
299042134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29913deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29923deb3ec6SMatthias Ringwald                 } else {
29933deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29943deb3ec6SMatthias Ringwald                 }
2995687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29963deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29973deb3ec6SMatthias Ringwald                 break;
29983deb3ec6SMatthias Ringwald             }
29993deb3ec6SMatthias Ringwald 
3000d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
30013deb3ec6SMatthias Ringwald                 // already busy?
30023deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
3003d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
3004d1a1f6a4SMatthias Ringwald                 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);
3005d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
3006d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3007f3582630SMatthias Ringwald                 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);
30083deb3ec6SMatthias Ringwald                 break;
30093deb3ec6SMatthias Ringwald 
30103deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
30113deb3ec6SMatthias Ringwald                 // already busy?
30123deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30133deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
3014d1a1f6a4SMatthias Ringwald                 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);
3015d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
3016d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3017f3582630SMatthias Ringwald                 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);
30183deb3ec6SMatthias Ringwald                 break;
3019d1a1f6a4SMatthias Ringwald 
30203deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
30213deb3ec6SMatthias Ringwald                 // already busy?
30223deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30233deb3ec6SMatthias Ringwald                 // calculate STK
302442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
3025d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
30263deb3ec6SMatthias Ringwald                 } else {
3027d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
30283deb3ec6SMatthias Ringwald                 }
3029d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
3030d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3031f3582630SMatthias Ringwald                 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);
30323deb3ec6SMatthias Ringwald                 break;
3033d1a1f6a4SMatthias Ringwald 
30343deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
30353deb3ec6SMatthias Ringwald                 // already busy?
30363deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30373deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
30389ad0dd7cSMatthias Ringwald 
30399ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
30409ad0dd7cSMatthias Ringwald                 // r' = padding || r
30419ad0dd7cSMatthias Ringwald                 // r - 64 bit value
30429ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30436535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
30449ad0dd7cSMatthias Ringwald 
30453deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3046d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
3047d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3048f3582630SMatthias Ringwald                 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);
3049d1a1f6a4SMatthias Ringwald                 break;
3050d1a1f6a4SMatthias Ringwald 
30513deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
30523deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
30533deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
30549c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
305542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30563deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
30573deb3ec6SMatthias Ringwald                 } else {
30583deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30593deb3ec6SMatthias Ringwald                 }
3060687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30613deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30623deb3ec6SMatthias Ringwald                 return;
30633deb3ec6SMatthias Ringwald             }
306442134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30653deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
3066916ea5b2SMatthias Ringwald                 // cache key before using
3067916ea5b2SMatthias Ringwald                 sm_cache_ltk(connection, setup->sm_ltk);
30683deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30699c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30703deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30713deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30723deb3ec6SMatthias Ringwald                 return;
30733deb3ec6SMatthias Ringwald             }
3074d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3075b96d60a6SMatthias Ringwald                 // allow to override LTK
3076b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3077b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3078b96d60a6SMatthias Ringwald                 }
3079916ea5b2SMatthias Ringwald                 // cache key before using
3080916ea5b2SMatthias Ringwald                 sm_cache_ltk(connection, setup->sm_ltk);
30813deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30829c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30835567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30843deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30853deb3ec6SMatthias Ringwald                 return;
30863deb3ec6SMatthias Ringwald             }
3087dd12a62bSMatthias Ringwald 
3088dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30893deb3ec6SMatthias Ringwald                 // already busy?
30903deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30913deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3092c61cfe5aSMatthias Ringwald 
3093dd12a62bSMatthias Ringwald 				sm_reset_setup();
3094dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3095dd12a62bSMatthias Ringwald 
309642646f38SMatthias Ringwald 				sm_reencryption_started(connection);
309742646f38SMatthias Ringwald 
3098c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3099c61cfe5aSMatthias Ringwald                 // r' = padding || r
3100c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3101c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
31026535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3103c61cfe5aSMatthias Ringwald 
31043deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3105d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3106d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3107f3582630SMatthias Ringwald                 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);
31083deb3ec6SMatthias Ringwald                 return;
310942134bc6SMatthias Ringwald #endif
311042134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
311142134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
311242134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
311342134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
311442134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
311542134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
311642134bc6SMatthias Ringwald                 return;
311742134bc6SMatthias Ringwald             }
311842134bc6SMatthias Ringwald #endif
31193deb3ec6SMatthias Ringwald 
31203deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3121e94757aeSMatthias Ringwald                 // send next key
3122403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3123403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
3124e94757aeSMatthias Ringwald                 }
3125e94757aeSMatthias Ringwald 
3126e94757aeSMatthias Ringwald                 // more to send?
3127e94757aeSMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
31283deb3ec6SMatthias Ringwald                     return;
31293deb3ec6SMatthias Ringwald                 }
31303deb3ec6SMatthias Ringwald 
31313deb3ec6SMatthias Ringwald                 // keys are sent
313242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
31333deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
313461d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
31353deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3136f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3137f5020412SMatthias Ringwald                         // start CTKD right away
3138f5020412SMatthias Ringwald                         continue;
31393deb3ec6SMatthias Ringwald                     } else {
31403deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
31413deb3ec6SMatthias Ringwald                     }
31423deb3ec6SMatthias Ringwald                 } else {
31431dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
31443deb3ec6SMatthias Ringwald                 }
31453deb3ec6SMatthias Ringwald                 break;
31463deb3ec6SMatthias Ringwald 
3147c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3148c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3149c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3150c18be159SMatthias Ringwald                 sm_reset_setup();
3151c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3152c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3153c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3154c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3155c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3156c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3157c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3158c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3159c18be159SMatthias Ringwald 
3160c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3161c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3162c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3163c18be159SMatthias Ringwald                 // Plus signing key if supported
3164c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3165c18be159SMatthias Ringwald #endif
3166c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3167c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3168c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3169c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3170c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3171c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3172c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3173c18be159SMatthias Ringwald 
3174c18be159SMatthias Ringwald                 // set state and send pairing response
3175c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3176c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3177c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3178c18be159SMatthias Ringwald                 break;
3179c18be159SMatthias Ringwald 
3180c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3181c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3182c18be159SMatthias Ringwald                 sm_reset_setup();
3183c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3184c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3185c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3186c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3187c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3188c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3189c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3190c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3191c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3192c18be159SMatthias Ringwald 
3193c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3194c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3195c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3196c18be159SMatthias Ringwald                 // Plus signing key if supported
3197c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3198c18be159SMatthias Ringwald #endif
3199c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3200c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3201c18be159SMatthias Ringwald 
3202c18be159SMatthias Ringwald                 // If Secure Connections pairing has been initiated over BR/EDR, the following fields of the SM Pairing Request PDU are reserved for future use:
3203c18be159SMatthias Ringwald                 // - the IO Capability field,
3204c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3205c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3206c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3207c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3208c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3209c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3210c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3211c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3212c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3213c18be159SMatthias Ringwald 
3214c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3215c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3216c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3217c18be159SMatthias Ringwald 
3218c18be159SMatthias Ringwald                 // set state and send pairing response
3219c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3220c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3221c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3222c18be159SMatthias Ringwald                 break;
3223c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3224c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3225c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3226c18be159SMatthias Ringwald                     return;
3227c18be159SMatthias Ringwald                 }
3228c18be159SMatthias Ringwald                 // keys are sent
3229c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3230c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
323161d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3232c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3233c18be159SMatthias Ringwald                         break;
3234c18be159SMatthias Ringwald                     }
3235c18be159SMatthias Ringwald                 }
3236c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3237c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3238c18be159SMatthias Ringwald                 continue;
3239c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3240c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3241c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3242c18be159SMatthias Ringwald                 break;
3243c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3244c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3245c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3246c18be159SMatthias Ringwald                 break;
3247c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3248c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3249c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3250c18be159SMatthias Ringwald                 break;
3251c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3252c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3253c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3254c18be159SMatthias Ringwald                 break;
3255c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3256c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3257c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3258c18be159SMatthias Ringwald                 break;
3259c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3260c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3261c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3262c18be159SMatthias Ringwald                 break;
3263c18be159SMatthias Ringwald #endif
3264c18be159SMatthias Ringwald 
32653deb3ec6SMatthias Ringwald             default:
32663deb3ec6SMatthias Ringwald                 break;
32673deb3ec6SMatthias Ringwald         }
32683deb3ec6SMatthias Ringwald 
32693deb3ec6SMatthias Ringwald         // check again if active connection was released
32707149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32713deb3ec6SMatthias Ringwald     }
32723deb3ec6SMatthias Ringwald }
32733deb3ec6SMatthias Ringwald 
3274d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3275d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3276f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
327804678764SMatthias Ringwald 
3279f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3280f3582630SMatthias Ringwald     if (connection == NULL) return;
3281f3582630SMatthias Ringwald 
3282d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
328304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3284f3582630SMatthias Ringwald     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);
3285d1a1f6a4SMatthias Ringwald }
32863deb3ec6SMatthias Ringwald 
3287d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3288f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
328904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329004678764SMatthias Ringwald 
3291f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3292f3582630SMatthias Ringwald     if (connection == NULL) return;
3293f3582630SMatthias Ringwald 
32948314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32953deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
329670b44dd4SMatthias Ringwald     sm_trigger_run();
3297d1a1f6a4SMatthias Ringwald }
3298d1a1f6a4SMatthias Ringwald 
3299d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3300d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3301f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
330204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
330304678764SMatthias Ringwald 
3304f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3305f3582630SMatthias Ringwald     if (connection == NULL) return;
3306f3582630SMatthias Ringwald 
3307d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
330804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3309f3582630SMatthias Ringwald     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);
3310d1a1f6a4SMatthias Ringwald }
3311d1a1f6a4SMatthias Ringwald 
3312d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3313f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
331404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
331504678764SMatthias Ringwald 
3316f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3317f3582630SMatthias Ringwald     if (connection == NULL) return;
3318f3582630SMatthias Ringwald 
3319d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3320d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3321f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
332270b44dd4SMatthias Ringwald         sm_trigger_run();
33233deb3ec6SMatthias Ringwald         return;
33243deb3ec6SMatthias Ringwald     }
332542134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33263deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
332770b44dd4SMatthias Ringwald         sm_trigger_run();
33283deb3ec6SMatthias Ringwald     } else {
3329d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3330d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3331f3582630SMatthias Ringwald         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);
33323deb3ec6SMatthias Ringwald     }
33333deb3ec6SMatthias Ringwald }
3334d1a1f6a4SMatthias Ringwald 
3335d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
333604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3337f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333804678764SMatthias Ringwald 
3339f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3340f3582630SMatthias Ringwald     if (connection == NULL) return;
3341f3582630SMatthias Ringwald 
33423deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33438314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
334442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
33453deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
33463deb3ec6SMatthias Ringwald     } else {
33473deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
33483deb3ec6SMatthias Ringwald     }
334970b44dd4SMatthias Ringwald     sm_trigger_run();
3350d1a1f6a4SMatthias Ringwald }
3351d1a1f6a4SMatthias Ringwald 
3352d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3353d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3354f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
335504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
335604678764SMatthias Ringwald 
3357f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3358f3582630SMatthias Ringwald     if (connection == NULL) return;
3359f3582630SMatthias Ringwald 
3360d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33613deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33623deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33633deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33643deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33653deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33663deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3367d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
336804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3369f3582630SMatthias Ringwald     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);
33703deb3ec6SMatthias Ringwald }
3371d1a1f6a4SMatthias Ringwald 
33722a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3373d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3374d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
337504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3376f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
337704678764SMatthias Ringwald 
3378f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3379f3582630SMatthias Ringwald     if (connection == NULL) return;
3380f3582630SMatthias Ringwald 
3381d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33823deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33833deb3ec6SMatthias Ringwald 
33843deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33853deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33863deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33873deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33883deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3389d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
339004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3391f3582630SMatthias Ringwald     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);
33923deb3ec6SMatthias Ringwald }
33932a526f21SMatthias Ringwald #endif
3394d1a1f6a4SMatthias Ringwald 
3395d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3396d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3397f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
339804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339904678764SMatthias Ringwald 
3400f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3401f3582630SMatthias Ringwald     if (connection == NULL) return;
3402f3582630SMatthias Ringwald 
34038314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
34043deb3ec6SMatthias Ringwald     // calc CSRK next
3405d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
340604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3407f3582630SMatthias Ringwald     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);
3408d1a1f6a4SMatthias Ringwald }
3409d1a1f6a4SMatthias Ringwald 
3410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3411f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
341204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341304678764SMatthias Ringwald 
3414f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3415f3582630SMatthias Ringwald     if (connection == NULL) return;
3416f3582630SMatthias Ringwald 
3417d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
34188314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
34193deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
34203deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
34213deb3ec6SMatthias Ringwald     } else {
34223deb3ec6SMatthias Ringwald         // no keys to send, just continue
342342134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
342461d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3425c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3426c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3427c5a72e35SMatthias Ringwald             } else {
34283deb3ec6SMatthias Ringwald                 // slave -> receive master keys
34293deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3430c5a72e35SMatthias Ringwald             }
34313deb3ec6SMatthias Ringwald         } else {
3432af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
34333deb3ec6SMatthias Ringwald         }
34342bacf595SMatthias Ringwald     }
343570b44dd4SMatthias Ringwald     sm_trigger_run();
3436d1a1f6a4SMatthias Ringwald }
3437d1a1f6a4SMatthias Ringwald 
343842134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3439d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3440f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
344104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
344204678764SMatthias Ringwald 
3443f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3444f3582630SMatthias Ringwald     if (connection == NULL) return;
3445f3582630SMatthias Ringwald 
34463deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
34478314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3448d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
344970b44dd4SMatthias Ringwald     sm_trigger_run();
3450d1a1f6a4SMatthias Ringwald }
3451d1a1f6a4SMatthias Ringwald #endif
3452d1a1f6a4SMatthias Ringwald 
3453d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3454d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3455d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
345604678764SMatthias Ringwald 
3457d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3458d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3459d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3460d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3461a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
346270b44dd4SMatthias Ringwald         sm_trigger_run();
34633deb3ec6SMatthias Ringwald         return;
34643deb3ec6SMatthias Ringwald     }
3465d1a1f6a4SMatthias Ringwald     // no match, try next
3466d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
346770b44dd4SMatthias Ringwald     sm_trigger_run();
34683deb3ec6SMatthias Ringwald }
34693deb3ec6SMatthias Ringwald 
3470d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3471d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3472d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
347304678764SMatthias Ringwald 
3474d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3475d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
347670b44dd4SMatthias Ringwald     sm_trigger_run();
34777df18c15SMatthias Ringwald }
3478d1a1f6a4SMatthias Ringwald 
3479d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3480d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3481d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
348204678764SMatthias Ringwald 
3483d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3484d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
348570b44dd4SMatthias Ringwald     sm_trigger_run();
34867df18c15SMatthias Ringwald }
3487d1a1f6a4SMatthias Ringwald 
3488d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3489d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3490d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
349104678764SMatthias Ringwald 
34926535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3493e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3494e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3495e91ddb40SMatthias Ringwald 
349670b44dd4SMatthias Ringwald     sm_trigger_run();
349751fa0b28SMatthias Ringwald }
34987df18c15SMatthias Ringwald 
3499d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3500d1a1f6a4SMatthias Ringwald     UNUSED(arg);
35013deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
35023deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
35033deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
35043deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
35053deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
35064ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35074ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
35083deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
35093deb3ec6SMatthias Ringwald             break;
35103deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
35113deb3ec6SMatthias Ringwald         default:
35123deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
35134ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
35142954e6c6SMatthias Ringwald             rau_state = RAU_IDLE;
3515e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
35163deb3ec6SMatthias Ringwald             break;
35173deb3ec6SMatthias Ringwald     }
351870b44dd4SMatthias Ringwald     sm_trigger_run();
35193deb3ec6SMatthias Ringwald }
35203deb3ec6SMatthias Ringwald 
3521c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
35226ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3523f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3524f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3525f3582630SMatthias Ringwald     if (connection == NULL) return;
3526c59d0c92SMatthias Ringwald 
352765a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
352870b44dd4SMatthias Ringwald     sm_trigger_run();
352965a9a04eSMatthias Ringwald }
3530d1a1f6a4SMatthias Ringwald 
35316ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
35326ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
35336ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
35346ca80073SMatthias Ringwald     if (connection == NULL) return;
35356ca80073SMatthias Ringwald 
3536b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
353770b44dd4SMatthias Ringwald     sm_trigger_run();
3538d1a1f6a4SMatthias Ringwald }
3539f1c1783eSMatthias Ringwald #endif
3540f1c1783eSMatthias Ringwald 
3541d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3542f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3543f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3544f3582630SMatthias Ringwald     if (connection == NULL) return;
3545f3582630SMatthias Ringwald 
3546d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
354770b44dd4SMatthias Ringwald     sm_trigger_run();
3548d1a1f6a4SMatthias Ringwald }
3549d1a1f6a4SMatthias Ringwald 
3550d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3551f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3552f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3553f3582630SMatthias Ringwald     if (connection == NULL) return;
3554f3582630SMatthias Ringwald 
3555caf15bf3SMatthias Ringwald     sm_reset_tk();
3556caf15bf3SMatthias Ringwald     uint32_t tk;
35575ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
35583deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3559d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
35603deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35614ea43905SMatthias Ringwald         if (tk >= 999999u){
35624ea43905SMatthias Ringwald             tk = tk - 999999u;
35633deb3ec6SMatthias Ringwald         }
3564caf15bf3SMatthias Ringwald     } else {
3565caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35664b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3567caf15bf3SMatthias Ringwald     }
3568f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
356942134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35703deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35713deb3ec6SMatthias Ringwald     } else {
3572b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3573b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3574b41539d5SMatthias Ringwald         } else {
35753deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35763deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35773deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35783deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3579f3582630SMatthias Ringwald                 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);
35803deb3ec6SMatthias Ringwald             }
35813deb3ec6SMatthias Ringwald         }
3582b41539d5SMatthias Ringwald     }
358370b44dd4SMatthias Ringwald     sm_trigger_run();
35843deb3ec6SMatthias Ringwald }
3585d1a1f6a4SMatthias Ringwald 
3586d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3587f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3588f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3589f3582630SMatthias Ringwald     if (connection == NULL) return;
3590f3582630SMatthias Ringwald 
3591d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3592d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3593d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3594d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
359570b44dd4SMatthias Ringwald     sm_trigger_run();
3596d1a1f6a4SMatthias Ringwald }
3597d1a1f6a4SMatthias Ringwald 
3598d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3599f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3600f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3601f3582630SMatthias Ringwald     if (connection == NULL) return;
3602f3582630SMatthias Ringwald 
3603d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
36043deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
36054ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
36063deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
36074ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
36088b3ffec5SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_data, 2, &sm_handle_random_result_ph3_div, (void *)(uintptr_t) connection->sm_handle);
36093deb3ec6SMatthias Ringwald }
3610899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3611899e6e02SMatthias Ringwald     // warn about default ER/IR
36121979f09cSMatthias Ringwald     bool warning = false;
3613899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
36141979f09cSMatthias Ringwald         warning = true;
3615899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3616899e6e02SMatthias Ringwald     }
3617899e6e02SMatthias Ringwald     if (sm_er_is_default()){
36181979f09cSMatthias Ringwald         warning = true;
3619899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3620899e6e02SMatthias Ringwald     }
362121045273SMatthias Ringwald     if (warning) {
3622899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3623899e6e02SMatthias Ringwald     }
362421045273SMatthias Ringwald }
3625899e6e02SMatthias Ringwald 
3626899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
36271979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36289305033eSMatthias Ringwald     if (arg != NULL){
3629899e6e02SMatthias Ringwald         // key generated, store in tlv
36304ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3631899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3632e0d13a19SMilanka Ringwald         UNUSED(status);
3633899e6e02SMatthias Ringwald     }
3634899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
36358d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3636841468bbSMatthias Ringwald 
3637841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3638841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3639841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3640841468bbSMatthias Ringwald     }
3641841468bbSMatthias Ringwald 
364270b44dd4SMatthias Ringwald     sm_trigger_run();
3643899e6e02SMatthias Ringwald }
3644899e6e02SMatthias Ringwald 
3645899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
36461979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
36479305033eSMatthias Ringwald     if (arg != 0){
3648899e6e02SMatthias Ringwald         // key generated, store in tlv
36494ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3650899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3651e0d13a19SMilanka Ringwald         UNUSED(status);
3652899e6e02SMatthias Ringwald     }
3653899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3654899e6e02SMatthias Ringwald 
3655899e6e02SMatthias Ringwald     // try load ir
36564ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3657899e6e02SMatthias Ringwald     if (key_size == 16){
3658899e6e02SMatthias Ringwald         // ok, let's continue
3659899e6e02SMatthias Ringwald         log_info("IR from TLV");
3660899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3661899e6e02SMatthias Ringwald     } else {
3662899e6e02SMatthias Ringwald         // invalid, generate new random one
36631979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3664899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3665899e6e02SMatthias Ringwald     }
3666899e6e02SMatthias Ringwald }
36673deb3ec6SMatthias Ringwald 
3668f664b5e8SMatthias Ringwald static void sm_connection_init(sm_connection_t * sm_conn, hci_con_handle_t con_handle, uint8_t role, uint8_t addr_type, bd_addr_t address){
3669f664b5e8SMatthias Ringwald 
3670f664b5e8SMatthias Ringwald     // connection info
3671f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3672f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3673f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3674f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3675f664b5e8SMatthias Ringwald 
3676f664b5e8SMatthias Ringwald     // security properties
3677f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3678f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3679f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3680f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3681f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3682f664b5e8SMatthias Ringwald 
3683f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3684f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3685f664b5e8SMatthias Ringwald 
3686f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3687f664b5e8SMatthias Ringwald }
3688f664b5e8SMatthias Ringwald 
3689d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36903deb3ec6SMatthias Ringwald 
3691cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3692cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36939ec2630cSMatthias Ringwald 
36943deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3695711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3696fbe050beSMatthias Ringwald     uint8_t           status;
3697f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3698f664b5e8SMatthias Ringwald 
36993deb3ec6SMatthias Ringwald     switch (packet_type) {
37003deb3ec6SMatthias Ringwald 
37013deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
37020e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
37033deb3ec6SMatthias Ringwald 
37043deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
3705745015f6SMatthias Ringwald                     switch (btstack_event_state_get_state(packet)){
3706745015f6SMatthias Ringwald                         case HCI_STATE_WORKING:
37073deb3ec6SMatthias Ringwald                             log_info("HCI Working!");
3708899e6e02SMatthias Ringwald                             // setup IR/ER with TLV
3709899e6e02SMatthias Ringwald                             btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
37109305033eSMatthias Ringwald                             if (sm_tlv_impl != NULL){
37114ea43905SMatthias Ringwald                                 int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3712899e6e02SMatthias Ringwald                                 if (key_size == 16){
3713899e6e02SMatthias Ringwald                                     // ok, let's continue
3714899e6e02SMatthias Ringwald                                     log_info("ER from TLV");
3715899e6e02SMatthias Ringwald                                     sm_handle_random_result_er( NULL );
3716899e6e02SMatthias Ringwald                                 } else {
3717899e6e02SMatthias Ringwald                                     // invalid, generate random one
37181979f09cSMatthias Ringwald                                     sm_persistent_keys_random_active = true;
3719899e6e02SMatthias Ringwald                                     btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3720899e6e02SMatthias Ringwald                                 }
3721899e6e02SMatthias Ringwald                             } else {
3722899e6e02SMatthias Ringwald                                 sm_validate_er_ir();
37238d9b6072SMatthias Ringwald                                 dkg_state = DKG_CALC_IRK;
3724841468bbSMatthias Ringwald 
3725841468bbSMatthias Ringwald                                 if (test_use_fixed_local_irk){
3726841468bbSMatthias Ringwald                                     log_info_key("IRK", sm_persistent_irk);
3727841468bbSMatthias Ringwald                                     dkg_state = DKG_CALC_DHK;
3728841468bbSMatthias Ringwald                                 }
3729899e6e02SMatthias Ringwald                             }
37301bf086daSMatthias Ringwald 
373115211b85SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
373215211b85SMatthias Ringwald                             // trigger ECC key generation
373315211b85SMatthias Ringwald                             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
373415211b85SMatthias Ringwald                                 sm_ec_generate_new_key();
373515211b85SMatthias Ringwald                             }
373615211b85SMatthias Ringwald #endif
373715211b85SMatthias Ringwald 
37381bf086daSMatthias Ringwald                             // restart random address updates after power cycle
37394a688bd1SMatthias Ringwald                             if (gap_random_adress_type == GAP_RANDOM_ADDRESS_TYPE_STATIC){
37404a688bd1SMatthias Ringwald                                 gap_random_address_set(sm_random_address);
37414a688bd1SMatthias Ringwald                             } else {
37421bf086daSMatthias Ringwald                                 gap_random_address_set_mode(gap_random_adress_type);
37434a688bd1SMatthias Ringwald                             }
3744745015f6SMatthias Ringwald                             break;
3745745015f6SMatthias Ringwald 
3746745015f6SMatthias Ringwald                         case HCI_STATE_OFF:
37477f775357SMatthias Ringwald                         case HCI_STATE_HALTING:
3748cbdd51cfSMatthias Ringwald                             log_info("SM: reset state");
3749745015f6SMatthias Ringwald                             // stop random address update
3750745015f6SMatthias Ringwald                             gap_random_address_update_stop();
3751cbdd51cfSMatthias Ringwald                             // reset state
3752cbdd51cfSMatthias Ringwald                             sm_state_reset();
3753745015f6SMatthias Ringwald                             break;
3754745015f6SMatthias Ringwald 
3755745015f6SMatthias Ringwald                         default:
3756745015f6SMatthias Ringwald                             break;
37573deb3ec6SMatthias Ringwald                     }
37583deb3ec6SMatthias Ringwald 					break;
3759c18be159SMatthias Ringwald 
37602d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
37612d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
37622d095694SMatthias Ringwald 			        // ignore if connection failed
37632d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
37643deb3ec6SMatthias Ringwald 
37652d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
37662d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
37672d095694SMatthias Ringwald 			        if (!sm_conn) break;
37682d095694SMatthias Ringwald 
37692d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
37702d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
37712d095694SMatthias Ringwald                                        con_handle,
37722d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3773f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
37742d095694SMatthias Ringwald                                        addr);
37752d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
37762d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
37772d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
37782d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3779c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
37802d095694SMatthias Ringwald 			        break;
37812d095694SMatthias Ringwald #endif
3782c18be159SMatthias Ringwald 
3783c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3784c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3785c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3786c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3787c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3788c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3789c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3790c18be159SMatthias Ringwald 			        break;
3791c18be159SMatthias Ringwald #endif
3792c18be159SMatthias Ringwald 
37933deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37943deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37953deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3796f664b5e8SMatthias Ringwald                             // ignore if connection failed
3797f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37983deb3ec6SMatthias Ringwald 
3799711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3800711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38013deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38023deb3ec6SMatthias Ringwald 
3803f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3804f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3805f664b5e8SMatthias Ringwald                                                con_handle,
3806f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3807f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3808f664b5e8SMatthias Ringwald                                                addr);
3809687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3810f664b5e8SMatthias Ringwald 
3811f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3812b6f39a74SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3813b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3814ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3815ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3816f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3817b892db1cSMatthias Ringwald                             }
3818b892db1cSMatthias Ringwald #endif
3819b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3820b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3821ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3822ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
38233deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38243deb3ec6SMatthias Ringwald                             }
3825b892db1cSMatthias Ringwald #endif
38263deb3ec6SMatthias Ringwald                             break;
38273deb3ec6SMatthias Ringwald 
38283deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3829711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3830711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
38313deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
38323deb3ec6SMatthias Ringwald 
38333deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
38343deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
38353deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
38363deb3ec6SMatthias Ringwald                                 break;
38373deb3ec6SMatthias Ringwald                             }
3838c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3839778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3840778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3841e53be891SMatthias Ringwald                                 break;
3842e53be891SMatthias Ringwald                             }
38433deb3ec6SMatthias Ringwald 
38443deb3ec6SMatthias Ringwald                             // store rand and ediv
38459c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3846f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3847549ad5d2SMatthias Ringwald 
3848549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3849549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
38504ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
38516c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
385206cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3853549ad5d2SMatthias Ringwald                                     break;
3854549ad5d2SMatthias Ringwald                                 }
38556c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
38566c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
38576c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
38586c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
38596c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
38606c39055aSMatthias Ringwald                                         break;
38616c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
38626c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
38636c39055aSMatthias Ringwald                                         break;
38646c39055aSMatthias Ringwald                                     default:
38656c39055aSMatthias Ringwald                                         // wait for irk look doen
38666c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
38676c39055aSMatthias Ringwald                                         break;
38686c39055aSMatthias Ringwald                                 }
38696c39055aSMatthias Ringwald                                 break;
38706c39055aSMatthias Ringwald                             }
3871549ad5d2SMatthias Ringwald 
3872549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
387306cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3874549ad5d2SMatthias Ringwald #else
3875549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3876549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3877549ad5d2SMatthias Ringwald #endif
38783deb3ec6SMatthias Ringwald                             break;
3879804d3e67SMatthias Ringwald 
38803deb3ec6SMatthias Ringwald                         default:
38813deb3ec6SMatthias Ringwald                             break;
38823deb3ec6SMatthias Ringwald                     }
38833deb3ec6SMatthias Ringwald                     break;
38843deb3ec6SMatthias Ringwald 
38853deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
38868601e696SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE_V2:
38873b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3888711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38893deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38903deb3ec6SMatthias Ringwald 
38913b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38923deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38933deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38943deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
389503a9359aSMatthias Ringwald 
3896fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3897fbe050beSMatthias Ringwald 
38985567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
389903a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3900fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3901fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
39028d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
39038d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39048d4eef95SMatthias Ringwald                                 } else {
390503a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39068d4eef95SMatthias Ringwald                                 }
3907fbe050beSMatthias Ringwald                             } else {
3908e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3909cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
39103b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3911cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
39123b7fd749SMatthias Ringwald                             }
3913fbe050beSMatthias Ringwald 
3914fbe050beSMatthias Ringwald                             // emit re-encryption complete
391573102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3916fbe050beSMatthias Ringwald 
3917c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3918c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3919c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
39200ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
392103a9359aSMatthias Ringwald                             }
392203a9359aSMatthias Ringwald 
39233deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39243deb3ec6SMatthias Ringwald                             break;
3925fbe050beSMatthias Ringwald 
39263deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3927fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3928dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
392942134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
39303deb3ec6SMatthias Ringwald                                 // slave
3931bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3932bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3933bbf8db22SMatthias Ringwald                                 } else {
3934f3582630SMatthias Ringwald                                     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);
3935bbf8db22SMatthias Ringwald                                 }
39363deb3ec6SMatthias Ringwald                             } else {
39373deb3ec6SMatthias Ringwald                                 // master
393861d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
39393deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
39403deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3941f3582630SMatthias Ringwald                                     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);
39423deb3ec6SMatthias Ringwald                                 } else {
39433deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39443deb3ec6SMatthias Ringwald                                 }
39453deb3ec6SMatthias Ringwald                             }
39463deb3ec6SMatthias Ringwald                             break;
3947c18be159SMatthias Ringwald 
3948c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3949c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3950a036ae12SMatthias Ringwald                             // CTKD requires BR/EDR Secure Connection
3951c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3952c18be159SMatthias Ringwald                             // prepare for pairing request
3953c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3954c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3955c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3956a036ae12SMatthias Ringwald                                 // check if remote supports fixed channels
3957553c9408SMatthias Ringwald                                 bool defer = true;
3958a036ae12SMatthias Ringwald                                 const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
3959a036ae12SMatthias Ringwald                                 if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE){
3960a036ae12SMatthias Ringwald                                     // check if remote supports SMP over BR/EDR
3961a036ae12SMatthias Ringwald                                     if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
3962c18be159SMatthias Ringwald                                         sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3963553c9408SMatthias Ringwald                                     } else {
3964553c9408SMatthias Ringwald                                         defer = false;
3965c18be159SMatthias Ringwald                                     }
3966a036ae12SMatthias Ringwald                                 } else {
3967a036ae12SMatthias Ringwald                                     // wait for fixed channel info
3968a036ae12SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK;
3969a036ae12SMatthias Ringwald                                 }
3970553c9408SMatthias Ringwald                                 if (defer){
3971*f82b8f4bSMatthias Ringwald                                     hci_dedicated_bonding_defer_disconnect(con_handle, true);
3972553c9408SMatthias Ringwald                                 }
3973a036ae12SMatthias Ringwald                             }
3974c18be159SMatthias Ringwald                             break;
3975c18be159SMatthias Ringwald #endif
39763deb3ec6SMatthias Ringwald                         default:
39773deb3ec6SMatthias Ringwald                             break;
39783deb3ec6SMatthias Ringwald                     }
39793deb3ec6SMatthias Ringwald                     break;
39803deb3ec6SMatthias Ringwald 
39813deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3982711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3983711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39843deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39853deb3ec6SMatthias Ringwald 
39863deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
39873deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
39883deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
39893deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39905567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
39915567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
39925567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
39935567aa60SMatthias Ringwald                             } else {
39943deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
39955567aa60SMatthias Ringwald                             }
39963deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
39973deb3ec6SMatthias Ringwald                             break;
39983deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
399942134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
40003deb3ec6SMatthias Ringwald                                 // slave
4001f3582630SMatthias Ringwald                                 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);
40023deb3ec6SMatthias Ringwald                             } else {
40033deb3ec6SMatthias Ringwald                                 // master
40043deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
40053deb3ec6SMatthias Ringwald                             }
40063deb3ec6SMatthias Ringwald                             break;
40073deb3ec6SMatthias Ringwald                         default:
40083deb3ec6SMatthias Ringwald                             break;
40093deb3ec6SMatthias Ringwald                     }
40103deb3ec6SMatthias Ringwald                     break;
40113deb3ec6SMatthias Ringwald 
40123deb3ec6SMatthias Ringwald 
40133deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
4014711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
4015711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
4016711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
40173deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
40183deb3ec6SMatthias Ringwald 
401903f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
40207f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
40217f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
40227f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
40237f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
40247f3f442dSMatthias Ringwald                             break;
40257f3f442dSMatthias Ringwald                         default:
402668a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
40270ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
40287f3f442dSMatthias Ringwald                             break;
402903f736b1SMatthias Ringwald                     }
4030accbde80SMatthias Ringwald 
40313deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
40323deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
40333deb3ec6SMatthias Ringwald                     break;
40343deb3ec6SMatthias Ringwald 
40353deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
4036f7811256SMatthias Ringwald                     if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_READ_BD_ADDR) {
40379091c5f5SMatthias Ringwald                         // set local addr for le device db
403833373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
40390c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
404033373e40SMatthias Ringwald                     }
404165b44ffdSMatthias Ringwald                     break;
4042a036ae12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4043a036ae12SMatthias Ringwald                 case L2CAP_EVENT_INFORMATION_RESPONSE:
4044a036ae12SMatthias Ringwald                     con_handle = l2cap_event_information_response_get_con_handle(packet);
4045a036ae12SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
4046a036ae12SMatthias Ringwald                     if (!sm_conn) break;
4047a036ae12SMatthias Ringwald                     if (sm_conn->sm_engine_state == SM_BR_EDR_INITIATOR_W4_FIXED_CHANNEL_MASK){
4048a036ae12SMatthias Ringwald                         // check if remote supports SMP over BR/EDR
4049a036ae12SMatthias Ringwald                         const hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
4050a036ae12SMatthias Ringwald                         if ((hci_connection->l2cap_state.fixed_channels_supported & (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER)) != 0){
4051a036ae12SMatthias Ringwald                             sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
4052a036ae12SMatthias Ringwald                         } else {
4053a036ae12SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
4054*f82b8f4bSMatthias Ringwald                             hci_dedicated_bonding_defer_disconnect(con_handle, false);
4055a036ae12SMatthias Ringwald                         }
4056a036ae12SMatthias Ringwald                     }
4057a036ae12SMatthias Ringwald                     break;
4058a036ae12SMatthias Ringwald #endif
405965b44ffdSMatthias Ringwald                 default:
406065b44ffdSMatthias Ringwald                     break;
40613deb3ec6SMatthias Ringwald 			}
406265b44ffdSMatthias Ringwald             break;
406365b44ffdSMatthias Ringwald         default:
406465b44ffdSMatthias Ringwald             break;
40653deb3ec6SMatthias Ringwald 	}
40663deb3ec6SMatthias Ringwald 
40673deb3ec6SMatthias Ringwald     sm_run();
40683deb3ec6SMatthias Ringwald }
40693deb3ec6SMatthias Ringwald 
40703deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
40713deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
40723deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
40733deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
40743deb3ec6SMatthias Ringwald }
40753deb3ec6SMatthias Ringwald 
4076945888f5SMatthias Ringwald 
407731c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4078945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
4079945888f5SMatthias Ringwald     switch (method){
4080945888f5SMatthias Ringwald         case JUST_WORKS:
408147fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
4082945888f5SMatthias Ringwald             return 1;
4083945888f5SMatthias Ringwald         default:
4084945888f5SMatthias Ringwald             return 0;
4085945888f5SMatthias Ringwald     }
4086945888f5SMatthias Ringwald }
408707036a04SMatthias Ringwald // responder
4088945888f5SMatthias Ringwald 
4089688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
4090688a08f9SMatthias Ringwald     switch (method){
4091688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
4092688a08f9SMatthias Ringwald             return 1;
4093688a08f9SMatthias Ringwald         default:
4094688a08f9SMatthias Ringwald             return 0;
4095688a08f9SMatthias Ringwald     }
4096688a08f9SMatthias Ringwald }
409740c5d850SMatthias Ringwald 
409840c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
409940c5d850SMatthias Ringwald     switch (method){
410040c5d850SMatthias Ringwald         case PK_RESP_INPUT:
410140c5d850SMatthias Ringwald         case PK_INIT_INPUT:
410247fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
410340c5d850SMatthias Ringwald             return 1;
410440c5d850SMatthias Ringwald         default:
410540c5d850SMatthias Ringwald             return 0;
410640c5d850SMatthias Ringwald     }
410740c5d850SMatthias Ringwald }
410840c5d850SMatthias Ringwald 
410931c09488SMatthias Ringwald #endif
4110688a08f9SMatthias Ringwald 
41113deb3ec6SMatthias Ringwald /**
41123deb3ec6SMatthias Ringwald  * @return ok
41133deb3ec6SMatthias Ringwald  */
41143deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
41153deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
41163deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
41173deb3ec6SMatthias Ringwald         case JUST_WORKS:
41184ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
41193deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
41203deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
412147fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
41224ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
41233deb3ec6SMatthias Ringwald         case OOB:
41244ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
412547fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
41264ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
41273deb3ec6SMatthias Ringwald         default:
41283deb3ec6SMatthias Ringwald             return 0;
41293deb3ec6SMatthias Ringwald     }
41303deb3ec6SMatthias Ringwald }
41313deb3ec6SMatthias Ringwald 
413236f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
413336f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
413436f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
413536f0defaSMatthias Ringwald     if (sm_sc_only_mode){
413636f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
413736f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
413836f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
413936f0defaSMatthias Ringwald             return;
414036f0defaSMatthias Ringwald         }
414136f0defaSMatthias Ringwald     }
414236f0defaSMatthias Ringwald #else
414336f0defaSMatthias Ringwald     UNUSED(packet);
414436f0defaSMatthias Ringwald #endif
414536f0defaSMatthias Ringwald 
414636f0defaSMatthias Ringwald     int have_ltk;
414736f0defaSMatthias Ringwald     uint8_t ltk[16];
414836f0defaSMatthias Ringwald 
414936f0defaSMatthias Ringwald     // IRK complete?
415036f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
415136f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
415236f0defaSMatthias Ringwald             // start pairing
415336f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
415436f0defaSMatthias Ringwald             break;
415536f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
415636f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
415736f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
415836f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
415936f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
416036f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
416136f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
416236f0defaSMatthias Ringwald             } else {
416336f0defaSMatthias Ringwald                 // start pairing
416436f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
416536f0defaSMatthias Ringwald             }
416636f0defaSMatthias Ringwald             break;
416736f0defaSMatthias Ringwald         default:
416836f0defaSMatthias Ringwald             // otherwise, store security request
416936f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
417036f0defaSMatthias Ringwald             break;
417136f0defaSMatthias Ringwald     }
417236f0defaSMatthias Ringwald }
417336f0defaSMatthias Ringwald #endif
417436f0defaSMatthias Ringwald 
41758334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
41768334d3d8SMatthias Ringwald 
41774c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
41784c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
41794c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
41804c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
41814c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
41824c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
41834c1d1092SMatthias Ringwald             17, // 0x04 pairing random
41844c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
41854c1d1092SMatthias Ringwald             17, // 0x06 encryption information
41867a2e6387SMatthias Ringwald             11, // 0x07 master identification
41874c1d1092SMatthias Ringwald             17, // 0x08 identification information
41884c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
41894c1d1092SMatthias Ringwald             17, // 0x0a signing information
41904c1d1092SMatthias Ringwald             2,  // 0x0b security request
41914c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
41924c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
41934c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
41944c1d1092SMatthias Ringwald     };
41953deb3ec6SMatthias Ringwald 
4196c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4197b170b20fSMatthias Ringwald         sm_run();
4198b170b20fSMatthias Ringwald     }
4199b170b20fSMatthias Ringwald 
42003deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
42014ea43905SMatthias Ringwald     if (size == 0u) return;
42024c1d1092SMatthias Ringwald 
42034c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
42044c1d1092SMatthias Ringwald 
42054c1d1092SMatthias Ringwald     // validate pdu size
42064c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
42077a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
42083deb3ec6SMatthias Ringwald 
4209711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
42103deb3ec6SMatthias Ringwald     if (!sm_conn) return;
42113deb3ec6SMatthias Ringwald 
42124c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
421368a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
42140ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4215accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
42163deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
42173deb3ec6SMatthias Ringwald         return;
42183deb3ec6SMatthias Ringwald     }
42193deb3ec6SMatthias Ringwald 
42204c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
42213deb3ec6SMatthias Ringwald 
42223deb3ec6SMatthias Ringwald     int err;
422342134bc6SMatthias Ringwald     UNUSED(err);
42243deb3ec6SMatthias Ringwald 
42254c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
42263d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
42273d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
42283d7fe1e9SMatthias Ringwald         buffer[1] = 3;
42293d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
42303d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
42313d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
42323d7fe1e9SMatthias Ringwald         return;
42333d7fe1e9SMatthias Ringwald     }
42343d7fe1e9SMatthias Ringwald 
42353deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
42363deb3ec6SMatthias Ringwald 
4237c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
42383deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
42393deb3ec6SMatthias Ringwald             return;
42403deb3ec6SMatthias Ringwald 
424142134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
424242134bc6SMatthias Ringwald 
42433deb3ec6SMatthias Ringwald         // Initiator
42443deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
42454c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
42463deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42473deb3ec6SMatthias Ringwald                 break;
42483deb3ec6SMatthias Ringwald             }
424936f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4250dc8ca372SMatthias Ringwald             break;
42513deb3ec6SMatthias Ringwald 
42523deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4253aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4254aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4255aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4256aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4257aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4258aacfafc3SMatthias Ringwald                 break;
4259aacfafc3SMatthias Ringwald             }
4260aacfafc3SMatthias Ringwald 
4261aacfafc3SMatthias Ringwald             // all other pdus are incorrect
42624c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
42633deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42643deb3ec6SMatthias Ringwald                 break;
42653deb3ec6SMatthias Ringwald             }
42660af429c6SMatthias Ringwald 
42673deb3ec6SMatthias Ringwald             // store pairing request
42686535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
42696535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
42703deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
42710af429c6SMatthias Ringwald 
42720af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
42730af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
42740af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
42750af429c6SMatthias Ringwald                 err = test_pairing_failure;
42760af429c6SMatthias Ringwald             }
42770af429c6SMatthias Ringwald #endif
42780af429c6SMatthias Ringwald 
42799305033eSMatthias Ringwald             if (err != 0){
4280f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
42813deb3ec6SMatthias Ringwald                 break;
42823deb3ec6SMatthias Ringwald             }
4283b41539d5SMatthias Ringwald 
4284b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4285b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4286f3582630SMatthias Ringwald                 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);
4287b41539d5SMatthias Ringwald                 break;
4288b41539d5SMatthias Ringwald             }
4289b41539d5SMatthias Ringwald 
4290136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4291136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
42928cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
42938cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4294136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4295136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4296136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4297c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4298136d331aSMatthias Ringwald                     }
42998cba5ca3SMatthias Ringwald                 } else {
4300c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
43018cba5ca3SMatthias Ringwald                 }
4302136d331aSMatthias Ringwald                 break;
4303136d331aSMatthias Ringwald             }
4304136d331aSMatthias Ringwald #endif
43053deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
43063deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
43073deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
43083deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4309f3582630SMatthias Ringwald                 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);
43103deb3ec6SMatthias Ringwald             }
43113deb3ec6SMatthias Ringwald             break;
43123deb3ec6SMatthias Ringwald 
43133deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
43144c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
43153deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43163deb3ec6SMatthias Ringwald                 break;
43173deb3ec6SMatthias Ringwald             }
43183deb3ec6SMatthias Ringwald 
43193deb3ec6SMatthias Ringwald             // store s_confirm
43209c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4321192365feSMatthias Ringwald 
4322aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4323aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4324aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4325aa9b34e5SMatthias Ringwald                 break;
4326aa9b34e5SMatthias Ringwald             }
4327aa9b34e5SMatthias Ringwald 
4328192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4329192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4330192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4331192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4332192365feSMatthias Ringwald             }
4333192365feSMatthias Ringwald #endif
43343deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
43353deb3ec6SMatthias Ringwald             break;
43363deb3ec6SMatthias Ringwald 
43373deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
43384c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
43393deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43403deb3ec6SMatthias Ringwald                 break;;
43413deb3ec6SMatthias Ringwald             }
43423deb3ec6SMatthias Ringwald 
43433deb3ec6SMatthias Ringwald             // received random value
43449c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
43453deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
43463deb3ec6SMatthias Ringwald             break;
434742134bc6SMatthias Ringwald #endif
43483deb3ec6SMatthias Ringwald 
434942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
43503deb3ec6SMatthias Ringwald         // Responder
43513deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
43523deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
43533deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
43544c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
43553deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
43563deb3ec6SMatthias Ringwald                 break;;
43573deb3ec6SMatthias Ringwald             }
43583deb3ec6SMatthias Ringwald 
43593deb3ec6SMatthias Ringwald             // store pairing request
4360212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4361212d735eSMatthias Ringwald 
4362212d735eSMatthias Ringwald             // check if IRK completed
4363212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4364212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4365212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
43663deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
43673deb3ec6SMatthias Ringwald                     break;
4368212d735eSMatthias Ringwald                 default:
4369212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4370212d735eSMatthias Ringwald                     break;
4371212d735eSMatthias Ringwald             }
4372212d735eSMatthias Ringwald             break;
437342134bc6SMatthias Ringwald #endif
43743deb3ec6SMatthias Ringwald 
437527c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4376c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
43774c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
437827c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
437927c32905SMatthias Ringwald                 break;
438027c32905SMatthias Ringwald             }
4381bccf5e67SMatthias Ringwald 
4382e53be891SMatthias Ringwald             // store public key for DH Key calculation
4383fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4384fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4385bccf5e67SMatthias Ringwald 
438602658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
438702658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
438802658749SMatthias Ringwald                 log_info("Remote PK matches ours");
438902658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
439002658749SMatthias Ringwald                 break;
439102658749SMatthias Ringwald             }
439202658749SMatthias Ringwald 
4393d1a1f6a4SMatthias Ringwald             // validate public key
4394d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
43959305033eSMatthias Ringwald             if (err != 0){
439602658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4397349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4398bccf5e67SMatthias Ringwald                 break;
4399bccf5e67SMatthias Ringwald             }
4400891bb64aSMatthias Ringwald 
4401d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4402f3582630SMatthias Ringwald             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);
44033cf37b8cSMatthias Ringwald 
440465a9a04eSMatthias Ringwald 
440565a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
440642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4407136d331aSMatthias Ringwald                 // responder
4408c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4409136d331aSMatthias Ringwald             } else {
4410136d331aSMatthias Ringwald                 // initiator
4411a1e31e9cSMatthias Ringwald                 // stk generation method
4412a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4413a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4414a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
441547fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4416c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4417a1e31e9cSMatthias Ringwald                         break;
4418a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
441907036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
442007036a04SMatthias Ringwald                         break;
442107036a04SMatthias Ringwald                     case PK_INIT_INPUT:
442247fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
442307036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
442407036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
442507036a04SMatthias Ringwald                             break;
442607036a04SMatthias Ringwald                         }
4427b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4428a1e31e9cSMatthias Ringwald                         break;
4429a1e31e9cSMatthias Ringwald                     case OOB:
4430d1a1f6a4SMatthias Ringwald                         // generate Nx
44314acf7b7bSMatthias Ringwald                         log_info("Generate Na");
44326ca80073SMatthias Ringwald                         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);
4433a1e31e9cSMatthias Ringwald                         break;
44347bbeb3adSMilanka Ringwald                     default:
44357bbeb3adSMilanka Ringwald                         btstack_assert(false);
44367bbeb3adSMilanka Ringwald                         break;
4437a1e31e9cSMatthias Ringwald                 }
4438136d331aSMatthias Ringwald             }
443927c32905SMatthias Ringwald             break;
4440e53be891SMatthias Ringwald 
4441c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
44424c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
444345a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
444445a61d50SMatthias Ringwald                 break;
444545a61d50SMatthias Ringwald             }
444645a61d50SMatthias Ringwald             // received confirm value
444745a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
444845a61d50SMatthias Ringwald 
4449192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4450192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4451192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4452192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4453192365feSMatthias Ringwald             }
4454192365feSMatthias Ringwald #endif
445542134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
445645a61d50SMatthias Ringwald                 // responder
445707036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
445807036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
445907036a04SMatthias Ringwald                         // still waiting for passkey
446007036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
446107036a04SMatthias Ringwald                         break;
446207036a04SMatthias Ringwald                     }
446307036a04SMatthias Ringwald                 }
4464b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
446545a61d50SMatthias Ringwald             } else {
446645a61d50SMatthias Ringwald                 // initiator
4467945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
44686ca80073SMatthias Ringwald                     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);
4469f1c1783eSMatthias Ringwald                 } else {
4470c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
447145a61d50SMatthias Ringwald                 }
4472f1c1783eSMatthias Ringwald             }
447345a61d50SMatthias Ringwald             break;
447445a61d50SMatthias Ringwald 
4475c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
44764c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4477e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4478136d331aSMatthias Ringwald                 break;
4479e53be891SMatthias Ringwald             }
4480e53be891SMatthias Ringwald 
4481e53be891SMatthias Ringwald             // received random value
4482e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4483e53be891SMatthias Ringwald 
44845a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4485ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4486d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4487d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4488d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
448965a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4490d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4491688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4492ae451ec5SMatthias Ringwald                  break;
44935a293e6eSMatthias Ringwald             }
44946f52a196SMatthias Ringwald 
44954acf7b7bSMatthias Ringwald             // OOB
44964acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
44974acf7b7bSMatthias Ringwald 
44984acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
44994acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
45004acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45014ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
45024acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
45034acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
45044acf7b7bSMatthias Ringwald                     } else {
45056535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
45064acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
45074acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
45084acf7b7bSMatthias Ringwald                     }
45094acf7b7bSMatthias Ringwald                 }  else {
45104ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
45114acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
45124acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
45134acf7b7bSMatthias Ringwald                     } else {
45146535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
45154acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
45164acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
45174acf7b7bSMatthias Ringwald                     }
45184acf7b7bSMatthias Ringwald                 }
45194acf7b7bSMatthias Ringwald 
4520a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
45214acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4522a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4523a680ba6bSMatthias Ringwald                      break;
4524a680ba6bSMatthias Ringwald                 }
45254acf7b7bSMatthias Ringwald             }
4526a680ba6bSMatthias Ringwald 
4527a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4528688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4529e53be891SMatthias Ringwald             break;
4530e53be891SMatthias Ringwald 
4531901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4532901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
45333cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4534901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4535901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4536901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4537901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4538901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4539901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4540901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4541c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4542901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4543d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
45444c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4545e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4546e53be891SMatthias Ringwald                 break;
4547e53be891SMatthias Ringwald             }
4548e53be891SMatthias Ringwald             // store DHKey Check
4549901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4550e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4551446a8c36SMatthias Ringwald 
4552901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4553901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4554019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4555bd57ffebSMatthias Ringwald             }
4556bd57ffebSMatthias Ringwald             break;
455727c32905SMatthias Ringwald #endif
455827c32905SMatthias Ringwald 
455942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
45603deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
45614c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
45623deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
456327c32905SMatthias Ringwald                 break;
45643deb3ec6SMatthias Ringwald             }
45653deb3ec6SMatthias Ringwald 
45663deb3ec6SMatthias Ringwald             // received confirm value
45679c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
45683deb3ec6SMatthias Ringwald 
4569192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4570192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4571192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4572192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4573192365feSMatthias Ringwald             }
4574192365feSMatthias Ringwald #endif
45753deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
45763deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
45775611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_DISPLAY_CANCEL, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
45783deb3ec6SMatthias Ringwald             }
45793deb3ec6SMatthias Ringwald 
45803deb3ec6SMatthias Ringwald             // handle user cancel pairing?
45813deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4582f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
45833deb3ec6SMatthias Ringwald                 break;
45843deb3ec6SMatthias Ringwald             }
45853deb3ec6SMatthias Ringwald 
45863deb3ec6SMatthias Ringwald             // wait for user action?
45873deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
45883deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
45893deb3ec6SMatthias Ringwald                 break;
45903deb3ec6SMatthias Ringwald             }
45913deb3ec6SMatthias Ringwald 
45923deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4593f3582630SMatthias Ringwald             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);
45943deb3ec6SMatthias Ringwald             break;
45953deb3ec6SMatthias Ringwald 
45963deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
45974c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
45983deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
45993deb3ec6SMatthias Ringwald                 break;;
46003deb3ec6SMatthias Ringwald             }
46013deb3ec6SMatthias Ringwald 
46023deb3ec6SMatthias Ringwald             // received random value
46039c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
46043deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
46053deb3ec6SMatthias Ringwald             break;
460642134bc6SMatthias Ringwald #endif
46073deb3ec6SMatthias Ringwald 
4608672dc582SMatthias Ringwald         case SM_PH2_W4_CONNECTION_ENCRYPTED:
46093deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
46104c1d1092SMatthias Ringwald             switch(sm_pdu_code){
46113deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
46123deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
46139c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
46143deb3ec6SMatthias Ringwald                     break;
46153deb3ec6SMatthias Ringwald 
46163deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
46173deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4618f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
46199c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
46203deb3ec6SMatthias Ringwald                     break;
46213deb3ec6SMatthias Ringwald 
46223deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
46233deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
46249c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
46253deb3ec6SMatthias Ringwald                     break;
46263deb3ec6SMatthias Ringwald 
46273deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
46283deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
46293deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4630724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
46313deb3ec6SMatthias Ringwald                     break;
46323deb3ec6SMatthias Ringwald 
46333deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
46343deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
46359c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
46363deb3ec6SMatthias Ringwald                     break;
46373deb3ec6SMatthias Ringwald                 default:
46383deb3ec6SMatthias Ringwald                     // Unexpected PDU
46393deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
46403deb3ec6SMatthias Ringwald                     break;
46413deb3ec6SMatthias Ringwald             }
46423deb3ec6SMatthias Ringwald             // done with key distribution?
464361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
46443deb3ec6SMatthias Ringwald 
46453deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
46463deb3ec6SMatthias Ringwald 
464742134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
46486f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
46493deb3ec6SMatthias Ringwald                 } else {
4650625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4651625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4652bbf8db22SMatthias Ringwald                     } else {
4653f3582630SMatthias Ringwald                         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);
4654625f00b2SMatthias Ringwald                     }
46553deb3ec6SMatthias Ringwald                 }
46563deb3ec6SMatthias Ringwald             }
46573deb3ec6SMatthias Ringwald             break;
4658c18be159SMatthias Ringwald 
4659c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4660c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4661553c9408SMatthias Ringwald 
4662553c9408SMatthias Ringwald             // dedicated bonding complete
4663*f82b8f4bSMatthias Ringwald             hci_dedicated_bonding_defer_disconnect(sm_conn->sm_handle, false);
4664553c9408SMatthias Ringwald 
4665c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4666c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4667c18be159SMatthias Ringwald                 break;
4668c18be159SMatthias Ringwald             }
4669c18be159SMatthias Ringwald             // store pairing response
4670c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4671c18be159SMatthias Ringwald 
4672c18be159SMatthias Ringwald             // validate encryption key size
4673c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(setup->sm_s_pres));
4674c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4675c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4676c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4677c18be159SMatthias Ringwald             }
4678c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4679c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4680c18be159SMatthias Ringwald                 break;
4681c18be159SMatthias Ringwald             }
4682c18be159SMatthias Ringwald 
4683c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4684c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4685c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4686c18be159SMatthias Ringwald 
4687c18be159SMatthias Ringwald             // skip receive if there are none
468861d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4689c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4690c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4691c18be159SMatthias Ringwald             } else {
4692c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4693c18be159SMatthias Ringwald             }
4694c18be159SMatthias Ringwald             break;
4695c18be159SMatthias Ringwald 
4696c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4697c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4698c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4699c18be159SMatthias Ringwald                 break;
4700c18be159SMatthias Ringwald             }
4701c18be159SMatthias Ringwald             // store pairing request
4702c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4703c18be159SMatthias Ringwald             // validate encryption key size
4704c18be159SMatthias Ringwald             sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(sm_conn->sm_m_preq));
4705c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4706c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4707c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4708c18be159SMatthias Ringwald             }
4709c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4710c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4711c18be159SMatthias Ringwald                 break;
4712c18be159SMatthias Ringwald             }
4713c18be159SMatthias Ringwald             // trigger response
4714c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4715c18be159SMatthias Ringwald             break;
4716c18be159SMatthias Ringwald 
4717c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4718c18be159SMatthias Ringwald             switch(sm_pdu_code){
4719c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4720c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4721c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4722c18be159SMatthias Ringwald                     break;
4723c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4724c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4725c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4726c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4727c18be159SMatthias Ringwald                     break;
4728c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4729c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4730c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4731c18be159SMatthias Ringwald                     break;
4732c18be159SMatthias Ringwald                 default:
4733c18be159SMatthias Ringwald                     // Unexpected PDU
4734c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4735c18be159SMatthias Ringwald                     break;
4736c18be159SMatthias Ringwald             }
4737c18be159SMatthias Ringwald 
4738c18be159SMatthias Ringwald             // all keys received
473961d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4740c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4741c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4742c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4743c18be159SMatthias Ringwald                 } else {
4744c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4745c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4746c18be159SMatthias Ringwald                 }
4747c18be159SMatthias Ringwald             }
4748c18be159SMatthias Ringwald             break;
4749c18be159SMatthias Ringwald #endif
4750c18be159SMatthias Ringwald 
47513deb3ec6SMatthias Ringwald         default:
47523deb3ec6SMatthias Ringwald             // Unexpected PDU
47533deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
47542d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
47553deb3ec6SMatthias Ringwald             break;
47563deb3ec6SMatthias Ringwald     }
47573deb3ec6SMatthias Ringwald 
475870b44dd4SMatthias Ringwald     // try to send next pdu
475970b44dd4SMatthias Ringwald     sm_trigger_run();
47603deb3ec6SMatthias Ringwald }
47613deb3ec6SMatthias Ringwald 
47623deb3ec6SMatthias Ringwald // Security Manager Client API
4763a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
47643deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
47653deb3ec6SMatthias Ringwald }
47663deb3ec6SMatthias Ringwald 
47674acf7b7bSMatthias Ringwald 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)){
4768a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4769a680ba6bSMatthias Ringwald }
4770a680ba6bSMatthias Ringwald 
4771b96d60a6SMatthias Ringwald void sm_register_ltk_callback( bool (*get_ltk_callback)(hci_con_handle_t con_handle, uint8_t address_type, bd_addr_t addr, uint8_t * ltk)){
4772b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4773b96d60a6SMatthias Ringwald }
4774b96d60a6SMatthias Ringwald 
477589a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
477689a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
477789a78d34SMatthias Ringwald }
477889a78d34SMatthias Ringwald 
477967f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
478067f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
478167f708e0SMatthias Ringwald }
478267f708e0SMatthias Ringwald 
47833deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
47843deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
47853deb3ec6SMatthias Ringwald }
47863deb3ec6SMatthias Ringwald 
47873deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
47883deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
47893deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
47903deb3ec6SMatthias Ringwald }
47913deb3ec6SMatthias Ringwald 
47923deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
479398d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
479498d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
479598d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
479698d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
479798d95509SMatthias Ringwald     }
479898d95509SMatthias Ringwald #endif
47993deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
48003deb3ec6SMatthias Ringwald }
48013deb3ec6SMatthias Ringwald 
48023deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
48033deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
48043deb3ec6SMatthias Ringwald }
48053deb3ec6SMatthias Ringwald 
480642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
48073deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
48083deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
48093deb3ec6SMatthias Ringwald }
481042134bc6SMatthias Ringwald #endif
48113deb3ec6SMatthias Ringwald 
48123deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
48136535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
48143deb3ec6SMatthias Ringwald }
48153deb3ec6SMatthias Ringwald 
48163deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
48176535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
48183deb3ec6SMatthias Ringwald }
48193deb3ec6SMatthias Ringwald 
48203deb3ec6SMatthias Ringwald // Testing support only
48213deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
48226535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4823103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4824841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
48253deb3ec6SMatthias Ringwald }
48263deb3ec6SMatthias Ringwald 
48273deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4828841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
48293deb3ec6SMatthias Ringwald }
48303deb3ec6SMatthias Ringwald 
4831d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4832d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4833d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4834d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
483534b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
483670b44dd4SMatthias Ringwald     sm_trigger_run();
4837d1a1f6a4SMatthias Ringwald }
4838674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
483934b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4840674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4841674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4842674e5b4aSMatthias Ringwald }
4843d1a1f6a4SMatthias Ringwald #endif
4844d1a1f6a4SMatthias Ringwald 
4845192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4846192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4847192365feSMatthias Ringwald     test_pairing_failure = reason;
4848192365feSMatthias Ringwald }
4849192365feSMatthias Ringwald #endif
4850192365feSMatthias Ringwald 
48517887cd92SMatthias Ringwald static void sm_state_reset(void) {
48527f775357SMatthias Ringwald #ifdef USE_CMAC_ENGINE
48537f775357SMatthias Ringwald     sm_cmac_active  = 0;
48547f775357SMatthias Ringwald #endif
48557f775357SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
48567f775357SMatthias Ringwald     rau_state = RAU_IDLE;
48577f775357SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
48587f775357SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
48597f775357SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
48607f775357SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
48617f775357SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
4862cbdd51cfSMatthias Ringwald     sm_persistent_keys_random_active = false;
48637f775357SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
486415211b85SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_IDLE;
48657f775357SMatthias Ringwald #endif
48667f775357SMatthias Ringwald }
48677f775357SMatthias Ringwald 
48683deb3ec6SMatthias Ringwald void sm_init(void){
48692d2d4d3cSMatthias Ringwald 
48702d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
48712d2d4d3cSMatthias Ringwald 
4872899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4873899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4874899e6e02SMatthias Ringwald 
48753deb3ec6SMatthias Ringwald     // defaults
48763deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
48773deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4878b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4879b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4880b4343428SMatthias Ringwald 
48813deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
48823deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
48833deb3ec6SMatthias Ringwald 
48845ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
48851979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4886caf15bf3SMatthias Ringwald 
48873deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
48883deb3ec6SMatthias Ringwald 
4889841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
48903deb3ec6SMatthias Ringwald 
48917f775357SMatthias Ringwald     // other
489284c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
489384c0c5c7SMatthias Ringwald 
4894a036ae12SMatthias Ringwald     // register for HCI Events
4895e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4896e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4897e03e489aSMatthias Ringwald 
4898a036ae12SMatthias Ringwald     // register for L2CAP events
4899a036ae12SMatthias Ringwald     l2cap_event_callback_registration.callback = &sm_event_packet_handler;
4900a036ae12SMatthias Ringwald     l2cap_add_event_handler(&l2cap_event_callback_registration);
4901a036ae12SMatthias Ringwald 
4902d1a1f6a4SMatthias Ringwald     //
4903d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4904d1a1f6a4SMatthias Ringwald 
490551bd74d1SMatthias Ringwald     // init le_device_db
490651bd74d1SMatthias Ringwald     le_device_db_init();
490751bd74d1SMatthias Ringwald 
4908b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4909e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4910384eabd3SMatthias Ringwald #ifdef ENABLE_CLASSIC
4911384eabd3SMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4912384eabd3SMatthias Ringwald #endif
491327c32905SMatthias Ringwald 
49147f775357SMatthias Ringwald     // state
49157f775357SMatthias Ringwald     sm_state_reset();
49162d2d4d3cSMatthias Ringwald 
49172d2d4d3cSMatthias Ringwald     sm_initialized = true;
49183deb3ec6SMatthias Ringwald }
49193deb3ec6SMatthias Ringwald 
492015537ea4SMatthias Ringwald void sm_deinit(void){
492115537ea4SMatthias Ringwald     sm_initialized = false;
492215537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
492315537ea4SMatthias Ringwald }
492415537ea4SMatthias Ringwald 
49254b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
49264b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4927caf15bf3SMatthias Ringwald }
4928caf15bf3SMatthias Ringwald 
49296c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
49301979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
49316c39055aSMatthias Ringwald }
49326c39055aSMatthias Ringwald 
4933711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4934711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
49353deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
49363deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
49373deb3ec6SMatthias Ringwald }
49383deb3ec6SMatthias Ringwald 
4939916ea5b2SMatthias Ringwald static void sm_cache_ltk(sm_connection_t * connection, const sm_key_t ltk){
4940916ea5b2SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(connection->sm_handle);
4941916ea5b2SMatthias Ringwald     btstack_assert(hci_con != NULL);
4942916ea5b2SMatthias Ringwald     memcpy(hci_con->link_key, ltk, 16);
4943916ea5b2SMatthias Ringwald     hci_con->link_key_type = 1;
4944916ea5b2SMatthias Ringwald }
4945916ea5b2SMatthias Ringwald 
494677e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
494777e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
494877e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
494977e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
495077e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
495177e2e5edSMatthias Ringwald }
495277e2e5edSMatthias Ringwald #endif
495377e2e5edSMatthias Ringwald 
49546bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4955711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4956711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49573deb3ec6SMatthias Ringwald     if (!sm_conn) return;
49586bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
49596bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
49603deb3ec6SMatthias Ringwald }
49613deb3ec6SMatthias Ringwald 
49623deb3ec6SMatthias Ringwald // request pairing
4963711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4964711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49653deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49663deb3ec6SMatthias Ringwald 
49677af5dcd5SMatthias Ringwald     bool have_ltk;
49687af5dcd5SMatthias Ringwald     uint8_t ltk[16];
49693deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
497042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
497124c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
497224c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
497324c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
49747af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
49757af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
49767af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
49777af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
49787af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
49797af5dcd5SMatthias Ringwald                         if (have_ltk){
49807af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
498124c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
49827af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
49837af5dcd5SMatthias Ringwald                             break;
49847af5dcd5SMatthias Ringwald                         }
49857af5dcd5SMatthias Ringwald                         /* fall through */
49867af5dcd5SMatthias Ringwald 
49877af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
49887af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49897af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
49907af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
49917af5dcd5SMatthias Ringwald                         break;
49927af5dcd5SMatthias Ringwald                     default:
49937af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
49947af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
49957af5dcd5SMatthias Ringwald                         break;
49967af5dcd5SMatthias Ringwald                 }
499724c20dc4SMatthias Ringwald                 break;
499824c20dc4SMatthias Ringwald             default:
499924c20dc4SMatthias Ringwald                 break;
500024c20dc4SMatthias Ringwald         }
50013deb3ec6SMatthias Ringwald     } else {
50023deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
5003175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
5004175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
50053deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
50063deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
50073dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
5008f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
5009f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
5010f53ec649SMatthias Ringwald                         if (have_ltk){
5011c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
50125567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
5013c245ca32SMatthias Ringwald                             break;
5014f53ec649SMatthias Ringwald                         }
5015cf373d3aSMatthias Ringwald                         /* fall through */
5016c245ca32SMatthias Ringwald 
501734c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
50183deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
50193deb3ec6SMatthias Ringwald                         break;
50203deb3ec6SMatthias Ringwald                     default:
5021d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
502209ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
50233deb3ec6SMatthias Ringwald                         break;
50243deb3ec6SMatthias Ringwald                 }
5025175b7faaSMatthias Ringwald                 break;
5026cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
5027cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
5028cb6d7eb0SMatthias Ringwald                 break;
5029175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
503009ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
5031175b7faaSMatthias Ringwald                 break;
5032175b7faaSMatthias Ringwald             default:
5033175b7faaSMatthias Ringwald                 break;
50343deb3ec6SMatthias Ringwald         }
50353deb3ec6SMatthias Ringwald     }
503670b44dd4SMatthias Ringwald     sm_trigger_run();
50373deb3ec6SMatthias Ringwald }
50383deb3ec6SMatthias Ringwald 
50393deb3ec6SMatthias Ringwald // called by client app on authorization request
5040711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
5041711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50423deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50433deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
5044589f5a99SMatthias Ringwald     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 0);
50453deb3ec6SMatthias Ringwald }
50463deb3ec6SMatthias Ringwald 
5047711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
5048711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50493deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50503deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
5051589f5a99SMatthias Ringwald     sm_notify_client_status(SM_EVENT_AUTHORIZATION_RESULT, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, 1);
50523deb3ec6SMatthias Ringwald }
50533deb3ec6SMatthias Ringwald 
50543deb3ec6SMatthias Ringwald // GAP Bonding API
50553deb3ec6SMatthias Ringwald 
5056711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
5057711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50583deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50593deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
50600af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
50610af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
50620af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
50630af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
50640af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
50650af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
50660af429c6SMatthias Ringwald #endif
50670af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
5068de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
5069de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
5070de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
507147fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
50720af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
5073de2fd182SMatthias Ringwald                     break;
507447fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
5075de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
5076de2fd182SMatthias Ringwald                     break;
5077de2fd182SMatthias Ringwald                 case JUST_WORKS:
5078de2fd182SMatthias Ringwald                 case OOB:
5079de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
5080de2fd182SMatthias Ringwald                     break;
50817bbeb3adSMilanka Ringwald                 default:
50827bbeb3adSMilanka Ringwald                     btstack_assert(false);
50837bbeb3adSMilanka Ringwald                     break;
5084de2fd182SMatthias Ringwald             }
50850af429c6SMatthias Ringwald             break;
50860af429c6SMatthias Ringwald         default:
50870af429c6SMatthias Ringwald             break;
50883deb3ec6SMatthias Ringwald     }
508970b44dd4SMatthias Ringwald     sm_trigger_run();
50903deb3ec6SMatthias Ringwald }
50913deb3ec6SMatthias Ringwald 
5092711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
5093711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50943deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
50953deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
50963deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5097136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
5098c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
5099bbf8db22SMatthias Ringwald         } else {
5100f3582630SMatthias Ringwald             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);
5101136d331aSMatthias Ringwald         }
51023deb3ec6SMatthias Ringwald     }
51030346c37cSMatthias Ringwald 
51040346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5105c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
5106dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
5107446a8c36SMatthias Ringwald     }
51080346c37cSMatthias Ringwald #endif
51090346c37cSMatthias Ringwald 
511070b44dd4SMatthias Ringwald     sm_trigger_run();
51113deb3ec6SMatthias Ringwald }
51123deb3ec6SMatthias Ringwald 
5113c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
5114c8c46d51SMatthias Ringwald     // for now, it's the same
5115c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
5116c8c46d51SMatthias Ringwald }
5117c8c46d51SMatthias Ringwald 
5118711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
5119711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51203deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51213deb3ec6SMatthias Ringwald     sm_reset_tk();
5122f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
51233deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
51243deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
5125f3582630SMatthias Ringwald         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);
51263deb3ec6SMatthias Ringwald     }
51271c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51286535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
51296535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
513007036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
513107036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
513207036a04SMatthias Ringwald     }
51331c516d8fSMatthias Ringwald #endif
513470b44dd4SMatthias Ringwald     sm_trigger_run();
51353deb3ec6SMatthias Ringwald }
51363deb3ec6SMatthias Ringwald 
51373d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
51383d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
51393d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
51403d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
5141dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
51424ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5143dd4a08fbSMatthias Ringwald     switch (action){
5144dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5145dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
51464ea43905SMatthias Ringwald             flags |= (1u << action);
5147dd4a08fbSMatthias Ringwald             break;
5148dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5149dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
51504ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5151dd4a08fbSMatthias Ringwald             break;
5152dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
51534ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5154dd4a08fbSMatthias Ringwald                 // erase actions queued
5155dd4a08fbSMatthias Ringwald                 num_actions--;
51564ea43905SMatthias Ringwald                 if (num_actions == 0u){
5157dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
51584ea43905SMatthias Ringwald                     flags &= 0x19u;
5159dd4a08fbSMatthias Ringwald                 }
5160dd4a08fbSMatthias Ringwald                 break;
5161dd4a08fbSMatthias Ringwald             }
5162dd4a08fbSMatthias Ringwald             num_actions++;
51634ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5164dd4a08fbSMatthias Ringwald             break;
5165dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
51664ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5167dd4a08fbSMatthias Ringwald                 // enter actions queued
5168dd4a08fbSMatthias Ringwald                 num_actions--;
51694ea43905SMatthias Ringwald                 if (num_actions == 0u){
5170dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
51714ea43905SMatthias Ringwald                     flags &= 0x19u;
5172dd4a08fbSMatthias Ringwald                 }
5173dd4a08fbSMatthias Ringwald                 break;
5174dd4a08fbSMatthias Ringwald             }
5175dd4a08fbSMatthias Ringwald             num_actions++;
51764ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5177dd4a08fbSMatthias Ringwald             break;
5178dd4a08fbSMatthias Ringwald         default:
5179dd4a08fbSMatthias Ringwald             break;
5180dd4a08fbSMatthias Ringwald     }
5181dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
518270b44dd4SMatthias Ringwald     sm_trigger_run();
51833d7fe1e9SMatthias Ringwald }
51843d7fe1e9SMatthias Ringwald 
5185c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5186d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5187d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5188d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
518970b44dd4SMatthias Ringwald     sm_trigger_run();
5190d1a1f6a4SMatthias Ringwald }
5191c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
51928334d3d8SMatthias Ringwald 
51938334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
51948334d3d8SMatthias Ringwald 
5195c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5196c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5197d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5198d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5199c59d0c92SMatthias Ringwald     return 0;
5200c59d0c92SMatthias Ringwald }
5201c59d0c92SMatthias Ringwald #endif
5202c59d0c92SMatthias Ringwald 
52033deb3ec6SMatthias Ringwald /**
5204ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5205ba394633SMatthias Ringwald  * @param con_handle
5206ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5207ba394633SMatthias Ringwald  */
5208ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5209ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5210ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5211ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5212ba394633SMatthias Ringwald }
5213ba394633SMatthias Ringwald 
5214ba394633SMatthias Ringwald /**
52153deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
52163deb3ec6SMatthias Ringwald  * @param handle
52176b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
52183deb3ec6SMatthias Ringwald  */
5219711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5220711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
52213deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
52223deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
52233deb3ec6SMatthias Ringwald }
52243deb3ec6SMatthias Ringwald 
5225916ea5b2SMatthias Ringwald uint8_t sm_get_ltk(hci_con_handle_t con_handle, sm_key_t ltk){
5226916ea5b2SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(con_handle);
5227916ea5b2SMatthias Ringwald     if (hci_connection == NULL){
5228916ea5b2SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5229916ea5b2SMatthias Ringwald     }
5230916ea5b2SMatthias Ringwald     if (hci_connection->link_key_type == 0){
5231916ea5b2SMatthias Ringwald         return ERROR_CODE_PIN_OR_KEY_MISSING;
5232916ea5b2SMatthias Ringwald     }
5233916ea5b2SMatthias Ringwald     memcpy(ltk, hci_connection->link_key, 16);
5234916ea5b2SMatthias Ringwald     return ERROR_CODE_SUCCESS;
5235916ea5b2SMatthias Ringwald }
5236916ea5b2SMatthias Ringwald 
52378f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
523847ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
523947ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
524047ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
524147ba4de1SMatthias Ringwald             return 0;
524247ba4de1SMatthias Ringwald         default:
52438f57b085SMatthias Ringwald             return 1;
52448f57b085SMatthias Ringwald     }
524547ba4de1SMatthias Ringwald }
5246d70217a2SMatthias Ringwald 
524733373e40SMatthias Ringwald static uint8_t own_address_type(void){
5248b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5249b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5250b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5251b95a5a35SMatthias Ringwald         default:
5252b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5253b95a5a35SMatthias Ringwald     }
525433373e40SMatthias Ringwald }
52558f57b085SMatthias Ringwald 
52563deb3ec6SMatthias Ringwald // GAP LE API
52573deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
52583deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
52593deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5260b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
52618f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
52623deb3ec6SMatthias Ringwald     gap_random_address_update_start();
52633deb3ec6SMatthias Ringwald     gap_random_address_trigger();
52643deb3ec6SMatthias Ringwald }
52653deb3ec6SMatthias Ringwald 
52663deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
52673deb3ec6SMatthias Ringwald     return gap_random_adress_type;
52683deb3ec6SMatthias Ringwald }
52693deb3ec6SMatthias Ringwald 
52703deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
52713deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
52728f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
52733deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
52743deb3ec6SMatthias Ringwald     gap_random_address_update_start();
52753deb3ec6SMatthias Ringwald }
52763deb3ec6SMatthias Ringwald 
5277667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
52788f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
52796535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
528063d302e8SMatthias Ringwald     // assert msb bits are set to '11'
528163d302e8SMatthias Ringwald     sm_random_address[0] |= 0xc0;
528263d302e8SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
52837e252622SMatthias Ringwald }
52847e252622SMatthias Ringwald 
5285d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
52863deb3ec6SMatthias Ringwald /*
52873deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
52883deb3ec6SMatthias Ringwald  * @param adv_int_min
52893deb3ec6SMatthias Ringwald  * @param adv_int_max
52903deb3ec6SMatthias Ringwald  * @param adv_type
52913deb3ec6SMatthias Ringwald  * @param direct_address_type
52923deb3ec6SMatthias Ringwald  * @param direct_address
52933deb3ec6SMatthias Ringwald  * @param channel_map
52943deb3ec6SMatthias Ringwald  * @param filter_policy
52953deb3ec6SMatthias Ringwald  *
52963deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
52973deb3ec6SMatthias Ringwald  */
52983deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
52993deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5300b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
53013deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
53023deb3ec6SMatthias Ringwald }
5303d70217a2SMatthias Ringwald #endif
5304dcd6c9b5SMatthias Ringwald 
5305dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5306dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5307dcd6c9b5SMatthias Ringwald      // wrong connection
5308dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5309dcd6c9b5SMatthias Ringwald     // already encrypted
5310dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5311dcd6c9b5SMatthias Ringwald     // irk status?
5312dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5313dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5314dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5315dcd6c9b5SMatthias Ringwald             return 0;
5316dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5317dcd6c9b5SMatthias Ringwald             break;
5318dcd6c9b5SMatthias Ringwald         default:
5319dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5320dcd6c9b5SMatthias Ringwald             return 1;
5321dcd6c9b5SMatthias Ringwald     }
5322f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5323f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5324b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5325b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5326b15d5ceaSMatthias Ringwald     } else {
5327dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5328dcd6c9b5SMatthias Ringwald     }
5329b15d5ceaSMatthias Ringwald }
53303cdbe9dbSMatthias Ringwald 
53313cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
53323cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
53333cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
53343cdbe9dbSMatthias Ringwald #else
53353cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
53363cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
53373cdbe9dbSMatthias Ringwald #endif
53383cdbe9dbSMatthias Ringwald }
5339052bbdc5SMatthias Ringwald 
5340052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5341052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5342052bbdc5SMatthias Ringwald }
53434f384501SMatthias Ringwald 
53444f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
53454f384501SMatthias Ringwald     uint16_t i;
53464f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
53474f384501SMatthias Ringwald         bd_addr_t entry_address;
53484f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
53494f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
53504f384501SMatthias Ringwald         // skip unused entries
53514f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
53524f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
53532e08b70bSMatthias Ringwald             sm_remove_le_device_db_entry(i);
53544f384501SMatthias Ringwald             break;
53554f384501SMatthias Ringwald         }
53564f384501SMatthias Ringwald     }
53574f384501SMatthias Ringwald }
5358