xref: /btstack/src/ble/sm.c (revision b96d60a6103b1a6f7c049e6b27899ce7e6965cfd)
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;
1973deb3ec6SMatthias Ringwald static uint8_t sm_slave_request_security;
1984b8c611fSMatthias Ringwald static uint32_t sm_fixed_passkey_in_display_role;
1991979f09cSMatthias Ringwald static bool sm_reconstruct_ltk_without_le_device_db_entry;
2003deb3ec6SMatthias Ringwald 
201c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
202c123d999SMatthias Ringwald static bool sm_sc_only_mode;
203c59d0c92SMatthias Ringwald static uint8_t sm_sc_oob_random[16];
204c59d0c92SMatthias Ringwald static void (*sm_sc_oob_callback)(const uint8_t * confirm_value, const uint8_t * random_value);
205c59d0c92SMatthias Ringwald static sm_sc_oob_state_t sm_sc_oob_state;
206c59d0c92SMatthias Ringwald #endif
207c59d0c92SMatthias Ringwald 
208899e6e02SMatthias Ringwald 
2091979f09cSMatthias Ringwald static bool                  sm_persistent_keys_random_active;
210899e6e02SMatthias Ringwald static const btstack_tlv_t * sm_tlv_impl;
211899e6e02SMatthias Ringwald static void *                sm_tlv_context;
212899e6e02SMatthias Ringwald 
2133deb3ec6SMatthias Ringwald // Security Manager Master Keys, please use sm_set_er(er) and sm_set_ir(ir) with your own 128 bit random values
2143deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_er;
2153deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_ir;
2163deb3ec6SMatthias Ringwald 
2173deb3ec6SMatthias Ringwald // derived from sm_persistent_ir
2183deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_dhk;
2193deb3ec6SMatthias Ringwald static sm_key_t sm_persistent_irk;
2203deb3ec6SMatthias Ringwald static derived_key_generation_t dkg_state;
2213deb3ec6SMatthias Ringwald 
2223deb3ec6SMatthias Ringwald // derived from sm_persistent_er
2233deb3ec6SMatthias Ringwald // ..
2243deb3ec6SMatthias Ringwald 
2253deb3ec6SMatthias Ringwald // random address update
2263deb3ec6SMatthias Ringwald static random_address_update_t rau_state;
2273deb3ec6SMatthias Ringwald static bd_addr_t sm_random_address;
2283deb3ec6SMatthias Ringwald 
229d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
230514d35fcSMatthias Ringwald // CMAC Calculation: General
231d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_cmac_t sm_cmac_request;
232d1a1f6a4SMatthias Ringwald static void (*sm_cmac_done_callback)(uint8_t hash[8]);
233d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_active;
234d1a1f6a4SMatthias Ringwald static uint8_t sm_cmac_hash[16];
2357a766ebfSMatthias Ringwald #endif
236514d35fcSMatthias Ringwald 
237514d35fcSMatthias Ringwald // CMAC for ATT Signed Writes
2387a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
239d1a1f6a4SMatthias Ringwald static uint16_t        sm_cmac_signed_write_message_len;
240d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_header[3];
241d1a1f6a4SMatthias Ringwald static const uint8_t * sm_cmac_signed_write_message;
242d1a1f6a4SMatthias Ringwald static uint8_t         sm_cmac_signed_write_sign_counter[4];
2437a766ebfSMatthias Ringwald #endif
244514d35fcSMatthias Ringwald 
245514d35fcSMatthias Ringwald // CMAC for Secure Connection functions
246514d35fcSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
247aec94140SMatthias Ringwald static sm_connection_t * sm_cmac_connection;
248514d35fcSMatthias Ringwald static uint8_t           sm_cmac_sc_buffer[80];
249514d35fcSMatthias Ringwald #endif
2503deb3ec6SMatthias Ringwald 
2513deb3ec6SMatthias Ringwald // resolvable private address lookup / CSRK calculation
2523deb3ec6SMatthias Ringwald static int       sm_address_resolution_test;
2533deb3ec6SMatthias Ringwald static int       sm_address_resolution_ah_calculation_active;
2543deb3ec6SMatthias Ringwald static uint8_t   sm_address_resolution_addr_type;
2553deb3ec6SMatthias Ringwald static bd_addr_t sm_address_resolution_address;
2563deb3ec6SMatthias Ringwald static void *    sm_address_resolution_context;
2573deb3ec6SMatthias Ringwald static address_resolution_mode_t sm_address_resolution_mode;
2588f2a52f4SMatthias Ringwald static btstack_linked_list_t sm_address_resolution_general_queue;
2593deb3ec6SMatthias Ringwald 
260d1a1f6a4SMatthias Ringwald // aes128 crypto engine.
2613deb3ec6SMatthias Ringwald static sm_aes128_state_t  sm_aes128_state;
2623deb3ec6SMatthias Ringwald 
263d1a1f6a4SMatthias Ringwald // crypto
264d1a1f6a4SMatthias Ringwald static btstack_crypto_random_t   sm_crypto_random_request;
265d1a1f6a4SMatthias Ringwald static btstack_crypto_aes128_t   sm_crypto_aes128_request;
266d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
267d1a1f6a4SMatthias Ringwald static btstack_crypto_ecc_p256_t sm_crypto_ecc_p256_request;
2687df1ef2fSMatthias Ringwald #endif
2697df1ef2fSMatthias Ringwald 
270d1a1f6a4SMatthias Ringwald // temp storage for random data
271d1a1f6a4SMatthias Ringwald static uint8_t sm_random_data[8];
272d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_key[16];
273d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_plaintext[16];
274d1a1f6a4SMatthias Ringwald static uint8_t sm_aes128_ciphertext[16];
2753deb3ec6SMatthias Ringwald 
276e03e489aSMatthias Ringwald // to receive hci events
277e03e489aSMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
278e03e489aSMatthias Ringwald 
27989a78d34SMatthias Ringwald /* to dispatch sm event */
28089a78d34SMatthias Ringwald static btstack_linked_list_t sm_event_handlers;
28189a78d34SMatthias Ringwald 
282ece00d2dSMatthias Ringwald /* to schedule calls to sm_run */
283ece00d2dSMatthias Ringwald static btstack_timer_source_t sm_run_timer;
284ece00d2dSMatthias Ringwald 
28509e4d397SMatthias Ringwald // LE Secure Connections
28609e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
28709e4d397SMatthias Ringwald static ec_key_generation_state_t ec_key_generation_state;
288fc5bff5fSMatthias Ringwald static uint8_t ec_q[64];
28909e4d397SMatthias Ringwald #endif
290df86eb96SMatthias Ringwald 
2913deb3ec6SMatthias Ringwald //
2923deb3ec6SMatthias Ringwald // Volume 3, Part H, Chapter 24
2933deb3ec6SMatthias Ringwald // "Security shall be initiated by the Security Manager in the device in the master role.
2943deb3ec6SMatthias Ringwald // The device in the slave role shall be the responding device."
2953deb3ec6SMatthias Ringwald // -> master := initiator, slave := responder
2963deb3ec6SMatthias Ringwald //
2973deb3ec6SMatthias Ringwald 
2983deb3ec6SMatthias Ringwald // data needed for security setup
2993deb3ec6SMatthias Ringwald typedef struct sm_setup_context {
3003deb3ec6SMatthias Ringwald 
301ec820d77SMatthias Ringwald     btstack_timer_source_t sm_timeout;
3023deb3ec6SMatthias Ringwald 
3033deb3ec6SMatthias Ringwald     // user response, (Phase 1 and/or 2)
3043deb3ec6SMatthias Ringwald     uint8_t   sm_user_response;
305dd4a08fbSMatthias Ringwald     uint8_t   sm_keypress_notification; // bitmap: passkey started, digit entered, digit erased, passkey cleared, passkey complete, 3 bit count
3063deb3ec6SMatthias Ringwald 
3073deb3ec6SMatthias Ringwald     // defines which keys will be send after connection is encrypted - calculated during Phase 1, used Phase 3
308715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_send_set;
309715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_sent_set;
3109a90d41aSMatthias Ringwald     uint8_t   sm_key_distribution_expected_set;
311715a43d1SMatthias Ringwald     uint8_t   sm_key_distribution_received_set;
3123deb3ec6SMatthias Ringwald 
3133deb3ec6SMatthias Ringwald     // Phase 2 (Pairing over SMP)
3143deb3ec6SMatthias Ringwald     stk_generation_method_t sm_stk_generation_method;
3153deb3ec6SMatthias Ringwald     sm_key_t  sm_tk;
316a680ba6bSMatthias Ringwald     uint8_t   sm_have_oob_data;
31727c32905SMatthias Ringwald     uint8_t   sm_use_secure_connections;
3183deb3ec6SMatthias Ringwald 
3193deb3ec6SMatthias Ringwald     sm_key_t  sm_c1_t3_value;   // c1 calculation
3203deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_m_preq; // pairing request - needed only for c1
3213deb3ec6SMatthias Ringwald     sm_pairing_packet_t sm_s_pres; // pairing response - needed only for c1
3223deb3ec6SMatthias Ringwald     sm_key_t  sm_local_random;
3233deb3ec6SMatthias Ringwald     sm_key_t  sm_local_confirm;
3243deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_random;
3253deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_confirm;
3263deb3ec6SMatthias Ringwald     uint8_t   sm_m_addr_type;   // address and type can be removed
3273deb3ec6SMatthias Ringwald     uint8_t   sm_s_addr_type;   //  ''
3283deb3ec6SMatthias Ringwald     bd_addr_t sm_m_address;     //  ''
3293deb3ec6SMatthias Ringwald     bd_addr_t sm_s_address;     //  ''
3303deb3ec6SMatthias Ringwald     sm_key_t  sm_ltk;
3313deb3ec6SMatthias Ringwald 
33268437d83SMatthias Ringwald     uint8_t   sm_state_vars;
333e53be891SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
334fc5bff5fSMatthias Ringwald     uint8_t   sm_peer_q[64];    // also stores random for EC key generation during init
335446a8c36SMatthias Ringwald     sm_key_t  sm_peer_nonce;    // might be combined with sm_peer_random
336446a8c36SMatthias Ringwald     sm_key_t  sm_local_nonce;   // might be combined with sm_local_random
337d08147dfSMatthias Ringwald     uint8_t   sm_dhkey[32];
338e53be891SMatthias Ringwald     sm_key_t  sm_peer_dhkey_check;
339e53be891SMatthias Ringwald     sm_key_t  sm_local_dhkey_check;
340446a8c36SMatthias Ringwald     sm_key_t  sm_ra;
341446a8c36SMatthias Ringwald     sm_key_t  sm_rb;
3422bacf595SMatthias Ringwald     sm_key_t  sm_t;             // used for f5 and h6
343a9f29768SMatthias Ringwald     sm_key_t  sm_mackey;
3447df18c15SMatthias Ringwald     uint8_t   sm_passkey_bit;   // also stores number of generated random bytes for EC key generation
345e53be891SMatthias Ringwald #endif
34627c32905SMatthias Ringwald 
3473deb3ec6SMatthias Ringwald     // Phase 3
3483deb3ec6SMatthias Ringwald 
3493deb3ec6SMatthias Ringwald     // key distribution, we generate
3503deb3ec6SMatthias Ringwald     uint16_t  sm_local_y;
3513deb3ec6SMatthias Ringwald     uint16_t  sm_local_div;
3523deb3ec6SMatthias Ringwald     uint16_t  sm_local_ediv;
3533deb3ec6SMatthias Ringwald     uint8_t   sm_local_rand[8];
3543deb3ec6SMatthias Ringwald     sm_key_t  sm_local_ltk;
3553deb3ec6SMatthias Ringwald     sm_key_t  sm_local_csrk;
3563deb3ec6SMatthias Ringwald     sm_key_t  sm_local_irk;
3573deb3ec6SMatthias Ringwald     // sm_local_address/addr_type not needed
3583deb3ec6SMatthias Ringwald 
3593deb3ec6SMatthias Ringwald     // key distribution, received from peer
3603deb3ec6SMatthias Ringwald     uint16_t  sm_peer_y;
3613deb3ec6SMatthias Ringwald     uint16_t  sm_peer_div;
3623deb3ec6SMatthias Ringwald     uint16_t  sm_peer_ediv;
3633deb3ec6SMatthias Ringwald     uint8_t   sm_peer_rand[8];
3643deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_ltk;
3653deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_irk;
3663deb3ec6SMatthias Ringwald     sm_key_t  sm_peer_csrk;
3673deb3ec6SMatthias Ringwald     uint8_t   sm_peer_addr_type;
3683deb3ec6SMatthias Ringwald     bd_addr_t sm_peer_address;
369715a43d1SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
370715a43d1SMatthias Ringwald     int       sm_le_device_index;
371715a43d1SMatthias Ringwald #endif
372e0a03c85SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
373e0a03c85SMatthias Ringwald     link_key_t sm_link_key;
374e0a03c85SMatthias Ringwald     link_key_type_t sm_link_key_type;
375e0a03c85SMatthias Ringwald #endif
3763deb3ec6SMatthias Ringwald } sm_setup_context_t;
3773deb3ec6SMatthias Ringwald 
3783deb3ec6SMatthias Ringwald //
3793deb3ec6SMatthias Ringwald static sm_setup_context_t the_setup;
3803deb3ec6SMatthias Ringwald static sm_setup_context_t * setup = &the_setup;
3813deb3ec6SMatthias Ringwald 
3823deb3ec6SMatthias Ringwald // active connection - the one for which the_setup is used for
3837149bde5SMatthias Ringwald static uint16_t sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
3843deb3ec6SMatthias Ringwald 
3856b65794dSMilanka Ringwald // @return 1 if oob data is available
3863deb3ec6SMatthias Ringwald // stores oob data in provided 16 byte buffer if not null
3873deb3ec6SMatthias Ringwald static int (*sm_get_oob_data)(uint8_t addres_type, bd_addr_t addr, uint8_t * oob_data) = NULL;
3884acf7b7bSMatthias 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);
389*b96d60a6SMatthias Ringwald static bool (*sm_get_ltk_callback)(hci_con_handle_t con_handle, uint8_t addres_type, bd_addr_t addr, uint8_t * ltk);
3903deb3ec6SMatthias Ringwald 
3913deb3ec6SMatthias Ringwald static void sm_run(void);
392711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
393711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39477e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39577e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
39677e2e5edSMatthias Ringwald #endif
3973deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3983deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
408d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4092a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
411d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4122a526f21SMatthias Ringwald #endif
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
415d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
416d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
417d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4186d80b495SMatthias 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));
41934b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4206ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4216ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4222a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
423d1a1f6a4SMatthias Ringwald #endif
4240ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4253deb3ec6SMatthias Ringwald 
4263deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4273deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4283deb3ec6SMatthias Ringwald }
4293deb3ec6SMatthias Ringwald 
4301fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4311fbd72c5SMatthias Ringwald //     return packet[0];
4321fbd72c5SMatthias Ringwald // }
4331fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4341fbd72c5SMatthias Ringwald     return packet[1];
4351fbd72c5SMatthias Ringwald }
4361fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4371fbd72c5SMatthias Ringwald     return packet[2];
4381fbd72c5SMatthias Ringwald }
4391fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4401fbd72c5SMatthias Ringwald     return packet[3];
4411fbd72c5SMatthias Ringwald }
4421fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4431fbd72c5SMatthias Ringwald     return packet[4];
4441fbd72c5SMatthias Ringwald }
4451fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4461fbd72c5SMatthias Ringwald     return packet[5];
4471fbd72c5SMatthias Ringwald }
4481fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4491fbd72c5SMatthias Ringwald     return packet[6];
4501fbd72c5SMatthias Ringwald }
4511fbd72c5SMatthias Ringwald 
4521fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4531fbd72c5SMatthias Ringwald     packet[0] = code;
4541fbd72c5SMatthias Ringwald }
4551fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4561fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4571fbd72c5SMatthias Ringwald }
4581fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4591fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4601fbd72c5SMatthias Ringwald }
4611fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4621fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4631fbd72c5SMatthias Ringwald }
4641fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4651fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4661fbd72c5SMatthias Ringwald }
4671fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4681fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4691fbd72c5SMatthias Ringwald }
4701fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4711fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4721fbd72c5SMatthias Ringwald }
4731fbd72c5SMatthias Ringwald 
4746b65794dSMilanka Ringwald // @return 1 if all bytes are 0
4751979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4763deb3ec6SMatthias Ringwald     int i;
4773764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47884c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4791979f09cSMatthias Ringwald             return false;
48084c0c5c7SMatthias Ringwald         }
4813deb3ec6SMatthias Ringwald     }
4821979f09cSMatthias Ringwald     return true;
4833deb3ec6SMatthias Ringwald }
4843deb3ec6SMatthias Ringwald 
4851979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4863764b551SMatthias Ringwald     return sm_is_null(random, 8);
4873764b551SMatthias Ringwald }
4883764b551SMatthias Ringwald 
4891979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4903764b551SMatthias Ringwald     return sm_is_null(key, 16);
4913764b551SMatthias Ringwald }
4923764b551SMatthias Ringwald 
49370b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49470b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49570b44dd4SMatthias Ringwald 	UNUSED(ts);
49670b44dd4SMatthias Ringwald 	sm_run();
49770b44dd4SMatthias Ringwald }
49870b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4992d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
50084c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50170b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50270b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50370b44dd4SMatthias Ringwald }
50470b44dd4SMatthias Ringwald 
5053deb3ec6SMatthias Ringwald // Key utils
5063deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5073deb3ec6SMatthias Ringwald     int i;
5083deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5093deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5103deb3ec6SMatthias Ringwald     }
5113deb3ec6SMatthias Ringwald }
5123deb3ec6SMatthias Ringwald 
5133deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5143deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5153deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5163deb3ec6SMatthias Ringwald     int i;
5173deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5183deb3ec6SMatthias Ringwald         key[15-i] = 0;
5193deb3ec6SMatthias Ringwald     }
5203deb3ec6SMatthias Ringwald }
5213deb3ec6SMatthias Ringwald 
522899e6e02SMatthias Ringwald // ER / IR checks
52321045273SMatthias Ringwald static void sm_er_ir_set_default(void){
524899e6e02SMatthias Ringwald     int i;
525899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
526899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
527899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
528899e6e02SMatthias Ringwald     }
529899e6e02SMatthias Ringwald }
530899e6e02SMatthias Ringwald 
531899e6e02SMatthias Ringwald static int sm_er_is_default(void){
532899e6e02SMatthias Ringwald     int i;
533899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
534899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
535899e6e02SMatthias Ringwald     }
536899e6e02SMatthias Ringwald     return 1;
537899e6e02SMatthias Ringwald }
538899e6e02SMatthias Ringwald 
539899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
540899e6e02SMatthias Ringwald     int i;
541899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
542899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
543899e6e02SMatthias Ringwald     }
544899e6e02SMatthias Ringwald     return 1;
545899e6e02SMatthias Ringwald }
546899e6e02SMatthias Ringwald 
54773102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54873102768SMatthias Ringwald     UNUSED(channel);
54973102768SMatthias Ringwald 
55073102768SMatthias Ringwald     // log event
55173102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55273102768SMatthias Ringwald     // dispatch to all event handlers
55373102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55473102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55573102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55673102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55773102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55873102768SMatthias Ringwald     }
55973102768SMatthias Ringwald }
56073102768SMatthias Ringwald 
56173102768SMatthias 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){
56273102768SMatthias Ringwald     event[0] = type;
56373102768SMatthias Ringwald     event[1] = event_size - 2;
56473102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56573102768SMatthias Ringwald     event[4] = addr_type;
56673102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56773102768SMatthias Ringwald }
56873102768SMatthias Ringwald 
56973102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
57073102768SMatthias Ringwald     uint8_t event[11];
57173102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57373102768SMatthias Ringwald }
57473102768SMatthias Ringwald 
57573102768SMatthias Ringwald static void sm_notify_client_passkey(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address, uint32_t passkey){
57673102768SMatthias Ringwald     uint8_t event[15];
57773102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57873102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57973102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
58073102768SMatthias Ringwald }
58173102768SMatthias Ringwald 
58273102768SMatthias 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){
58373102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58473102768SMatthias Ringwald     bd_addr_t identity_address;
58573102768SMatthias Ringwald     int identity_address_type;
58673102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58773102768SMatthias Ringwald 
58873102768SMatthias Ringwald     uint8_t event[20];
58973102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59073102768SMatthias Ringwald     event[11] = identity_address_type;
59173102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
59273102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
59373102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59473102768SMatthias Ringwald }
59573102768SMatthias Ringwald 
59673102768SMatthias 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){
59773102768SMatthias Ringwald     uint8_t event[12];
59873102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59973102768SMatthias Ringwald     event[11] = status;
60073102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
60173102768SMatthias Ringwald }
60273102768SMatthias Ringwald 
60373102768SMatthias Ringwald 
60473102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60573102768SMatthias Ringwald 
6063ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6073ab61f77SMatthias Ringwald 
6087b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60973102768SMatthias Ringwald 
61073102768SMatthias Ringwald     int       identity_addr_type;
61173102768SMatthias Ringwald     bd_addr_t identity_addr;
6123c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6133c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61473102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6153c0e26deSMatthias Ringwald     } else {
6163c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6173c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6183c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6193c0e26deSMatthias Ringwald     }
62073102768SMatthias Ringwald 
62173102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
62273102768SMatthias Ringwald }
62373102768SMatthias Ringwald 
62473102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62573102768SMatthias Ringwald 
62660be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62760be5b21SMatthias Ringwald 
6287b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62973102768SMatthias Ringwald 
63073102768SMatthias Ringwald     int       identity_addr_type;
63173102768SMatthias Ringwald     bd_addr_t identity_addr;
6323c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6333c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63473102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6353c0e26deSMatthias Ringwald     } else {
6363c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6373c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6383c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6393c0e26deSMatthias Ringwald     }
64073102768SMatthias Ringwald 
64173102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
64273102768SMatthias Ringwald }
64373102768SMatthias Ringwald 
644d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
645d3c12277SMatthias Ringwald 
646d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
647d3c12277SMatthias Ringwald 
648d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
649d3c12277SMatthias Ringwald 
650d3c12277SMatthias Ringwald     uint8_t event[11];
651d3c12277SMatthias 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);
652d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
653d3c12277SMatthias Ringwald }
654d3c12277SMatthias Ringwald 
6550ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
656f61072f5SMatthias Ringwald 
657d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
658d77906ffSMatthias Ringwald 
65969f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
66069f82ad8SMatthias Ringwald 
6610ccf6c9cSMatthias Ringwald     uint8_t event[13];
6620ccf6c9cSMatthias 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);
6630ccf6c9cSMatthias Ringwald     event[11] = status;
6640ccf6c9cSMatthias Ringwald     event[12] = reason;
6650ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6660ccf6c9cSMatthias Ringwald }
6670ccf6c9cSMatthias Ringwald 
6683deb3ec6SMatthias Ringwald // SMP Timeout implementation
6693deb3ec6SMatthias Ringwald 
6703deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6713deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6723deb3ec6SMatthias Ringwald //
6733deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6743deb3ec6SMatthias Ringwald //
6753deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6763deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6773deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6783deb3ec6SMatthias Ringwald // established.
6793deb3ec6SMatthias Ringwald 
680ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6813deb3ec6SMatthias Ringwald     log_info("SM timeout");
682c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6833deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68468a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6850ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6863deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6873deb3ec6SMatthias Ringwald 
6883deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6893deb3ec6SMatthias Ringwald     sm_run();
6903deb3ec6SMatthias Ringwald }
6913deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
692528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
69391a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
694528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
695528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
696528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6973deb3ec6SMatthias Ringwald }
6983deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
699528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
7003deb3ec6SMatthias Ringwald }
7013deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
7023deb3ec6SMatthias Ringwald     sm_timeout_stop();
7033deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7043deb3ec6SMatthias Ringwald }
7053deb3ec6SMatthias Ringwald 
7063deb3ec6SMatthias Ringwald // end of sm timeout
7073deb3ec6SMatthias Ringwald 
7083deb3ec6SMatthias Ringwald // GAP Random Address updates
7093deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
710ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7113deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7123deb3ec6SMatthias Ringwald 
7133deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
714899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
715d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
716fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71770b44dd4SMatthias Ringwald     sm_trigger_run();
7183deb3ec6SMatthias Ringwald }
7193deb3ec6SMatthias Ringwald 
720ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7219ec2630cSMatthias Ringwald     UNUSED(timer);
7229ec2630cSMatthias Ringwald 
7233deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
724528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
725528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7263deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7273deb3ec6SMatthias Ringwald }
7283deb3ec6SMatthias Ringwald 
7293deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
730528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
731528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
732528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7333deb3ec6SMatthias Ringwald }
7343deb3ec6SMatthias Ringwald 
7353deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
736528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7373deb3ec6SMatthias Ringwald }
7383deb3ec6SMatthias Ringwald 
7393deb3ec6SMatthias Ringwald // ah(k,r) helper
7403deb3ec6SMatthias Ringwald // r = padding || r
7413deb3ec6SMatthias Ringwald // r - 24 bit value
7424a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7433deb3ec6SMatthias Ringwald     // r'= padding || r
7443deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7456535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7463deb3ec6SMatthias Ringwald }
7473deb3ec6SMatthias Ringwald 
7483deb3ec6SMatthias Ringwald // d1 helper
7493deb3ec6SMatthias Ringwald // d' = padding || r || d
7503deb3ec6SMatthias Ringwald // d,r - 16 bit values
7514a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7523deb3ec6SMatthias Ringwald     // d'= padding || r || d
7533deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
754f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
755f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7563deb3ec6SMatthias Ringwald }
7573deb3ec6SMatthias Ringwald 
7583deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7594a6806f3SMatthias 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){
7603deb3ec6SMatthias Ringwald 
7613deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7623deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7633deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7643deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7653deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7663deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7673deb3ec6SMatthias Ringwald 
7683deb3ec6SMatthias Ringwald     sm_key_t p1;
7699c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7709c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7713deb3ec6SMatthias Ringwald     p1[14] = rat;
7723deb3ec6SMatthias Ringwald     p1[15] = iat;
7738314c363SMatthias Ringwald     log_info_key("p1", p1);
7748314c363SMatthias Ringwald     log_info_key("r", r);
7753deb3ec6SMatthias Ringwald 
7763deb3ec6SMatthias Ringwald     // t1 = r xor p1
7773deb3ec6SMatthias Ringwald     int i;
7783deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7793deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7803deb3ec6SMatthias Ringwald     }
7818314c363SMatthias Ringwald     log_info_key("t1", t1);
7823deb3ec6SMatthias Ringwald }
7833deb3ec6SMatthias Ringwald 
7843deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7854a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7863deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7873deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7883deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7893deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7903deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7913deb3ec6SMatthias Ringwald 
7923deb3ec6SMatthias Ringwald     sm_key_t p2;
7933deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7946535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7956535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7968314c363SMatthias Ringwald     log_info_key("p2", p2);
7973deb3ec6SMatthias Ringwald 
7983deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7993deb3ec6SMatthias Ringwald     int i;
8003deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
8013deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
8023deb3ec6SMatthias Ringwald     }
8038314c363SMatthias Ringwald     log_info_key("t3", t3);
8043deb3ec6SMatthias Ringwald }
8053deb3ec6SMatthias Ringwald 
8064a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8078314c363SMatthias Ringwald     log_info_key("r1", r1);
8088314c363SMatthias Ringwald     log_info_key("r2", r2);
8096535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8106535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8113deb3ec6SMatthias Ringwald }
8123deb3ec6SMatthias Ringwald 
813fbe050beSMatthias Ringwald 
8143deb3ec6SMatthias Ringwald // decide on stk generation based on
8153deb3ec6SMatthias Ringwald // - pairing request
8163deb3ec6SMatthias Ringwald // - io capabilities
8173deb3ec6SMatthias Ringwald // - OOB data availability
8183deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8193deb3ec6SMatthias Ringwald 
8208334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8218334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8228334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8238334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8248334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8258334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8268334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8278334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8288334d3d8SMatthias Ringwald     };
8298334d3d8SMatthias Ringwald 
8308334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8318334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8328334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8338334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8348334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8358334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8368334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8378334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8388334d3d8SMatthias Ringwald     };
8398334d3d8SMatthias Ringwald #endif
8408334d3d8SMatthias Ringwald 
8413deb3ec6SMatthias Ringwald     // default: just works
8423deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8433deb3ec6SMatthias Ringwald 
84427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84527c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84627c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8474ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84827c32905SMatthias Ringwald #else
84927c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
85027c32905SMatthias Ringwald #endif
85198d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
85227c32905SMatthias Ringwald 
85365a9a04eSMatthias Ringwald 
85465a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8551979f09cSMatthias Ringwald     bool use_oob;
85665a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85765a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85865a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8591979f09cSMatthias 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;
86065a9a04eSMatthias Ringwald     } else {
86165a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
86265a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8631979f09cSMatthias 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;
86465a9a04eSMatthias Ringwald     }
86565a9a04eSMatthias Ringwald     if (use_oob){
86665a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86765a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86865a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86965a9a04eSMatthias Ringwald         return;
87065a9a04eSMatthias Ringwald     }
87165a9a04eSMatthias Ringwald 
87227c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
87327c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87427c32905SMatthias Ringwald     // model shall be used.
8754ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8764ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87727c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87827c32905SMatthias Ringwald         return;
87927c32905SMatthias Ringwald     }
88027c32905SMatthias Ringwald 
8813deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8823deb3ec6SMatthias Ringwald     sm_reset_tk();
8833deb3ec6SMatthias Ringwald 
8843deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8858da2e96dSMatthias 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)){
8863deb3ec6SMatthias Ringwald         return;
8873deb3ec6SMatthias Ringwald     }
8883deb3ec6SMatthias Ringwald 
8893deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8903deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
89127c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
89227c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
89327c32905SMatthias Ringwald 
89427c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
895c6b7cbd9SMatthias Ringwald     // table not define by default
89627c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89727c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89827c32905SMatthias Ringwald     }
89927c32905SMatthias Ringwald #endif
90027c32905SMatthias 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)];
90127c32905SMatthias Ringwald 
9023deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
9031ad129beSMatthias 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);
9043deb3ec6SMatthias Ringwald }
9053deb3ec6SMatthias Ringwald 
9063deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9073deb3ec6SMatthias Ringwald     int flags = 0;
9083deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9103deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9113deb3ec6SMatthias Ringwald     }
9123deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9143deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9153deb3ec6SMatthias Ringwald     }
9163deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9173deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9183deb3ec6SMatthias Ringwald     }
9193deb3ec6SMatthias Ringwald     return flags;
9203deb3ec6SMatthias Ringwald }
9213deb3ec6SMatthias Ringwald 
9229a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9233deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9249a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9259a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
926715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9279790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
928715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9299790be5fSMatthias Ringwald #endif
9303deb3ec6SMatthias Ringwald }
9313deb3ec6SMatthias Ringwald 
9323deb3ec6SMatthias Ringwald // CSRK Key Lookup
9333deb3ec6SMatthias Ringwald 
9343deb3ec6SMatthias Ringwald 
9353deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9363deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9373deb3ec6SMatthias Ringwald }
9383deb3ec6SMatthias Ringwald 
939711e6c80SMatthias 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){
9406535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9413deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9423deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9433deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9443deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
945711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9463deb3ec6SMatthias Ringwald }
9473deb3ec6SMatthias Ringwald 
9483deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9493deb3ec6SMatthias Ringwald     // check if already in list
950665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9513deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
952665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
953665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
954665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9553deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9563deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9573deb3ec6SMatthias Ringwald         // already in list
9583deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9593deb3ec6SMatthias Ringwald     }
9603deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9613deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9623deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9636535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
964665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96570b44dd4SMatthias Ringwald     sm_trigger_run();
9663deb3ec6SMatthias Ringwald     return 0;
9673deb3ec6SMatthias Ringwald }
9683deb3ec6SMatthias Ringwald 
969d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
970d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
971514d35fcSMatthias Ringwald 
972d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
973d1a1f6a4SMatthias Ringwald     UNUSED(arg);
974d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
975d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97670b44dd4SMatthias Ringwald     sm_trigger_run();
9773deb3ec6SMatthias Ringwald }
978514d35fcSMatthias Ringwald 
9794dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9804ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9813deb3ec6SMatthias Ringwald }
9826d80b495SMatthias Ringwald #endif
9833deb3ec6SMatthias Ringwald 
9846d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
985514d35fcSMatthias Ringwald // generic cmac calculation
986d1a1f6a4SMatthias 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)){
987d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
988d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
989d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9903deb3ec6SMatthias Ringwald }
9917a766ebfSMatthias Ringwald #endif
9923deb3ec6SMatthias Ringwald 
993514d35fcSMatthias Ringwald // cmac for ATT Message signing
9947a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
995d1a1f6a4SMatthias Ringwald 
996d1a1f6a4SMatthias 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)){
997d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
998d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
999d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
1000d1a1f6a4SMatthias Ringwald }
1001d1a1f6a4SMatthias Ringwald 
10024dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
1003d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1004d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10054dfd504aSMatthias Ringwald         return 0;
10064dfd504aSMatthias Ringwald     }
10074dfd504aSMatthias Ringwald 
1008d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10094dfd504aSMatthias Ringwald 
1010d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10114dfd504aSMatthias Ringwald     if (offset < 3){
1012d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10134dfd504aSMatthias Ringwald     }
1014d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10154dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1016d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10174dfd504aSMatthias Ringwald     }
1018d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10194dfd504aSMatthias Ringwald }
10204dfd504aSMatthias Ringwald 
10214dfd504aSMatthias 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)){
1022514d35fcSMatthias Ringwald     // ATT Message Signing
1023d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1024d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1025d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1026514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1027d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1028d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1029d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10303deb3ec6SMatthias Ringwald }
10317a766ebfSMatthias Ringwald #endif
10323deb3ec6SMatthias Ringwald 
10333deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1034446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10353deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1036d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10373deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10383deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103942134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10403deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10415611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10423deb3ec6SMatthias Ringwald             } else {
1043c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10443deb3ec6SMatthias Ringwald             }
10453deb3ec6SMatthias Ringwald             break;
10463deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
104742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1048c9b8fdd9SMatthias Ringwald                 sm_notify_client_passkey(SM_EVENT_PASSKEY_DISPLAY_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
10493deb3ec6SMatthias Ringwald             } else {
10503deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10515611a760SMatthias Ringwald                 sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10523deb3ec6SMatthias Ringwald             }
10533deb3ec6SMatthias Ringwald             break;
105447fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10553deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10565611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_PASSKEY_INPUT_NUMBER, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
10573deb3ec6SMatthias Ringwald             break;
105847fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1059446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1060c8c46d51SMatthias Ringwald             sm_notify_client_passkey(SM_EVENT_NUMERIC_COMPARISON_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, big_endian_read_32(setup->sm_tk, 12));
106127c32905SMatthias Ringwald             break;
10623deb3ec6SMatthias Ringwald         case JUST_WORKS:
10633deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10645611a760SMatthias Ringwald             sm_notify_client_base(SM_EVENT_JUST_WORKS_REQUEST, sm_conn->sm_handle, sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address);
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) {
1076b2296177SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, bution_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 
152355f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
152455f09f49SMatthias Ringwald 
152555f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
152655f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
152755f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
152855f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
152955f09f49SMatthias Ringwald 
153055f09f49SMatthias Ringwald     if (bonding_enabled){
153155f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
153227ef8bc8SMatthias Ringwald     } else {
153327ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153427ef8bc8SMatthias Ringwald     }
15353deb3ec6SMatthias Ringwald }
15363deb3ec6SMatthias Ringwald 
1537688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1538f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1539688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1540688a08f9SMatthias Ringwald }
1541688a08f9SMatthias Ringwald 
1542688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1543688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1544688a08f9SMatthias Ringwald }
1545688a08f9SMatthias Ringwald 
15469af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1547688a08f9SMatthias Ringwald 
1548dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1549945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1550f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1551dc300847SMatthias Ringwald 
1552b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1553b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15541f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1555b90c4e75SMatthias Ringwald     } else {
1556b90c4e75SMatthias 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);
1557b35a3de2SMatthias Ringwald     }
1558b35a3de2SMatthias Ringwald }
1559b35a3de2SMatthias Ringwald 
1560688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
156142134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1562688a08f9SMatthias Ringwald         // Responder
15634acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15644acf7b7bSMatthias Ringwald             // generate Nb
15654acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15666ca80073SMatthias 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);
15674acf7b7bSMatthias Ringwald         } else {
1568688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15694acf7b7bSMatthias Ringwald         }
1570688a08f9SMatthias Ringwald     } else {
1571688a08f9SMatthias Ringwald         // Initiator role
1572688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1573688a08f9SMatthias Ringwald             case JUST_WORKS:
1574dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1575688a08f9SMatthias Ringwald                 break;
1576688a08f9SMatthias Ringwald 
157747fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1578bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1579688a08f9SMatthias Ringwald                 break;
1580688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1581688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
158247fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15834ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1584b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1585688a08f9SMatthias Ringwald                 } else {
1586dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1587688a08f9SMatthias Ringwald                 }
1588688a08f9SMatthias Ringwald                 break;
1589688a08f9SMatthias Ringwald             case OOB:
159065a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1591688a08f9SMatthias Ringwald                 break;
15927bbeb3adSMilanka Ringwald             default:
15937bbeb3adSMilanka Ringwald                 btstack_assert(false);
15947bbeb3adSMilanka Ringwald                 break;
1595688a08f9SMatthias Ringwald         }
1596688a08f9SMatthias Ringwald     }
1597688a08f9SMatthias Ringwald }
1598688a08f9SMatthias Ringwald 
1599aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1600688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1601688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1602688a08f9SMatthias Ringwald 
1603c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1604c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1605a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1606c59d0c92SMatthias Ringwald         return;
1607c59d0c92SMatthias Ringwald     }
1608c59d0c92SMatthias Ringwald 
1609bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1610bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16116857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16122bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1613b4f65634SMatthias Ringwald #endif
1614bd57ffebSMatthias Ringwald 
1615bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1616aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16176535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1618bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1619aec94140SMatthias Ringwald             break;
1620688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1621688a08f9SMatthias Ringwald             // check
1622688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1623bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1624688a08f9SMatthias Ringwald                 break;
1625688a08f9SMatthias Ringwald             }
1626bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1627688a08f9SMatthias Ringwald             break;
1628901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1629901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1630901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1631901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1632901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1633019005a0SMatthias Ringwald             break;
1634019005a0SMatthias Ringwald         }
16350346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16366535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1637bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16380346c37cSMatthias Ringwald             break;
16390346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16406535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1641bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16420346c37cSMatthias Ringwald             break;
16430346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1644b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1645b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1646b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1647b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16486535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16496535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1650893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1651bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1652019005a0SMatthias Ringwald             break;
1653901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16546535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165542134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1656901c000fSMatthias Ringwald                 // responder
1657901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1658901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1659901c000fSMatthias Ringwald                 } else {
1660901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1661901c000fSMatthias Ringwald                 }
1662901c000fSMatthias Ringwald             } else {
1663901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1664901c000fSMatthias Ringwald             }
1665901c000fSMatthias Ringwald             break;
1666901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1667901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1668901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1669aec94140SMatthias Ringwald                 break;
1670aec94140SMatthias Ringwald             }
167142134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1672901c000fSMatthias Ringwald                 // responder
1673901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1674901c000fSMatthias Ringwald             } else {
1675901c000fSMatthias Ringwald                 // initiator
1676901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1677bd57ffebSMatthias Ringwald             }
1678901c000fSMatthias Ringwald             break;
16796857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
168057132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16816535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
168257132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16832bacf595SMatthias Ringwald             break;
168457132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16852bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16862bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16872bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16888974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168955160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16908974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16912bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16922bacf595SMatthias Ringwald             } else {
16932bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16942bacf595SMatthias Ringwald             }
16950ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16962bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16972bacf595SMatthias Ringwald             break;
1698e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1699e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1700e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1701e0a03c85SMatthias Ringwald             break;
1702e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1703e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1704e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1705e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1706e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1707e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1708e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1709c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1710e0a03c85SMatthias Ringwald             break;
1711bdb14b0eSMatthias Ringwald #endif
1712bd57ffebSMatthias Ringwald         default:
1713bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1714bd57ffebSMatthias Ringwald             break;
1715bd57ffebSMatthias Ringwald     }
171670b44dd4SMatthias Ringwald     sm_trigger_run();
1717aec94140SMatthias Ringwald }
1718aec94140SMatthias Ringwald 
1719688a08f9SMatthias 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){
1720dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1721aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17226535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17236535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1724aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1725aec94140SMatthias Ringwald     log_info("f4 key");
1726aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1727aec94140SMatthias Ringwald     log_info("f4 message");
1728dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1729d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1730aec94140SMatthias Ringwald }
1731aec94140SMatthias Ringwald 
17320346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17330346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17340346c37cSMatthias Ringwald 
17350346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17368334d3d8SMatthias Ringwald 
17378334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17388334d3d8SMatthias Ringwald 
173940c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17400346c37cSMatthias Ringwald     // calculate salt for f5
17410346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17420346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17436535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1744d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17450346c37cSMatthias Ringwald }
17460346c37cSMatthias Ringwald 
17470346c37cSMatthias 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){
17480346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17490346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17500346c37cSMatthias Ringwald 
17510346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17520346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17566535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17576535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17586535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17590346c37cSMatthias Ringwald     log_info("f5 key");
17600346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17610346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17620346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1763d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17640346c37cSMatthias Ringwald }
17650346c37cSMatthias Ringwald 
17660346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17670346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17680346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17690346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17706535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17716535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
177242134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17730346c37cSMatthias Ringwald         // responder
17740346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17750346c37cSMatthias Ringwald     } else {
17760346c37cSMatthias Ringwald         // initiator
17770346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17780346c37cSMatthias Ringwald     }
17790346c37cSMatthias Ringwald }
17800346c37cSMatthias Ringwald 
17810346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17820346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17830346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17840346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17850346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17860346c37cSMatthias Ringwald     // 1..52 setup before
17870346c37cSMatthias Ringwald     log_info("f5 key");
17880346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17890346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17900346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1791d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17920346c37cSMatthias Ringwald }
1793f92edc8eSMatthias Ringwald 
17940346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17950346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17960346c37cSMatthias Ringwald }
17970346c37cSMatthias Ringwald 
179831f061fbSMatthias 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){
17996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
18006535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
18026535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18036535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18046535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
180531f061fbSMatthias Ringwald }
180631f061fbSMatthias Ringwald 
180731f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180831f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180931f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1810dc300847SMatthias Ringwald     log_info("f6 key");
1811dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1812dc300847SMatthias Ringwald     log_info("f6 message");
1813dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1814d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1815dc300847SMatthias Ringwald }
1816dc300847SMatthias Ringwald 
1817f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1818f92edc8eSMatthias Ringwald // - U is 256 bits
1819f92edc8eSMatthias Ringwald // - V is 256 bits
1820f92edc8eSMatthias Ringwald // - X is 128 bits
1821f92edc8eSMatthias Ringwald // - Y is 128 bits
1822bd57ffebSMatthias 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){
1823bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1824bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18256535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18266535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18276535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1828f92edc8eSMatthias Ringwald     log_info("g2 key");
1829f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1830f92edc8eSMatthias Ringwald     log_info("g2 message");
18312bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1832d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1833f92edc8eSMatthias Ringwald }
1834f92edc8eSMatthias Ringwald 
1835b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1836f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
183742134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1838f92edc8eSMatthias Ringwald         // responder
1839fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1840f92edc8eSMatthias Ringwald     } else {
1841f92edc8eSMatthias Ringwald         // initiator
1842fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1843f92edc8eSMatthias Ringwald     }
1844f92edc8eSMatthias Ringwald }
1845f92edc8eSMatthias Ringwald 
1846945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18479af0f475SMatthias Ringwald     uint8_t z = 0;
184840c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18499af0f475SMatthias Ringwald         // some form of passkey
18509af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18514ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18529af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18539af0f475SMatthias Ringwald     }
1854fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18559af0f475SMatthias Ringwald }
1856688a08f9SMatthias Ringwald 
1857688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1858a680ba6bSMatthias Ringwald     // OOB
1859a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18604acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18614acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18624acf7b7bSMatthias Ringwald         } else {
18634acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18644acf7b7bSMatthias Ringwald         }
1865a680ba6bSMatthias Ringwald         return;
1866a680ba6bSMatthias Ringwald     }
1867a680ba6bSMatthias Ringwald 
1868688a08f9SMatthias Ringwald     uint8_t z = 0;
186940c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1870688a08f9SMatthias Ringwald         // some form of passkey
1871688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1872688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18734ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1874688a08f9SMatthias Ringwald     }
1875fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1876688a08f9SMatthias Ringwald }
1877688a08f9SMatthias Ringwald 
18780346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1879505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18803cf37b8cSMatthias Ringwald 
18813cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18823cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18833cf37b8cSMatthias Ringwald         return;
18843cf37b8cSMatthias Ringwald     } else {
18853cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18863cf37b8cSMatthias Ringwald     }
1887d1a1f6a4SMatthias Ringwald }
18883cf37b8cSMatthias Ringwald 
1889d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1890f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1891f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1892f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1893f3582630SMatthias Ringwald 
1894d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1895d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1896d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1897d1a1f6a4SMatthias Ringwald     // trigger next step
1898d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1899d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1900d1a1f6a4SMatthias Ringwald     }
190170b44dd4SMatthias Ringwald     sm_trigger_run();
1902dc300847SMatthias Ringwald }
1903dc300847SMatthias Ringwald 
1904dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1905dc300847SMatthias Ringwald     // calculate DHKCheck
1906dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1907dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1908dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19096535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19106535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1911dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1912dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1913dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1914dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1915dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1916dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1917dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1918dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1920dc300847SMatthias Ringwald         // responder
192131f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
192231f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1923dc300847SMatthias Ringwald     } else {
1924dc300847SMatthias Ringwald         // initiator
192531f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192631f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1927dc300847SMatthias Ringwald     }
1928dc300847SMatthias Ringwald }
1929dc300847SMatthias Ringwald 
1930019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1931019005a0SMatthias Ringwald     // validate E = f6()
1932019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1933019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1934019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19356535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19366535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1937019005a0SMatthias Ringwald 
1938019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1939019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1940019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1941019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1942019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1943019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1944019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1945019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
194642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1947019005a0SMatthias Ringwald         // responder
194831f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1950019005a0SMatthias Ringwald     } else {
1951019005a0SMatthias Ringwald         // initiator
195231f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
195331f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1954019005a0SMatthias Ringwald     }
1955019005a0SMatthias Ringwald }
19562bacf595SMatthias Ringwald 
195755c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19582bacf595SMatthias Ringwald 
19592bacf595SMatthias Ringwald //
19602bacf595SMatthias Ringwald // Link Key Conversion Function h6
19612bacf595SMatthias Ringwald //
196257132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19632bacf595SMatthias Ringwald // - W is 128 bits
19642bacf595SMatthias Ringwald // - keyID is 32 bits
19652bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19662bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19672bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19682bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19692bacf595SMatthias Ringwald     log_info("h6 key");
19702bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19712bacf595SMatthias Ringwald     log_info("h6 message");
19722bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1973d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19742bacf595SMatthias Ringwald }
197557132f12SMatthias Ringwald //
197657132f12SMatthias Ringwald // Link Key Conversion Function h7
197757132f12SMatthias Ringwald //
197857132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197957132f12SMatthias Ringwald // - SALT is 128 bits
198057132f12SMatthias Ringwald // - W    is 128 bits
198157132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
198257132f12SMatthias Ringwald 	const uint16_t message_len = 16;
198357132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
198457132f12SMatthias Ringwald 	log_info("h7 key");
198557132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
198657132f12SMatthias Ringwald 	log_info("h7 message");
198757132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198857132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198957132f12SMatthias Ringwald }
19902bacf595SMatthias Ringwald 
1991b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1992b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1993b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1994b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
199557132f12SMatthias Ringwald 
1996c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1997b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19982bacf595SMatthias Ringwald }
19992bacf595SMatthias Ringwald 
2000e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2001e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
2002e0a03c85SMatthias Ringwald }
2003e0a03c85SMatthias Ringwald 
20042bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20052bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20062bacf595SMatthias Ringwald }
20072bacf595SMatthias Ringwald 
2008e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2009e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2010e0a03c85SMatthias Ringwald }
2011e0a03c85SMatthias Ringwald 
2012c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
201357132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
201457132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
201557132f12SMatthias Ringwald }
2016e0a03c85SMatthias Ringwald 
2017e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2018e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2019e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2020e0a03c85SMatthias Ringwald }
2021e0a03c85SMatthias Ringwald 
2022c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2023e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2024e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2025e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2026e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2027e0a03c85SMatthias Ringwald }
2028e0a03c85SMatthias Ringwald 
2029c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2030c18be159SMatthias 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;
2031c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2032c18be159SMatthias Ringwald }
2033c18be159SMatthias Ringwald 
20349af0f475SMatthias Ringwald #endif
20359af0f475SMatthias Ringwald 
203655c62cf5SMatthias Ringwald #endif
203755c62cf5SMatthias Ringwald 
2038613da3deSMatthias Ringwald // key management legacy connections:
2039613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2040613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2041613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2042613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2043613da3deSMatthias Ringwald 
2044613da3deSMatthias Ringwald // key management secure connections:
2045613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2046613da3deSMatthias Ringwald 
204742134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20485829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20495829ebe2SMatthias Ringwald     int encryption_key_size;
20505829ebe2SMatthias Ringwald     int authenticated;
20515829ebe2SMatthias Ringwald     int authorized;
20523dc3a67dSMatthias Ringwald     int secure_connection;
20535829ebe2SMatthias Ringwald 
20545829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20555829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20563dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20573dc3a67dSMatthias 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);
20585829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20595829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20605829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20613dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20625829ebe2SMatthias Ringwald }
206342134bc6SMatthias Ringwald #endif
2064bd57ffebSMatthias Ringwald 
206542134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
206659066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20676535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
206859066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
206959066796SMatthias Ringwald     // re-establish used key encryption size
207059066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20714ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
207259066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20734ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20743dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20753dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
207659066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
207759066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
207859066796SMatthias Ringwald }
207942134bc6SMatthias Ringwald #endif
208059066796SMatthias Ringwald 
20813deb3ec6SMatthias Ringwald // distributed key generation
2082d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20833deb3ec6SMatthias Ringwald     switch (dkg_state){
20843deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20853deb3ec6SMatthias Ringwald             // already busy?
20863deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2087d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20883deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2089d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2090d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2091d1a1f6a4SMatthias 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);
2092d7f1c72eSMatthias Ringwald                 return true;
20933deb3ec6SMatthias Ringwald             }
20943deb3ec6SMatthias Ringwald             break;
20953deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20963deb3ec6SMatthias Ringwald             // already busy?
20973deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2098d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20993deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2100d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2101d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2102d1a1f6a4SMatthias 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);
2103d7f1c72eSMatthias Ringwald                 return true;
21043deb3ec6SMatthias Ringwald             }
21053deb3ec6SMatthias Ringwald             break;
21063deb3ec6SMatthias Ringwald         default:
21073deb3ec6SMatthias Ringwald             break;
21083deb3ec6SMatthias Ringwald     }
2109d7f1c72eSMatthias Ringwald     return false;
2110d7f1c72eSMatthias Ringwald }
21113deb3ec6SMatthias Ringwald 
21123deb3ec6SMatthias Ringwald // random address updates
2113d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21143deb3ec6SMatthias Ringwald     switch (rau_state){
2115fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2116fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21175b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2118d7f1c72eSMatthias Ringwald             return true;
21193deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21203deb3ec6SMatthias Ringwald             // already busy?
21213deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2122d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2123d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2124d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2125d7f1c72eSMatthias Ringwald                 return true;
21263deb3ec6SMatthias Ringwald             }
21273deb3ec6SMatthias Ringwald             break;
21283deb3ec6SMatthias Ringwald         default:
21293deb3ec6SMatthias Ringwald             break;
21303deb3ec6SMatthias Ringwald     }
2131d7f1c72eSMatthias Ringwald     return false;
2132d7f1c72eSMatthias Ringwald }
21333deb3ec6SMatthias Ringwald 
21343deb3ec6SMatthias Ringwald // CSRK Lookup
2135d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2136d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2137d7f1c72eSMatthias Ringwald 
21383deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21393deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21403deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2141665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2142665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21433deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21443deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21453deb3ec6SMatthias Ringwald                 // and start lookup
21463deb3ec6SMatthias 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);
21473deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21483deb3ec6SMatthias Ringwald                 break;
21493deb3ec6SMatthias Ringwald             }
21503deb3ec6SMatthias Ringwald         }
21513deb3ec6SMatthias Ringwald     }
21523deb3ec6SMatthias Ringwald 
21533deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21543deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2155665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21563deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2157665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21583deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21593deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21603deb3ec6SMatthias Ringwald         }
21613deb3ec6SMatthias Ringwald     }
21623deb3ec6SMatthias Ringwald 
21633deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21643deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2165092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2166092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2167adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21683deb3ec6SMatthias Ringwald             bd_addr_t addr;
21693deb3ec6SMatthias Ringwald             sm_key_t irk;
21703deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21713deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21723deb3ec6SMatthias Ringwald 
2173adf5eaa9SMatthias Ringwald             // skip unused entries
2174adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2175adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2176adf5eaa9SMatthias Ringwald                 continue;
2177adf5eaa9SMatthias Ringwald             }
2178adf5eaa9SMatthias Ringwald 
21795df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21803deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2181a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21823deb3ec6SMatthias Ringwald                 break;
21833deb3ec6SMatthias Ringwald             }
21843deb3ec6SMatthias Ringwald 
2185a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2186a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21873deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21883deb3ec6SMatthias Ringwald                 continue;
21893deb3ec6SMatthias Ringwald             }
21903deb3ec6SMatthias Ringwald 
21913deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21923deb3ec6SMatthias Ringwald 
21933deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21948314c363SMatthias Ringwald             log_info_key("IRK", irk);
21953deb3ec6SMatthias Ringwald 
21966535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2197d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21983deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2199d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2200d1a1f6a4SMatthias 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);
2201d7f1c72eSMatthias Ringwald             return true;
22023deb3ec6SMatthias Ringwald         }
22033deb3ec6SMatthias Ringwald 
2204092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22053deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22063deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22073deb3ec6SMatthias Ringwald         }
22083deb3ec6SMatthias Ringwald     }
2209d7f1c72eSMatthias Ringwald     return false;
2210d7f1c72eSMatthias Ringwald }
22113deb3ec6SMatthias Ringwald 
2212d7f1c72eSMatthias Ringwald // SC OOB
2213d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2214c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2215c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2216c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2217c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2218c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2219c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2220d7f1c72eSMatthias Ringwald             return true;
2221c59d0c92SMatthias Ringwald         default:
2222c59d0c92SMatthias Ringwald             break;
2223c59d0c92SMatthias Ringwald     }
2224c59d0c92SMatthias Ringwald #endif
2225d7f1c72eSMatthias Ringwald     return false;
2226d7f1c72eSMatthias Ringwald }
2227275aafe8SMatthias Ringwald 
2228687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2229687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2230687a03c8SMatthias Ringwald }
2231687a03c8SMatthias Ringwald 
223241d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2233d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2234d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
223541d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2236e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
223741d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
223841d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
223941d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2240f4935286SMatthias Ringwald 
2241f4935286SMatthias Ringwald             // general
2242f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2243f4935286SMatthias Ringwald                 uint8_t buffer[2];
2244f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2245f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2246f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2247687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2248f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2249f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2250f4935286SMatthias Ringwald                 break;
2251f4935286SMatthias Ringwald             }
2252f4935286SMatthias Ringwald 
225341d32297SMatthias Ringwald             // responder side
225441d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
225541d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
225641d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2257d7f1c72eSMatthias Ringwald                 return true;
22584b8b5afeSMatthias Ringwald 
22594b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22604b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22614b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22624b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2263e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22644b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22654b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2266d7f1c72eSMatthias Ringwald                         return true;
22674b8b5afeSMatthias Ringwald                     default:
22684b8b5afeSMatthias Ringwald                         break;
22694b8b5afeSMatthias Ringwald                 }
22704b8b5afeSMatthias Ringwald                 break;
22714b8b5afeSMatthias Ringwald #endif
227241d32297SMatthias Ringwald             default:
227341d32297SMatthias Ringwald                 break;
227441d32297SMatthias Ringwald         }
227541d32297SMatthias Ringwald     }
2276d7f1c72eSMatthias Ringwald     return false;
2277d7f1c72eSMatthias Ringwald }
22783deb3ec6SMatthias Ringwald 
2279d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22803deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2281d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22823deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22837149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2284665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22853deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22863deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22871979f09cSMatthias Ringwald         bool done = true;
22883deb3ec6SMatthias Ringwald         int err;
228942134bc6SMatthias Ringwald         UNUSED(err);
229034b6528fSMatthias Ringwald 
229134b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
229234b6528fSMatthias Ringwald         // assert ec key is ready
2293505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2294178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2295178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
229634b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
229734b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
229834b6528fSMatthias Ringwald             }
229934b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
230034b6528fSMatthias Ringwald                 continue;
230134b6528fSMatthias Ringwald             }
230234b6528fSMatthias Ringwald         }
230334b6528fSMatthias Ringwald #endif
230434b6528fSMatthias Ringwald 
23053deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
230642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23073deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23083deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
230942134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2310549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
231106cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
231287014f74SMatthias Ringwald #endif
231387014f74SMatthias Ringwald #endif
231434c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23155567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
231634c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2317549ad5d2SMatthias Ringwald #endif
2318c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2319c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2320c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2321c18be159SMatthias Ringwald #endif
232287014f74SMatthias Ringwald 				// just lock context
232387014f74SMatthias Ringwald 				break;
23243deb3ec6SMatthias Ringwald             default:
23251979f09cSMatthias Ringwald                 done = false;
23263deb3ec6SMatthias Ringwald                 break;
23273deb3ec6SMatthias Ringwald         }
23283deb3ec6SMatthias Ringwald         if (done){
23297149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23307149bde5SMatthias 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);
23313deb3ec6SMatthias Ringwald         }
23323deb3ec6SMatthias Ringwald     }
2333d7f1c72eSMatthias Ringwald }
2334d7f1c72eSMatthias Ringwald 
2335403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2336403280b9SMatthias Ringwald     int i;
2337403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2338403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2339403280b9SMatthias Ringwald     uint8_t action = 0;
2340403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2341403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2342403280b9SMatthias Ringwald             bool clear_flag = true;
2343403280b9SMatthias Ringwald             switch (i){
2344403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2345403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2346403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2347403280b9SMatthias Ringwald                 default:
2348403280b9SMatthias Ringwald                     break;
2349403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2350403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2351403280b9SMatthias Ringwald                     num_actions--;
2352403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2353403280b9SMatthias Ringwald                     break;
2354403280b9SMatthias Ringwald             }
2355403280b9SMatthias Ringwald             if (clear_flag){
2356403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2357403280b9SMatthias Ringwald             }
2358403280b9SMatthias Ringwald             action = i;
2359403280b9SMatthias Ringwald             break;
2360403280b9SMatthias Ringwald         }
2361403280b9SMatthias Ringwald     }
2362403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2363403280b9SMatthias Ringwald 
2364403280b9SMatthias Ringwald     // send keypress notification
2365403280b9SMatthias Ringwald     uint8_t buffer[2];
2366403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2367403280b9SMatthias Ringwald     buffer[1] = action;
2368687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2369403280b9SMatthias Ringwald 
2370403280b9SMatthias Ringwald     // try
2371403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2372403280b9SMatthias Ringwald }
2373403280b9SMatthias Ringwald 
2374403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2375403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2376403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2377403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2378403280b9SMatthias Ringwald         uint8_t buffer[17];
2379403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2380403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2381687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2382403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2383403280b9SMatthias Ringwald         return;
2384403280b9SMatthias Ringwald     }
2385403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2386403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2387403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2388403280b9SMatthias Ringwald         uint8_t buffer[11];
2389403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2390403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2391403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2392687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2393403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2394403280b9SMatthias Ringwald         return;
2395403280b9SMatthias Ringwald     }
2396403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2397403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2398403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2399403280b9SMatthias Ringwald         uint8_t buffer[17];
2400403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2401403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2402687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2403403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2404403280b9SMatthias Ringwald         return;
2405403280b9SMatthias Ringwald     }
2406403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2407403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2408403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2409403280b9SMatthias Ringwald         bd_addr_t local_address;
2410403280b9SMatthias Ringwald         uint8_t buffer[8];
2411403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2412403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2413403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2414403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2415403280b9SMatthias Ringwald                 // public or static random
2416403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2417403280b9SMatthias Ringwald                 break;
2418403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2419403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2420403280b9SMatthias Ringwald                 // fallback to public
2421403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2422403280b9SMatthias Ringwald                 buffer[1] = 0;
2423403280b9SMatthias Ringwald                 break;
2424403280b9SMatthias Ringwald             default:
2425403280b9SMatthias Ringwald                 btstack_assert(false);
2426403280b9SMatthias Ringwald                 break;
2427403280b9SMatthias Ringwald         }
2428403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2429687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2430403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2431403280b9SMatthias Ringwald         return;
2432403280b9SMatthias Ringwald     }
2433403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2434403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2435403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2436403280b9SMatthias Ringwald 
2437403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2438403280b9SMatthias Ringwald         // hack to reproduce test runs
2439403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2440403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2441403280b9SMatthias Ringwald                     }
2442403280b9SMatthias Ringwald 
2443403280b9SMatthias Ringwald                     // store local CSRK
2444403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2445403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2446403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2447403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2448403280b9SMatthias Ringwald                     }
2449403280b9SMatthias Ringwald #endif
2450403280b9SMatthias Ringwald 
2451403280b9SMatthias Ringwald         uint8_t buffer[17];
2452403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2453403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2454687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2455403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2456403280b9SMatthias Ringwald         return;
2457403280b9SMatthias Ringwald     }
2458403280b9SMatthias Ringwald     btstack_assert(false);
2459403280b9SMatthias Ringwald }
2460403280b9SMatthias Ringwald 
2461bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2462bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2463bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2464bbd73538SMatthias Ringwald     // - use secure connections
2465bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2466bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2467bbd73538SMatthias 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;
2468bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2469bbd73538SMatthias Ringwald     // - need identity address / public addr
2470bbd73538SMatthias 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);
2471bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2472bbd73538SMatthias 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)
2473bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2474bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2475bbd73538SMatthias 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.
2476bbd73538SMatthias Ringwald     uint8_t link_key[16];
2477bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2478bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
24797040ba26SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type);
2480bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2481bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2482bbd73538SMatthias Ringwald         return false;
2483bbd73538SMatthias Ringwald     }
2484bbd73538SMatthias Ringwald     // get started (all of the above are true)
2485bbd73538SMatthias Ringwald     return true;
2486bbd73538SMatthias Ringwald #else
2487bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2488bbd73538SMatthias Ringwald 	return false;
2489bbd73538SMatthias Ringwald #endif
2490bbd73538SMatthias Ringwald }
2491bbd73538SMatthias Ringwald 
24926f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24936f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24946f7422f1SMatthias 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;
24956f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24966f7422f1SMatthias Ringwald     } else {
24976f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24986f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24996f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
25006f7422f1SMatthias Ringwald     }
25016f7422f1SMatthias Ringwald }
25026f7422f1SMatthias Ringwald 
2503af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2504af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2505af7ef9d1SMatthias 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;
2506af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2507af7ef9d1SMatthias Ringwald     } else {
2508af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2509af7ef9d1SMatthias Ringwald     }
2510af7ef9d1SMatthias Ringwald }
2511af7ef9d1SMatthias Ringwald 
2512d7f1c72eSMatthias Ringwald static void sm_run(void){
2513d7f1c72eSMatthias Ringwald 
2514d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2515d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2516d7f1c72eSMatthias Ringwald 
2517d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2518d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2519d7f1c72eSMatthias Ringwald 
2520d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2521d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2522d7f1c72eSMatthias Ringwald 
2523d7f1c72eSMatthias Ringwald     bool done;
2524d7f1c72eSMatthias Ringwald 
2525d7f1c72eSMatthias Ringwald     //
2526d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2527d7f1c72eSMatthias Ringwald     //
2528d7f1c72eSMatthias Ringwald 
2529d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2530d7f1c72eSMatthias Ringwald     if (done) return;
2531d7f1c72eSMatthias Ringwald 
2532d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2533d7f1c72eSMatthias Ringwald     if (done) return;
2534d7f1c72eSMatthias Ringwald 
2535d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2536d7f1c72eSMatthias Ringwald     if (done) return;
2537d7f1c72eSMatthias Ringwald 
2538d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2539d7f1c72eSMatthias Ringwald     if (done) return;
2540d7f1c72eSMatthias Ringwald 
2541d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2542d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2543d7f1c72eSMatthias Ringwald 
2544d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2545d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2546d7f1c72eSMatthias Ringwald     if (done) return;
2547d7f1c72eSMatthias Ringwald 
2548d7f1c72eSMatthias Ringwald     //
2549d7f1c72eSMatthias Ringwald     // active connection handling
2550d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2551d7f1c72eSMatthias Ringwald 
2552d7f1c72eSMatthias Ringwald     while (true) {
2553d7f1c72eSMatthias Ringwald 
2554d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2555d7f1c72eSMatthias Ringwald 
2556d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25573deb3ec6SMatthias Ringwald 
25583deb3ec6SMatthias Ringwald         //
25593deb3ec6SMatthias Ringwald         // active connection handling
25603deb3ec6SMatthias Ringwald         //
25613deb3ec6SMatthias Ringwald 
25623cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25633cf37b8cSMatthias Ringwald         if (!connection) {
25643cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25653cf37b8cSMatthias Ringwald             return;
25663cf37b8cSMatthias Ringwald         }
25673cf37b8cSMatthias Ringwald 
25683deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25697149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25707149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25717149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2572b170b20fSMatthias Ringwald             return;
2573b170b20fSMatthias Ringwald         }
25743deb3ec6SMatthias Ringwald 
25753d7fe1e9SMatthias Ringwald         // send keypress notifications
2576dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2577403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2578d7471931SMatthias Ringwald             return;
25793d7fe1e9SMatthias Ringwald         }
25803d7fe1e9SMatthias Ringwald 
25813deb3ec6SMatthias Ringwald         int key_distribution_flags;
258242134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2583b6afa23eSMatthias Ringwald 		int err;
2584b6afa23eSMatthias Ringwald 		UNUSED(err);
25859b75de03SMatthias Ringwald         bool have_ltk;
25869b75de03SMatthias Ringwald         uint8_t ltk[16];
25873deb3ec6SMatthias Ringwald 
25883deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2589dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2590dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2591dd4a08fbSMatthias Ringwald         }
25923deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25933deb3ec6SMatthias Ringwald 
2594f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2595aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2596aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2597aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2598aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2599aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2600aec94140SMatthias Ringwald                 break;
2601688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2602688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2603688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2604688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2605688a08f9SMatthias Ringwald                 break;
2606dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2607dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2608dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2609dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2610dc300847SMatthias Ringwald                 break;
2611019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2612b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2613019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26140346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26150346c37cSMatthias Ringwald                 break;
26160346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2617b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26180346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26190346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26200346c37cSMatthias Ringwald                 break;
26210346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2622b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26230346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26240346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26250346c37cSMatthias Ringwald                 break;
26260346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2627b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26280346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26290346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2630019005a0SMatthias Ringwald                 break;
2631bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2632b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2633bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2634b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2635bd57ffebSMatthias Ringwald                 break;
2636e0a03c85SMatthias Ringwald #endif
2637e0a03c85SMatthias Ringwald 
263842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26393deb3ec6SMatthias Ringwald             // initiator side
2640f32b7a88SMatthias Ringwald 
26415567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2642f32b7a88SMatthias Ringwald 				sm_reset_setup();
2643f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2644daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2645f32b7a88SMatthias Ringwald 
26463deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26479c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26485567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26493deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2650c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2651c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26523deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26533deb3ec6SMatthias Ringwald                 return;
26543deb3ec6SMatthias Ringwald             }
26553deb3ec6SMatthias Ringwald 
2656b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2657b26f445fSMatthias Ringwald 				sm_reset_setup();
2658b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2659b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2660d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2661b26f445fSMatthias Ringwald 
26621ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26633deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2664687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26653deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26663deb3ec6SMatthias Ringwald                 break;
266742134bc6SMatthias Ringwald #endif
26683deb3ec6SMatthias Ringwald 
266927c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
267041d32297SMatthias Ringwald 
2671c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26721979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26731979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
267427c32905SMatthias Ringwald                 uint8_t buffer[65];
267527c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
267627c32905SMatthias Ringwald                 //
2677fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2678fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2679e53be891SMatthias Ringwald 
2680349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2681349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2682349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2683349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2684349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2685349d0adbSMatthias Ringwald                 }
2686349d0adbSMatthias Ringwald #endif
2687349d0adbSMatthias Ringwald 
268845a61d50SMatthias Ringwald                 // stk generation method
268945a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
269045a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
269145a61d50SMatthias Ringwald                     case JUST_WORKS:
269247fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
269342134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269407036a04SMatthias Ringwald                             // responder
26951979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2696b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
269727c32905SMatthias Ringwald                         } else {
269807036a04SMatthias Ringwald                             // initiator
2699c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
270027c32905SMatthias Ringwald                         }
270145a61d50SMatthias Ringwald                         break;
270245a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
270345a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
270447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
270507036a04SMatthias Ringwald                         // use random TK for display
27066535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27076535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
270845a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
270907036a04SMatthias Ringwald 
271042134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
271145a61d50SMatthias Ringwald                             // responder
2712c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
271345a61d50SMatthias Ringwald                         } else {
271445a61d50SMatthias Ringwald                             // initiator
2715c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271645a61d50SMatthias Ringwald                         }
27171979f09cSMatthias Ringwald                         trigger_user_response = true;
271845a61d50SMatthias Ringwald                         break;
271945a61d50SMatthias Ringwald                     case OOB:
272065a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
272165a9a04eSMatthias Ringwald                             // responder
272265a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
272365a9a04eSMatthias Ringwald                         } else {
272465a9a04eSMatthias Ringwald                             // initiator
272565a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272665a9a04eSMatthias Ringwald                         }
272745a61d50SMatthias Ringwald                         break;
27287bbeb3adSMilanka Ringwald                     default:
27297bbeb3adSMilanka Ringwald                         btstack_assert(false);
27307bbeb3adSMilanka Ringwald                         break;
273145a61d50SMatthias Ringwald                 }
273245a61d50SMatthias Ringwald 
2733687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
273427c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2735644c6a1dSMatthias Ringwald 
2736b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2737644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2738644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2739644c6a1dSMatthias Ringwald                 }
2740b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2741b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2742b90c4e75SMatthias Ringwald                 }
274327c32905SMatthias Ringwald                 break;
274427c32905SMatthias Ringwald             }
2745c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2746e53be891SMatthias Ringwald                 uint8_t buffer[17];
2747e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27489af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
274942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2750c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2751e53be891SMatthias Ringwald                 } else {
2752c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2753e53be891SMatthias Ringwald                 }
2754687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2755e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2756e53be891SMatthias Ringwald                 break;
2757e53be891SMatthias Ringwald             }
2758c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2759e53be891SMatthias Ringwald                 uint8_t buffer[17];
2760e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2761e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27629d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27634ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
276440c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
276542134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
276645a61d50SMatthias Ringwald                         // responder
2767c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
276845a61d50SMatthias Ringwald                     } else {
276945a61d50SMatthias Ringwald                         // initiator
2770c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
277145a61d50SMatthias Ringwald                     }
277245a61d50SMatthias Ringwald                 } else {
277340c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
277442134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2775e53be891SMatthias Ringwald                         // responder
277647fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
277740c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2778901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27792886623dSMatthias Ringwald                         } else {
278040c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27812886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2782446a8c36SMatthias Ringwald                         }
2783e53be891SMatthias Ringwald                     } else {
2784136d331aSMatthias Ringwald                         // initiator
2785c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2786e53be891SMatthias Ringwald                     }
278745a61d50SMatthias Ringwald                 }
2788687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2789e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2790e53be891SMatthias Ringwald                 break;
2791e53be891SMatthias Ringwald             }
2792c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2793e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2794e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2795e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2796dc300847SMatthias Ringwald 
279742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2798c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2799e53be891SMatthias Ringwald                 } else {
2800c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2801e53be891SMatthias Ringwald                 }
2802e083ca23SMatthias Ringwald 
2803687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2804e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2805e53be891SMatthias Ringwald                 break;
2806e53be891SMatthias Ringwald             }
2807e53be891SMatthias Ringwald 
2808e53be891SMatthias Ringwald #endif
280942134bc6SMatthias Ringwald 
281042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2811dd12a62bSMatthias Ringwald 
281287014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
281387014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
281487014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2815687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2816c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
281787014f74SMatthias Ringwald 				break;
281887014f74SMatthias Ringwald 			}
281987014f74SMatthias Ringwald 
282038196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
282138196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
282238196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
282338196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
282438196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
282538196718SMatthias Ringwald 						// start using context by loading security info
282638196718SMatthias Ringwald 						sm_reset_setup();
282738196718SMatthias Ringwald 						sm_load_security_info(connection);
282838196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
282938196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
283038196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
283142646f38SMatthias Ringwald                             sm_reencryption_started(connection);
283238196718SMatthias Ringwald                             sm_trigger_run();
283338196718SMatthias Ringwald 							break;
283438196718SMatthias Ringwald 						}
283538196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
283638196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
283738196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
283838196718SMatthias Ringwald 						return;
283938196718SMatthias Ringwald 					default:
284038196718SMatthias Ringwald 						// just wait until IRK lookup is completed
284138196718SMatthias Ringwald 						break;
284238196718SMatthias Ringwald 				}
284338196718SMatthias Ringwald 				break;
284438196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
284538196718SMatthias Ringwald 
2846b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2847b6afa23eSMatthias Ringwald                 sm_reset_setup();
28489b75de03SMatthias Ringwald 
28499b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28509b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28519b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28529b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28539b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28549b75de03SMatthias Ringwald                         if (have_ltk){
28559b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
285619a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28579b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28589b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28599b75de03SMatthias Ringwald                         }
28609b75de03SMatthias Ringwald                         break;
28619b75de03SMatthias Ringwald                     default:
28629b75de03SMatthias Ringwald                         break;
28639b75de03SMatthias Ringwald                 }
28649b75de03SMatthias Ringwald 
2865b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2866d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
286739543d07SMatthias Ringwald 
2868b6afa23eSMatthias Ringwald 				// recover pairing request
2869b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2870b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2871b6afa23eSMatthias Ringwald 
2872b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2873b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2874b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2875b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2876b6afa23eSMatthias Ringwald                     }
2877b6afa23eSMatthias Ringwald #endif
28789305033eSMatthias Ringwald 				if (err != 0){
2879f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2880b6afa23eSMatthias Ringwald 					sm_trigger_run();
2881b6afa23eSMatthias Ringwald 					break;
2882b6afa23eSMatthias Ringwald 				}
2883b6afa23eSMatthias Ringwald 
2884b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2885b6afa23eSMatthias Ringwald 
2886b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2887b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2888b6afa23eSMatthias 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);
2889b6afa23eSMatthias Ringwald 					break;
2890b6afa23eSMatthias Ringwald 				}
2891b6afa23eSMatthias Ringwald 
2892b6afa23eSMatthias Ringwald 				/* fall through */
2893b6afa23eSMatthias Ringwald 
28943deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28951ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2896f55bd529SMatthias Ringwald 
2897f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28983deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28991ad129beSMatthias Ringwald 
2900f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2901f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2902f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2903f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2904f55bd529SMatthias Ringwald                 }
2905f55bd529SMatthias Ringwald #endif
2906f55bd529SMatthias Ringwald                 // setup in response
2907f55bd529SMatthias 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);
2908f55bd529SMatthias 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);
2909f55bd529SMatthias Ringwald 
2910f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29119a90d41aSMatthias 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));
2912f55bd529SMatthias Ringwald 
291327c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2914c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29150b8af2a5SMatthias Ringwald                 } else {
29160b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
291727c32905SMatthias Ringwald                 }
29180b8af2a5SMatthias Ringwald 
2919687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29203deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2921446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2922c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29233deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2924446a8c36SMatthias Ringwald                 }
29253deb3ec6SMatthias Ringwald                 return;
292642134bc6SMatthias Ringwald #endif
29273deb3ec6SMatthias Ringwald 
29283deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29293deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29303deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29319c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
293242134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29333deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29343deb3ec6SMatthias Ringwald                 } else {
29353deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29363deb3ec6SMatthias Ringwald                 }
2937687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29383deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29393deb3ec6SMatthias Ringwald                 break;
29403deb3ec6SMatthias Ringwald             }
29413deb3ec6SMatthias Ringwald 
2942d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29433deb3ec6SMatthias Ringwald                 // already busy?
29443deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2945d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2946d1a1f6a4SMatthias 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);
2947d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2948d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2949f3582630SMatthias 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);
29503deb3ec6SMatthias Ringwald                 break;
29513deb3ec6SMatthias Ringwald 
29523deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29533deb3ec6SMatthias Ringwald                 // already busy?
29543deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29553deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2956d1a1f6a4SMatthias 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);
2957d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2958d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2959f3582630SMatthias 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);
29603deb3ec6SMatthias Ringwald                 break;
2961d1a1f6a4SMatthias Ringwald 
29623deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29633deb3ec6SMatthias Ringwald                 // already busy?
29643deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29653deb3ec6SMatthias Ringwald                 // calculate STK
296642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2967d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29683deb3ec6SMatthias Ringwald                 } else {
2969d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29703deb3ec6SMatthias Ringwald                 }
2971d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2972d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2973f3582630SMatthias 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);
29743deb3ec6SMatthias Ringwald                 break;
2975d1a1f6a4SMatthias Ringwald 
29763deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29773deb3ec6SMatthias Ringwald                 // already busy?
29783deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29793deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29809ad0dd7cSMatthias Ringwald 
29819ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29829ad0dd7cSMatthias Ringwald                 // r' = padding || r
29839ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29849ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29856535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29869ad0dd7cSMatthias Ringwald 
29873deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2988d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2989d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2990f3582630SMatthias 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);
2991d1a1f6a4SMatthias Ringwald                 break;
2992d1a1f6a4SMatthias Ringwald 
29933deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29943deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29953deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29969c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
299742134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29983deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29993deb3ec6SMatthias Ringwald                 } else {
30003deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
30013deb3ec6SMatthias Ringwald                 }
3002687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30033deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30043deb3ec6SMatthias Ringwald                 return;
30053deb3ec6SMatthias Ringwald             }
300642134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30073deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30083deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30099c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30103deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30113deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30123deb3ec6SMatthias Ringwald                 return;
30133deb3ec6SMatthias Ringwald             }
3014d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
3015*b96d60a6SMatthias Ringwald                 // allow to override LTK
3016*b96d60a6SMatthias Ringwald                 if (sm_get_ltk_callback != NULL){
3017*b96d60a6SMatthias Ringwald                     (void)(*sm_get_ltk_callback)(connection->sm_handle, connection->sm_peer_addr_type, connection->sm_peer_address, setup->sm_ltk);
3018*b96d60a6SMatthias Ringwald                 }
30193deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30209c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30215567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30223deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30233deb3ec6SMatthias Ringwald                 return;
30243deb3ec6SMatthias Ringwald             }
3025dd12a62bSMatthias Ringwald 
3026dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30273deb3ec6SMatthias Ringwald                 // already busy?
30283deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30293deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3030c61cfe5aSMatthias Ringwald 
3031dd12a62bSMatthias Ringwald 				sm_reset_setup();
3032dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3033dd12a62bSMatthias Ringwald 
303442646f38SMatthias Ringwald 				sm_reencryption_started(connection);
303542646f38SMatthias Ringwald 
3036c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3037c61cfe5aSMatthias Ringwald                 // r' = padding || r
3038c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3039c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30406535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3041c61cfe5aSMatthias Ringwald 
30423deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3043d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3044d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3045f3582630SMatthias 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);
30463deb3ec6SMatthias Ringwald                 return;
304742134bc6SMatthias Ringwald #endif
304842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
304942134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
305042134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
305142134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
305242134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
305342134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
305442134bc6SMatthias Ringwald                 return;
305542134bc6SMatthias Ringwald             }
305642134bc6SMatthias Ringwald #endif
30573deb3ec6SMatthias Ringwald 
30583deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3059403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3060403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30613deb3ec6SMatthias Ringwald                     return;
30623deb3ec6SMatthias Ringwald                 }
30633deb3ec6SMatthias Ringwald 
30643deb3ec6SMatthias Ringwald                 // keys are sent
306542134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30663deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
306761d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30683deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3069f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3070f5020412SMatthias Ringwald                         // start CTKD right away
3071f5020412SMatthias Ringwald                         continue;
30723deb3ec6SMatthias Ringwald                     } else {
30733deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30743deb3ec6SMatthias Ringwald                     }
30753deb3ec6SMatthias Ringwald                 } else {
30761dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30773deb3ec6SMatthias Ringwald                 }
30783deb3ec6SMatthias Ringwald                 break;
30793deb3ec6SMatthias Ringwald 
3080c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3081c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3082c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3083c18be159SMatthias Ringwald                 sm_reset_setup();
3084c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3085c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3086c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3087c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3088c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3089c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3090c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3091c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3092c18be159SMatthias Ringwald 
3093c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3094c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3095c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3096c18be159SMatthias Ringwald                 // Plus signing key if supported
3097c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3098c18be159SMatthias Ringwald #endif
3099c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3100c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3101c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3102c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3103c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3104c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3105c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3106c18be159SMatthias Ringwald 
3107c18be159SMatthias Ringwald                 // set state and send pairing response
3108c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3109c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3110c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3111c18be159SMatthias Ringwald                 break;
3112c18be159SMatthias Ringwald 
3113c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3114c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3115c18be159SMatthias Ringwald                 sm_reset_setup();
3116c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3117c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3118c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3119c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3120c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3121c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3122c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3123c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3124c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3125c18be159SMatthias Ringwald 
3126c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3127c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3128c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3129c18be159SMatthias Ringwald                 // Plus signing key if supported
3130c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3131c18be159SMatthias Ringwald #endif
3132c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3133c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3134c18be159SMatthias Ringwald 
3135c18be159SMatthias 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:
3136c18be159SMatthias Ringwald                 // - the IO Capability field,
3137c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3138c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3139c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3140c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3141c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3142c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3143c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3144c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3145c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3146c18be159SMatthias Ringwald 
3147c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3148c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3149c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3150c18be159SMatthias Ringwald 
3151c18be159SMatthias Ringwald                 // set state and send pairing response
3152c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3153c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3154c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3155c18be159SMatthias Ringwald                 break;
3156c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3157c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3158c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3159c18be159SMatthias Ringwald                     return;
3160c18be159SMatthias Ringwald                 }
3161c18be159SMatthias Ringwald                 // keys are sent
3162c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3163c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
316461d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3165c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3166c18be159SMatthias Ringwald                         break;
3167c18be159SMatthias Ringwald                     }
3168c18be159SMatthias Ringwald                 }
3169c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3170c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3171c18be159SMatthias Ringwald                 continue;
3172c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3173c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3174c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3175c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3176c18be159SMatthias Ringwald                 break;
3177c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3178c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3179c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3180c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3181c18be159SMatthias Ringwald                 break;
3182c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3183c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3184c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3185c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3186c18be159SMatthias Ringwald                 break;
3187c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3188c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3189c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3190c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3191c18be159SMatthias Ringwald                 break;
3192c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3193c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3194c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3195c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3196c18be159SMatthias Ringwald                 break;
3197c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3198c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3199c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3200c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3201c18be159SMatthias Ringwald                 break;
3202c18be159SMatthias Ringwald #endif
3203c18be159SMatthias Ringwald 
32043deb3ec6SMatthias Ringwald             default:
32053deb3ec6SMatthias Ringwald                 break;
32063deb3ec6SMatthias Ringwald         }
32073deb3ec6SMatthias Ringwald 
32083deb3ec6SMatthias Ringwald         // check again if active connection was released
32097149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32103deb3ec6SMatthias Ringwald     }
32113deb3ec6SMatthias Ringwald }
32123deb3ec6SMatthias Ringwald 
3213d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3214d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3215f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
321604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
321704678764SMatthias Ringwald 
3218f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3219f3582630SMatthias Ringwald     if (connection == NULL) return;
3220f3582630SMatthias Ringwald 
3221d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
322204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3223f3582630SMatthias 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);
3224d1a1f6a4SMatthias Ringwald }
32253deb3ec6SMatthias Ringwald 
3226d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3227f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322904678764SMatthias Ringwald 
3230f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3231f3582630SMatthias Ringwald     if (connection == NULL) return;
3232f3582630SMatthias Ringwald 
32338314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32343deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
323570b44dd4SMatthias Ringwald     sm_trigger_run();
3236d1a1f6a4SMatthias Ringwald }
3237d1a1f6a4SMatthias Ringwald 
3238d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3239d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3240f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324204678764SMatthias Ringwald 
3243f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3244f3582630SMatthias Ringwald     if (connection == NULL) return;
3245f3582630SMatthias Ringwald 
3246d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
324704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3248f3582630SMatthias 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);
3249d1a1f6a4SMatthias Ringwald }
3250d1a1f6a4SMatthias Ringwald 
3251d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3252f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
325304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
325404678764SMatthias Ringwald 
3255f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3256f3582630SMatthias Ringwald     if (connection == NULL) return;
3257f3582630SMatthias Ringwald 
3258d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3259d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3260f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
326170b44dd4SMatthias Ringwald         sm_trigger_run();
32623deb3ec6SMatthias Ringwald         return;
32633deb3ec6SMatthias Ringwald     }
326442134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32653deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
326670b44dd4SMatthias Ringwald         sm_trigger_run();
32673deb3ec6SMatthias Ringwald     } else {
3268d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3269d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3270f3582630SMatthias 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);
32713deb3ec6SMatthias Ringwald     }
32723deb3ec6SMatthias Ringwald }
3273d1a1f6a4SMatthias Ringwald 
3274d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
327504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3276f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327704678764SMatthias Ringwald 
3278f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3279f3582630SMatthias Ringwald     if (connection == NULL) return;
3280f3582630SMatthias Ringwald 
32813deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32828314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
328342134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32843deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
32853deb3ec6SMatthias Ringwald     } else {
32863deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
32873deb3ec6SMatthias Ringwald     }
328870b44dd4SMatthias Ringwald     sm_trigger_run();
3289d1a1f6a4SMatthias Ringwald }
3290d1a1f6a4SMatthias Ringwald 
3291d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3292d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3293f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
329404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
329504678764SMatthias Ringwald 
3296f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3297f3582630SMatthias Ringwald     if (connection == NULL) return;
3298f3582630SMatthias Ringwald 
3299d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33003deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33013deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
33023deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
33033deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33043deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33053deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3306d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
330704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3308f3582630SMatthias 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);
33093deb3ec6SMatthias Ringwald }
3310d1a1f6a4SMatthias Ringwald 
33112a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3312d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3313d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
331404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3315f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
331604678764SMatthias Ringwald 
3317f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3318f3582630SMatthias Ringwald     if (connection == NULL) return;
3319f3582630SMatthias Ringwald 
3320d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33213deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33223deb3ec6SMatthias Ringwald 
33233deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33243deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33253deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33263deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33273deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3328d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
332904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3330f3582630SMatthias 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);
33313deb3ec6SMatthias Ringwald }
33322a526f21SMatthias Ringwald #endif
3333d1a1f6a4SMatthias Ringwald 
3334d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3335d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3336f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
333804678764SMatthias Ringwald 
3339f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3340f3582630SMatthias Ringwald     if (connection == NULL) return;
3341f3582630SMatthias Ringwald 
33428314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33433deb3ec6SMatthias Ringwald     // calc CSRK next
3344d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
334504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3346f3582630SMatthias 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);
3347d1a1f6a4SMatthias Ringwald }
3348d1a1f6a4SMatthias Ringwald 
3349d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3350f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
335104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
335204678764SMatthias Ringwald 
3353f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3354f3582630SMatthias Ringwald     if (connection == NULL) return;
3355f3582630SMatthias Ringwald 
3356d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33578314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33583deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33593deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33603deb3ec6SMatthias Ringwald     } else {
33613deb3ec6SMatthias Ringwald         // no keys to send, just continue
336242134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
336361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3364c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3365c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3366c5a72e35SMatthias Ringwald             } else {
33673deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33683deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3369c5a72e35SMatthias Ringwald             }
33703deb3ec6SMatthias Ringwald         } else {
3371af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33723deb3ec6SMatthias Ringwald         }
33732bacf595SMatthias Ringwald     }
337470b44dd4SMatthias Ringwald     sm_trigger_run();
3375d1a1f6a4SMatthias Ringwald }
3376d1a1f6a4SMatthias Ringwald 
337742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3378d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3379f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
338004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
338104678764SMatthias Ringwald 
3382f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3383f3582630SMatthias Ringwald     if (connection == NULL) return;
3384f3582630SMatthias Ringwald 
33853deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33868314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3387d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
338870b44dd4SMatthias Ringwald     sm_trigger_run();
3389d1a1f6a4SMatthias Ringwald }
3390d1a1f6a4SMatthias Ringwald #endif
3391d1a1f6a4SMatthias Ringwald 
3392d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3393d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3394d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
339504678764SMatthias Ringwald 
3396d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3397d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3398d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3399d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3400d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3401a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
340270b44dd4SMatthias Ringwald         sm_trigger_run();
34033deb3ec6SMatthias Ringwald         return;
34043deb3ec6SMatthias Ringwald     }
3405d1a1f6a4SMatthias Ringwald     // no match, try next
3406d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
340770b44dd4SMatthias Ringwald     sm_trigger_run();
34083deb3ec6SMatthias Ringwald }
34093deb3ec6SMatthias Ringwald 
3410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3411d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3412d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341304678764SMatthias Ringwald 
3414d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3415d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
341670b44dd4SMatthias Ringwald     sm_trigger_run();
34177df18c15SMatthias Ringwald }
3418d1a1f6a4SMatthias Ringwald 
3419d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3420d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3421d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342204678764SMatthias Ringwald 
3423d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3424d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
342570b44dd4SMatthias Ringwald     sm_trigger_run();
34267df18c15SMatthias Ringwald }
3427d1a1f6a4SMatthias Ringwald 
3428d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3429d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3430d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
343104678764SMatthias Ringwald 
34326535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3433e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3434e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3435e91ddb40SMatthias Ringwald 
343670b44dd4SMatthias Ringwald     sm_trigger_run();
343751fa0b28SMatthias Ringwald }
34387df18c15SMatthias Ringwald 
3439d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3440d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34413deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34423deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34433deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34443deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34453deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34464ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34474ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34483deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34493deb3ec6SMatthias Ringwald             break;
34503deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34513deb3ec6SMatthias Ringwald         default:
34523deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34534ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
3454e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
34553deb3ec6SMatthias Ringwald             break;
34563deb3ec6SMatthias Ringwald     }
345770b44dd4SMatthias Ringwald     sm_trigger_run();
34583deb3ec6SMatthias Ringwald }
34593deb3ec6SMatthias Ringwald 
3460c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34616ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3462f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3463f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3464f3582630SMatthias Ringwald     if (connection == NULL) return;
3465c59d0c92SMatthias Ringwald 
346665a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
346770b44dd4SMatthias Ringwald     sm_trigger_run();
346865a9a04eSMatthias Ringwald }
3469d1a1f6a4SMatthias Ringwald 
34706ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34716ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34726ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34736ca80073SMatthias Ringwald     if (connection == NULL) return;
34746ca80073SMatthias Ringwald 
3475b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
347670b44dd4SMatthias Ringwald     sm_trigger_run();
3477d1a1f6a4SMatthias Ringwald }
3478f1c1783eSMatthias Ringwald #endif
3479f1c1783eSMatthias Ringwald 
3480d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3481f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3482f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3483f3582630SMatthias Ringwald     if (connection == NULL) return;
3484f3582630SMatthias Ringwald 
3485d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
348670b44dd4SMatthias Ringwald     sm_trigger_run();
3487d1a1f6a4SMatthias Ringwald }
3488d1a1f6a4SMatthias Ringwald 
3489d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3490f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3491f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3492f3582630SMatthias Ringwald     if (connection == NULL) return;
3493f3582630SMatthias Ringwald 
3494caf15bf3SMatthias Ringwald     sm_reset_tk();
3495caf15bf3SMatthias Ringwald     uint32_t tk;
34965ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
34973deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3498d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
34993deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
35004ea43905SMatthias Ringwald         if (tk >= 999999u){
35014ea43905SMatthias Ringwald             tk = tk - 999999u;
35023deb3ec6SMatthias Ringwald         }
3503caf15bf3SMatthias Ringwald     } else {
3504caf15bf3SMatthias Ringwald         // override with pre-defined passkey
35054b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3506caf15bf3SMatthias Ringwald     }
3507f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
350842134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35093deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35103deb3ec6SMatthias Ringwald     } else {
3511b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3512b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3513b41539d5SMatthias Ringwald         } else {
35143deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35153deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35163deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35173deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3518f3582630SMatthias 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);
35193deb3ec6SMatthias Ringwald             }
35203deb3ec6SMatthias Ringwald         }
3521b41539d5SMatthias Ringwald     }
352270b44dd4SMatthias Ringwald     sm_trigger_run();
35233deb3ec6SMatthias Ringwald }
3524d1a1f6a4SMatthias Ringwald 
3525d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3526f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3527f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3528f3582630SMatthias Ringwald     if (connection == NULL) return;
3529f3582630SMatthias Ringwald 
3530d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3531d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3532d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3533d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
353470b44dd4SMatthias Ringwald     sm_trigger_run();
3535d1a1f6a4SMatthias Ringwald }
3536d1a1f6a4SMatthias Ringwald 
3537d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3538f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3539f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3540f3582630SMatthias Ringwald     if (connection == NULL) return;
3541f3582630SMatthias Ringwald 
3542d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35433deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35444ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35453deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35464ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35478b3ffec5SMatthias 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);
35483deb3ec6SMatthias Ringwald }
3549899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3550899e6e02SMatthias Ringwald     // warn about default ER/IR
35511979f09cSMatthias Ringwald     bool warning = false;
3552899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35531979f09cSMatthias Ringwald         warning = true;
3554899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3555899e6e02SMatthias Ringwald     }
3556899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35571979f09cSMatthias Ringwald         warning = true;
3558899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3559899e6e02SMatthias Ringwald     }
356021045273SMatthias Ringwald     if (warning) {
3561899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3562899e6e02SMatthias Ringwald     }
356321045273SMatthias Ringwald }
3564899e6e02SMatthias Ringwald 
3565899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35661979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35679305033eSMatthias Ringwald     if (arg != NULL){
3568899e6e02SMatthias Ringwald         // key generated, store in tlv
35694ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3570899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3571e0d13a19SMilanka Ringwald         UNUSED(status);
3572899e6e02SMatthias Ringwald     }
3573899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35748d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3575841468bbSMatthias Ringwald 
3576841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3577841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3578841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3579841468bbSMatthias Ringwald     }
3580841468bbSMatthias Ringwald 
358170b44dd4SMatthias Ringwald     sm_trigger_run();
3582899e6e02SMatthias Ringwald }
3583899e6e02SMatthias Ringwald 
3584899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
35851979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35869305033eSMatthias Ringwald     if (arg != 0){
3587899e6e02SMatthias Ringwald         // key generated, store in tlv
35884ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3589899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3590e0d13a19SMilanka Ringwald         UNUSED(status);
3591899e6e02SMatthias Ringwald     }
3592899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3593899e6e02SMatthias Ringwald 
3594899e6e02SMatthias Ringwald     // try load ir
35954ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3596899e6e02SMatthias Ringwald     if (key_size == 16){
3597899e6e02SMatthias Ringwald         // ok, let's continue
3598899e6e02SMatthias Ringwald         log_info("IR from TLV");
3599899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3600899e6e02SMatthias Ringwald     } else {
3601899e6e02SMatthias Ringwald         // invalid, generate new random one
36021979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3603899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3604899e6e02SMatthias Ringwald     }
3605899e6e02SMatthias Ringwald }
36063deb3ec6SMatthias Ringwald 
3607f664b5e8SMatthias 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){
3608f664b5e8SMatthias Ringwald 
3609f664b5e8SMatthias Ringwald     // connection info
3610f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3611f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3612f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3613f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3614f664b5e8SMatthias Ringwald 
3615f664b5e8SMatthias Ringwald     // security properties
3616f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3617f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3618f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3619f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3620f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3621f664b5e8SMatthias Ringwald 
3622f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3623f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3624f664b5e8SMatthias Ringwald 
3625f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3626f664b5e8SMatthias Ringwald }
3627f664b5e8SMatthias Ringwald 
3628d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36293deb3ec6SMatthias Ringwald 
3630cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3631cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36329ec2630cSMatthias Ringwald 
36333deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3634711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3635fbe050beSMatthias Ringwald     uint8_t           status;
3636f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3637f664b5e8SMatthias Ringwald 
36383deb3ec6SMatthias Ringwald     switch (packet_type) {
36393deb3ec6SMatthias Ringwald 
36403deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36410e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36423deb3ec6SMatthias Ringwald 
36433deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
36443deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3645be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
36463deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3647899e6e02SMatthias Ringwald 
3648899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3649899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36509305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
36514ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3652899e6e02SMatthias Ringwald                             if (key_size == 16){
3653899e6e02SMatthias Ringwald                                 // ok, let's continue
3654899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3655899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3656899e6e02SMatthias Ringwald                             } else {
3657899e6e02SMatthias Ringwald                                 // invalid, generate random one
36581979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3659899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3660899e6e02SMatthias Ringwald                             }
3661899e6e02SMatthias Ringwald                         } else {
3662899e6e02SMatthias Ringwald                             sm_validate_er_ir();
36638d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3664841468bbSMatthias Ringwald 
3665841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3666841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3667841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3668841468bbSMatthias Ringwald                             }
3669899e6e02SMatthias Ringwald                         }
36701bf086daSMatthias Ringwald 
36711bf086daSMatthias Ringwald                         // restart random address updates after power cycle
36721bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
36733deb3ec6SMatthias Ringwald 					}
36743deb3ec6SMatthias Ringwald 					break;
3675c18be159SMatthias Ringwald 
36762d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
36772d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
36782d095694SMatthias Ringwald 			        // ignore if connection failed
36792d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
36803deb3ec6SMatthias Ringwald 
36812d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
36822d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
36832d095694SMatthias Ringwald 			        if (!sm_conn) break;
36842d095694SMatthias Ringwald 
36852d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
36862d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
36872d095694SMatthias Ringwald                                        con_handle,
36882d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3689f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
36902d095694SMatthias Ringwald                                        addr);
36912d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
36922d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
36932d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
36942d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3695c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
36962d095694SMatthias Ringwald 			        break;
36972d095694SMatthias Ringwald #endif
3698c18be159SMatthias Ringwald 
3699c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3700c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3701c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3702c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3703c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3704c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3705c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3706c18be159SMatthias Ringwald 			        break;
3707c18be159SMatthias Ringwald #endif
3708c18be159SMatthias Ringwald 
37093deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37103deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37113deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3712f664b5e8SMatthias Ringwald                             // ignore if connection failed
3713f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37143deb3ec6SMatthias Ringwald 
3715711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3716711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37173deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37183deb3ec6SMatthias Ringwald 
3719f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3720f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3721f664b5e8SMatthias Ringwald                                                con_handle,
3722f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3723f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3724f664b5e8SMatthias Ringwald                                                addr);
3725687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3726f664b5e8SMatthias Ringwald 
3727f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3728b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3729b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3730ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3731ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3732f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3733b892db1cSMatthias Ringwald                             }
3734b892db1cSMatthias Ringwald #endif
3735b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3736b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3737ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3738ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37393deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37403deb3ec6SMatthias Ringwald                             }
3741b892db1cSMatthias Ringwald #endif
37423deb3ec6SMatthias Ringwald                             break;
37433deb3ec6SMatthias Ringwald 
37443deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3745711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3746711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37473deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37483deb3ec6SMatthias Ringwald 
37493deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37503deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37513deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37523deb3ec6SMatthias Ringwald                                 break;
37533deb3ec6SMatthias Ringwald                             }
3754c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3755778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3756778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3757e53be891SMatthias Ringwald                                 break;
3758e53be891SMatthias Ringwald                             }
37593deb3ec6SMatthias Ringwald 
37603deb3ec6SMatthias Ringwald                             // store rand and ediv
37619c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3762f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3763549ad5d2SMatthias Ringwald 
3764549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3765549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37664ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37676c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
376806cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3769549ad5d2SMatthias Ringwald                                     break;
3770549ad5d2SMatthias Ringwald                                 }
37716c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37726c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37736c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37746c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37756c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
37766c39055aSMatthias Ringwald                                         break;
37776c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
37786c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
37796c39055aSMatthias Ringwald                                         break;
37806c39055aSMatthias Ringwald                                     default:
37816c39055aSMatthias Ringwald                                         // wait for irk look doen
37826c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
37836c39055aSMatthias Ringwald                                         break;
37846c39055aSMatthias Ringwald                                 }
37856c39055aSMatthias Ringwald                                 break;
37866c39055aSMatthias Ringwald                             }
3787549ad5d2SMatthias Ringwald 
3788549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
378906cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3790549ad5d2SMatthias Ringwald #else
3791549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3792549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3793549ad5d2SMatthias Ringwald #endif
37943deb3ec6SMatthias Ringwald                             break;
3795804d3e67SMatthias Ringwald 
37963deb3ec6SMatthias Ringwald                         default:
37973deb3ec6SMatthias Ringwald                             break;
37983deb3ec6SMatthias Ringwald                     }
37993deb3ec6SMatthias Ringwald                     break;
38003deb3ec6SMatthias Ringwald 
38013deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
38023b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3803711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38043deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38053deb3ec6SMatthias Ringwald 
38063b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38073deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38083deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38093deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
381003a9359aSMatthias Ringwald 
3811fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3812fbe050beSMatthias Ringwald 
38135567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
381403a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3815fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3816fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38178d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38188d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38198d4eef95SMatthias Ringwald                                 } else {
382003a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38218d4eef95SMatthias Ringwald                                 }
3822fbe050beSMatthias Ringwald                             } else {
3823e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3824cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38253b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3826cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38273b7fd749SMatthias Ringwald                             }
3828fbe050beSMatthias Ringwald 
3829fbe050beSMatthias Ringwald                             // emit re-encryption complete
383073102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3831fbe050beSMatthias Ringwald 
3832c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3833c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3834c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38350ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
383603a9359aSMatthias Ringwald                             }
383703a9359aSMatthias Ringwald 
38383deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38393deb3ec6SMatthias Ringwald                             break;
3840fbe050beSMatthias Ringwald 
38413deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3842fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3843dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
384442134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38453deb3ec6SMatthias Ringwald                                 // slave
3846bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3847bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3848bbf8db22SMatthias Ringwald                                 } else {
3849f3582630SMatthias 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);
3850bbf8db22SMatthias Ringwald                                 }
38513deb3ec6SMatthias Ringwald                             } else {
38523deb3ec6SMatthias Ringwald                                 // master
385361d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38543deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38553deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
3856f3582630SMatthias 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);
38573deb3ec6SMatthias Ringwald                                 } else {
38583deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38593deb3ec6SMatthias Ringwald                                 }
38603deb3ec6SMatthias Ringwald                             }
38613deb3ec6SMatthias Ringwald                             break;
3862c18be159SMatthias Ringwald 
3863c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3864c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3865c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3866c18be159SMatthias Ringwald                             // prepare for pairing request
3867c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3868c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3869c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3870c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3871c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3872c18be159SMatthias Ringwald                             }
3873c18be159SMatthias Ringwald                             break;
3874c18be159SMatthias Ringwald #endif
38753deb3ec6SMatthias Ringwald                         default:
38763deb3ec6SMatthias Ringwald                             break;
38773deb3ec6SMatthias Ringwald                     }
38783deb3ec6SMatthias Ringwald                     break;
38793deb3ec6SMatthias Ringwald 
38803deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3881711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3882711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38833deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38843deb3ec6SMatthias Ringwald 
38853deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
38863deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
38873deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
38883deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
38895567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
38905567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
38915567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38925567aa60SMatthias Ringwald                             } else {
38933deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38945567aa60SMatthias Ringwald                             }
38953deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38963deb3ec6SMatthias Ringwald                             break;
38973deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
389842134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38993deb3ec6SMatthias Ringwald                                 // slave
3900f3582630SMatthias 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);
39013deb3ec6SMatthias Ringwald                             } else {
39023deb3ec6SMatthias Ringwald                                 // master
39033deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
39043deb3ec6SMatthias Ringwald                             }
39053deb3ec6SMatthias Ringwald                             break;
39063deb3ec6SMatthias Ringwald                         default:
39073deb3ec6SMatthias Ringwald                             break;
39083deb3ec6SMatthias Ringwald                     }
39093deb3ec6SMatthias Ringwald                     break;
39103deb3ec6SMatthias Ringwald 
39113deb3ec6SMatthias Ringwald 
39123deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3913711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3914711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3915711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39163deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39173deb3ec6SMatthias Ringwald 
391803f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39197f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39207f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39217f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39227f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39237f3f442dSMatthias Ringwald                             break;
39247f3f442dSMatthias Ringwald                         default:
392568a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39260ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39277f3f442dSMatthias Ringwald                             break;
392803f736b1SMatthias Ringwald                     }
3929accbde80SMatthias Ringwald 
39303deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39313deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39323deb3ec6SMatthias Ringwald                     break;
39333deb3ec6SMatthias Ringwald 
39343deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
393533373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
39369091c5f5SMatthias Ringwald                         // set local addr for le device db
393733373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39380c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
393933373e40SMatthias Ringwald                     }
394065b44ffdSMatthias Ringwald                     break;
394165b44ffdSMatthias Ringwald                 default:
394265b44ffdSMatthias Ringwald                     break;
39433deb3ec6SMatthias Ringwald 			}
394465b44ffdSMatthias Ringwald             break;
394565b44ffdSMatthias Ringwald         default:
394665b44ffdSMatthias Ringwald             break;
39473deb3ec6SMatthias Ringwald 	}
39483deb3ec6SMatthias Ringwald 
39493deb3ec6SMatthias Ringwald     sm_run();
39503deb3ec6SMatthias Ringwald }
39513deb3ec6SMatthias Ringwald 
39523deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39533deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39543deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39553deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39563deb3ec6SMatthias Ringwald }
39573deb3ec6SMatthias Ringwald 
3958945888f5SMatthias Ringwald 
395931c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3960945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3961945888f5SMatthias Ringwald     switch (method){
3962945888f5SMatthias Ringwald         case JUST_WORKS:
396347fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3964945888f5SMatthias Ringwald             return 1;
3965945888f5SMatthias Ringwald         default:
3966945888f5SMatthias Ringwald             return 0;
3967945888f5SMatthias Ringwald     }
3968945888f5SMatthias Ringwald }
396907036a04SMatthias Ringwald // responder
3970945888f5SMatthias Ringwald 
3971688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3972688a08f9SMatthias Ringwald     switch (method){
3973688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3974688a08f9SMatthias Ringwald             return 1;
3975688a08f9SMatthias Ringwald         default:
3976688a08f9SMatthias Ringwald             return 0;
3977688a08f9SMatthias Ringwald     }
3978688a08f9SMatthias Ringwald }
397940c5d850SMatthias Ringwald 
398040c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
398140c5d850SMatthias Ringwald     switch (method){
398240c5d850SMatthias Ringwald         case PK_RESP_INPUT:
398340c5d850SMatthias Ringwald         case PK_INIT_INPUT:
398447fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
398540c5d850SMatthias Ringwald             return 1;
398640c5d850SMatthias Ringwald         default:
398740c5d850SMatthias Ringwald             return 0;
398840c5d850SMatthias Ringwald     }
398940c5d850SMatthias Ringwald }
399040c5d850SMatthias Ringwald 
399131c09488SMatthias Ringwald #endif
3992688a08f9SMatthias Ringwald 
39933deb3ec6SMatthias Ringwald /**
39943deb3ec6SMatthias Ringwald  * @return ok
39953deb3ec6SMatthias Ringwald  */
39963deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
39973deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
39983deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
39993deb3ec6SMatthias Ringwald         case JUST_WORKS:
40004ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
40013deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
40023deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
400347fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
40044ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
40053deb3ec6SMatthias Ringwald         case OOB:
40064ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
400747fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40084ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40093deb3ec6SMatthias Ringwald         default:
40103deb3ec6SMatthias Ringwald             return 0;
40113deb3ec6SMatthias Ringwald     }
40123deb3ec6SMatthias Ringwald }
40133deb3ec6SMatthias Ringwald 
401436f0defaSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
401536f0defaSMatthias Ringwald static void sm_initiator_connected_handle_security_request(sm_connection_t * sm_conn, const uint8_t *packet){
401636f0defaSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
401736f0defaSMatthias Ringwald     if (sm_sc_only_mode){
401836f0defaSMatthias Ringwald         uint8_t auth_req = packet[1];
401936f0defaSMatthias Ringwald         if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
402036f0defaSMatthias Ringwald             sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
402136f0defaSMatthias Ringwald             return;
402236f0defaSMatthias Ringwald         }
402336f0defaSMatthias Ringwald     }
402436f0defaSMatthias Ringwald #else
402536f0defaSMatthias Ringwald     UNUSED(packet);
402636f0defaSMatthias Ringwald #endif
402736f0defaSMatthias Ringwald 
402836f0defaSMatthias Ringwald     int have_ltk;
402936f0defaSMatthias Ringwald     uint8_t ltk[16];
403036f0defaSMatthias Ringwald 
403136f0defaSMatthias Ringwald     // IRK complete?
403236f0defaSMatthias Ringwald     switch (sm_conn->sm_irk_lookup_state){
403336f0defaSMatthias Ringwald         case IRK_LOOKUP_FAILED:
403436f0defaSMatthias Ringwald             // start pairing
403536f0defaSMatthias Ringwald             sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
403636f0defaSMatthias Ringwald             break;
403736f0defaSMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
403836f0defaSMatthias Ringwald             le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
403936f0defaSMatthias Ringwald             have_ltk = !sm_is_null_key(ltk);
404036f0defaSMatthias Ringwald             log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
404136f0defaSMatthias Ringwald             if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
404236f0defaSMatthias Ringwald                 // start re-encrypt if we have LTK and the connection is not already encrypted
404336f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
404436f0defaSMatthias Ringwald             } else {
404536f0defaSMatthias Ringwald                 // start pairing
404636f0defaSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
404736f0defaSMatthias Ringwald             }
404836f0defaSMatthias Ringwald             break;
404936f0defaSMatthias Ringwald         default:
405036f0defaSMatthias Ringwald             // otherwise, store security request
405136f0defaSMatthias Ringwald             sm_conn->sm_security_request_received = 1;
405236f0defaSMatthias Ringwald             break;
405336f0defaSMatthias Ringwald     }
405436f0defaSMatthias Ringwald }
405536f0defaSMatthias Ringwald #endif
405636f0defaSMatthias Ringwald 
40578334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40588334d3d8SMatthias Ringwald 
40594c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40604c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40614c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40624c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40634c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40644c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40654c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40664c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40674c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40687a2e6387SMatthias Ringwald             11, // 0x07 master identification
40694c1d1092SMatthias Ringwald             17, // 0x08 identification information
40704c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40714c1d1092SMatthias Ringwald             17, // 0x0a signing information
40724c1d1092SMatthias Ringwald             2,  // 0x0b security request
40734c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40744c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40754c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
40764c1d1092SMatthias Ringwald     };
40773deb3ec6SMatthias Ringwald 
4078c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4079b170b20fSMatthias Ringwald         sm_run();
4080b170b20fSMatthias Ringwald     }
4081b170b20fSMatthias Ringwald 
40823deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
40834ea43905SMatthias Ringwald     if (size == 0u) return;
40844c1d1092SMatthias Ringwald 
40854c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
40864c1d1092SMatthias Ringwald 
40874c1d1092SMatthias Ringwald     // validate pdu size
40884c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
40897a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
40903deb3ec6SMatthias Ringwald 
4091711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
40923deb3ec6SMatthias Ringwald     if (!sm_conn) return;
40933deb3ec6SMatthias Ringwald 
40944c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
409568a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
40960ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4097accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
40983deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
40993deb3ec6SMatthias Ringwald         return;
41003deb3ec6SMatthias Ringwald     }
41013deb3ec6SMatthias Ringwald 
41024c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
41033deb3ec6SMatthias Ringwald 
41043deb3ec6SMatthias Ringwald     int err;
410542134bc6SMatthias Ringwald     UNUSED(err);
41063deb3ec6SMatthias Ringwald 
41074c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
41083d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
41093d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
41103d7fe1e9SMatthias Ringwald         buffer[1] = 3;
41113d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
41123d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
41133d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
41143d7fe1e9SMatthias Ringwald         return;
41153d7fe1e9SMatthias Ringwald     }
41163d7fe1e9SMatthias Ringwald 
41173deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
41183deb3ec6SMatthias Ringwald 
4119c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
41203deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
41213deb3ec6SMatthias Ringwald             return;
41223deb3ec6SMatthias Ringwald 
412342134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
412442134bc6SMatthias Ringwald 
41253deb3ec6SMatthias Ringwald         // Initiator
41263deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
41274c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
41283deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41293deb3ec6SMatthias Ringwald                 break;
41303deb3ec6SMatthias Ringwald             }
413136f0defaSMatthias Ringwald             sm_initiator_connected_handle_security_request(sm_conn, packet);
4132dc8ca372SMatthias Ringwald             break;
41333deb3ec6SMatthias Ringwald 
41343deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4135aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4136aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4137aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4138aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4139aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4140aacfafc3SMatthias Ringwald                 break;
4141aacfafc3SMatthias Ringwald             }
4142aacfafc3SMatthias Ringwald 
4143aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41444c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41453deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41463deb3ec6SMatthias Ringwald                 break;
41473deb3ec6SMatthias Ringwald             }
41480af429c6SMatthias Ringwald 
41493deb3ec6SMatthias Ringwald             // store pairing request
41506535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41516535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41523deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41530af429c6SMatthias Ringwald 
41540af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41550af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41560af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41570af429c6SMatthias Ringwald                 err = test_pairing_failure;
41580af429c6SMatthias Ringwald             }
41590af429c6SMatthias Ringwald #endif
41600af429c6SMatthias Ringwald 
41619305033eSMatthias Ringwald             if (err != 0){
4162f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41633deb3ec6SMatthias Ringwald                 break;
41643deb3ec6SMatthias Ringwald             }
4165b41539d5SMatthias Ringwald 
4166b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4167b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4168f3582630SMatthias 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);
4169b41539d5SMatthias Ringwald                 break;
4170b41539d5SMatthias Ringwald             }
4171b41539d5SMatthias Ringwald 
4172136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4173136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41748cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41758cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4176136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4177136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4178136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4179c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4180136d331aSMatthias Ringwald                     }
41818cba5ca3SMatthias Ringwald                 } else {
4182c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
41838cba5ca3SMatthias Ringwald                 }
4184136d331aSMatthias Ringwald                 break;
4185136d331aSMatthias Ringwald             }
4186136d331aSMatthias Ringwald #endif
41873deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
41883deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
41893deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
41903deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4191f3582630SMatthias 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);
41923deb3ec6SMatthias Ringwald             }
41933deb3ec6SMatthias Ringwald             break;
41943deb3ec6SMatthias Ringwald 
41953deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
41964c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
41973deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41983deb3ec6SMatthias Ringwald                 break;
41993deb3ec6SMatthias Ringwald             }
42003deb3ec6SMatthias Ringwald 
42013deb3ec6SMatthias Ringwald             // store s_confirm
42029c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4203192365feSMatthias Ringwald 
4204aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4205aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4206aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4207aa9b34e5SMatthias Ringwald                 break;
4208aa9b34e5SMatthias Ringwald             }
4209aa9b34e5SMatthias Ringwald 
4210192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4211192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4212192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4213192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4214192365feSMatthias Ringwald             }
4215192365feSMatthias Ringwald #endif
42163deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42173deb3ec6SMatthias Ringwald             break;
42183deb3ec6SMatthias Ringwald 
42193deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42204c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42213deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42223deb3ec6SMatthias Ringwald                 break;;
42233deb3ec6SMatthias Ringwald             }
42243deb3ec6SMatthias Ringwald 
42253deb3ec6SMatthias Ringwald             // received random value
42269c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42273deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42283deb3ec6SMatthias Ringwald             break;
422942134bc6SMatthias Ringwald #endif
42303deb3ec6SMatthias Ringwald 
423142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42323deb3ec6SMatthias Ringwald         // Responder
42333deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42343deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42353deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42364c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42373deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42383deb3ec6SMatthias Ringwald                 break;;
42393deb3ec6SMatthias Ringwald             }
42403deb3ec6SMatthias Ringwald 
42413deb3ec6SMatthias Ringwald             // store pairing request
4242212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4243212d735eSMatthias Ringwald 
4244212d735eSMatthias Ringwald             // check if IRK completed
4245212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4246212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4247212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42483deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42493deb3ec6SMatthias Ringwald                     break;
4250212d735eSMatthias Ringwald                 default:
4251212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4252212d735eSMatthias Ringwald                     break;
4253212d735eSMatthias Ringwald             }
4254212d735eSMatthias Ringwald             break;
425542134bc6SMatthias Ringwald #endif
42563deb3ec6SMatthias Ringwald 
425727c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4258c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42594c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
426027c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
426127c32905SMatthias Ringwald                 break;
426227c32905SMatthias Ringwald             }
4263bccf5e67SMatthias Ringwald 
4264e53be891SMatthias Ringwald             // store public key for DH Key calculation
4265fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4266fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4267bccf5e67SMatthias Ringwald 
426802658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
426902658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
427002658749SMatthias Ringwald                 log_info("Remote PK matches ours");
427102658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
427202658749SMatthias Ringwald                 break;
427302658749SMatthias Ringwald             }
427402658749SMatthias Ringwald 
4275d1a1f6a4SMatthias Ringwald             // validate public key
4276d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
42779305033eSMatthias Ringwald             if (err != 0){
427802658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4279349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4280bccf5e67SMatthias Ringwald                 break;
4281bccf5e67SMatthias Ringwald             }
4282891bb64aSMatthias Ringwald 
4283d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4284f3582630SMatthias 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);
42853cf37b8cSMatthias Ringwald 
428665a9a04eSMatthias Ringwald 
428765a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
428842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4289136d331aSMatthias Ringwald                 // responder
4290c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4291136d331aSMatthias Ringwald             } else {
4292136d331aSMatthias Ringwald                 // initiator
4293a1e31e9cSMatthias Ringwald                 // stk generation method
4294a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4295a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4296a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
429747fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4298c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4299a1e31e9cSMatthias Ringwald                         break;
4300a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
430107036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
430207036a04SMatthias Ringwald                         break;
430307036a04SMatthias Ringwald                     case PK_INIT_INPUT:
430447fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
430507036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
430607036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
430707036a04SMatthias Ringwald                             break;
430807036a04SMatthias Ringwald                         }
4309b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4310a1e31e9cSMatthias Ringwald                         break;
4311a1e31e9cSMatthias Ringwald                     case OOB:
4312d1a1f6a4SMatthias Ringwald                         // generate Nx
43134acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43146ca80073SMatthias 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);
4315a1e31e9cSMatthias Ringwald                         break;
43167bbeb3adSMilanka Ringwald                     default:
43177bbeb3adSMilanka Ringwald                         btstack_assert(false);
43187bbeb3adSMilanka Ringwald                         break;
4319a1e31e9cSMatthias Ringwald                 }
4320136d331aSMatthias Ringwald             }
432127c32905SMatthias Ringwald             break;
4322e53be891SMatthias Ringwald 
4323c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43244c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
432545a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
432645a61d50SMatthias Ringwald                 break;
432745a61d50SMatthias Ringwald             }
432845a61d50SMatthias Ringwald             // received confirm value
432945a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
433045a61d50SMatthias Ringwald 
4331192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4332192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4333192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4334192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4335192365feSMatthias Ringwald             }
4336192365feSMatthias Ringwald #endif
433742134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
433845a61d50SMatthias Ringwald                 // responder
433907036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
434007036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
434107036a04SMatthias Ringwald                         // still waiting for passkey
434207036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
434307036a04SMatthias Ringwald                         break;
434407036a04SMatthias Ringwald                     }
434507036a04SMatthias Ringwald                 }
4346b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
434745a61d50SMatthias Ringwald             } else {
434845a61d50SMatthias Ringwald                 // initiator
4349945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43506ca80073SMatthias 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);
4351f1c1783eSMatthias Ringwald                 } else {
4352c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
435345a61d50SMatthias Ringwald                 }
4354f1c1783eSMatthias Ringwald             }
435545a61d50SMatthias Ringwald             break;
435645a61d50SMatthias Ringwald 
4357c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43584c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4359e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4360136d331aSMatthias Ringwald                 break;
4361e53be891SMatthias Ringwald             }
4362e53be891SMatthias Ringwald 
4363e53be891SMatthias Ringwald             // received random value
4364e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4365e53be891SMatthias Ringwald 
43665a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4367ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4368d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4369d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4370d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
437165a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4372d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4373688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4374ae451ec5SMatthias Ringwald                  break;
43755a293e6eSMatthias Ringwald             }
43766f52a196SMatthias Ringwald 
43774acf7b7bSMatthias Ringwald             // OOB
43784acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
43794acf7b7bSMatthias Ringwald 
43804acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
43814acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
43824acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43834ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
43844acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
43854acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
43864acf7b7bSMatthias Ringwald                     } else {
43876535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
43884acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
43894acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
43904acf7b7bSMatthias Ringwald                     }
43914acf7b7bSMatthias Ringwald                 }  else {
43924ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
43934acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
43944acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
43954acf7b7bSMatthias Ringwald                     } else {
43966535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
43974acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
43984acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
43994acf7b7bSMatthias Ringwald                     }
44004acf7b7bSMatthias Ringwald                 }
44014acf7b7bSMatthias Ringwald 
4402a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
44034acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4404a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4405a680ba6bSMatthias Ringwald                      break;
4406a680ba6bSMatthias Ringwald                 }
44074acf7b7bSMatthias Ringwald             }
4408a680ba6bSMatthias Ringwald 
4409a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4410688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4411e53be891SMatthias Ringwald             break;
4412e53be891SMatthias Ringwald 
4413901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4414901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44153cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4416901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4417901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4418901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4419901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4420901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4421901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4422901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4423c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4424901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4425d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44264c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4427e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4428e53be891SMatthias Ringwald                 break;
4429e53be891SMatthias Ringwald             }
4430e53be891SMatthias Ringwald             // store DHKey Check
4431901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4432e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4433446a8c36SMatthias Ringwald 
4434901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4435901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4436019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4437bd57ffebSMatthias Ringwald             }
4438bd57ffebSMatthias Ringwald             break;
443927c32905SMatthias Ringwald #endif
444027c32905SMatthias Ringwald 
444142134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44423deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44434c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44443deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
444527c32905SMatthias Ringwald                 break;
44463deb3ec6SMatthias Ringwald             }
44473deb3ec6SMatthias Ringwald 
44483deb3ec6SMatthias Ringwald             // received confirm value
44499c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44503deb3ec6SMatthias Ringwald 
4451192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4452192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4453192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4454192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4455192365feSMatthias Ringwald             }
4456192365feSMatthias Ringwald #endif
44573deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44583deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44595611a760SMatthias 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);
44603deb3ec6SMatthias Ringwald             }
44613deb3ec6SMatthias Ringwald 
44623deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44633deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4464f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44653deb3ec6SMatthias Ringwald                 break;
44663deb3ec6SMatthias Ringwald             }
44673deb3ec6SMatthias Ringwald 
44683deb3ec6SMatthias Ringwald             // wait for user action?
44693deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44703deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44713deb3ec6SMatthias Ringwald                 break;
44723deb3ec6SMatthias Ringwald             }
44733deb3ec6SMatthias Ringwald 
44743deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4475f3582630SMatthias 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);
44763deb3ec6SMatthias Ringwald             break;
44773deb3ec6SMatthias Ringwald 
44783deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
44794c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
44803deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
44813deb3ec6SMatthias Ringwald                 break;;
44823deb3ec6SMatthias Ringwald             }
44833deb3ec6SMatthias Ringwald 
44843deb3ec6SMatthias Ringwald             // received random value
44859c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
44863deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
44873deb3ec6SMatthias Ringwald             break;
448842134bc6SMatthias Ringwald #endif
44893deb3ec6SMatthias Ringwald 
44903deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
44914c1d1092SMatthias Ringwald             switch(sm_pdu_code){
44923deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
44933deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
44949c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
44953deb3ec6SMatthias Ringwald                     break;
44963deb3ec6SMatthias Ringwald 
44973deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
44983deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4499f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
45009c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
45013deb3ec6SMatthias Ringwald                     break;
45023deb3ec6SMatthias Ringwald 
45033deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
45043deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
45059c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
45063deb3ec6SMatthias Ringwald                     break;
45073deb3ec6SMatthias Ringwald 
45083deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
45093deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
45103deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4511724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
45123deb3ec6SMatthias Ringwald                     break;
45133deb3ec6SMatthias Ringwald 
45143deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45153deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45169c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45173deb3ec6SMatthias Ringwald                     break;
45183deb3ec6SMatthias Ringwald                 default:
45193deb3ec6SMatthias Ringwald                     // Unexpected PDU
45203deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45213deb3ec6SMatthias Ringwald                     break;
45223deb3ec6SMatthias Ringwald             }
45233deb3ec6SMatthias Ringwald             // done with key distribution?
452461d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45253deb3ec6SMatthias Ringwald 
45263deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45273deb3ec6SMatthias Ringwald 
452842134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45296f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45303deb3ec6SMatthias Ringwald                 } else {
4531625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4532625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4533bbf8db22SMatthias Ringwald                     } else {
4534f3582630SMatthias 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);
4535625f00b2SMatthias Ringwald                     }
45363deb3ec6SMatthias Ringwald                 }
45373deb3ec6SMatthias Ringwald             }
45383deb3ec6SMatthias Ringwald             break;
4539c18be159SMatthias Ringwald 
4540c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4541c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4542c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4543c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4544c18be159SMatthias Ringwald                 break;
4545c18be159SMatthias Ringwald             }
4546c18be159SMatthias Ringwald             // store pairing response
4547c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4548c18be159SMatthias Ringwald 
4549c18be159SMatthias Ringwald             // validate encryption key size
4550c18be159SMatthias 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));
4551c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4552c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4553c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4554c18be159SMatthias Ringwald             }
4555c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4556c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4557c18be159SMatthias Ringwald                 break;
4558c18be159SMatthias Ringwald             }
4559c18be159SMatthias Ringwald 
4560c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4561c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4562c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4563c18be159SMatthias Ringwald 
4564c18be159SMatthias Ringwald             // skip receive if there are none
456561d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4566c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4567c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4568c18be159SMatthias Ringwald             } else {
4569c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4570c18be159SMatthias Ringwald             }
4571c18be159SMatthias Ringwald             break;
4572c18be159SMatthias Ringwald 
4573c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4574c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4575c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4576c18be159SMatthias Ringwald                 break;
4577c18be159SMatthias Ringwald             }
4578c18be159SMatthias Ringwald             // store pairing request
4579c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4580c18be159SMatthias Ringwald             // validate encryption key size
4581c18be159SMatthias 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));
4582c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4583c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4584c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4585c18be159SMatthias Ringwald             }
4586c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4587c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4588c18be159SMatthias Ringwald                 break;
4589c18be159SMatthias Ringwald             }
4590c18be159SMatthias Ringwald             // trigger response
4591c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4592c18be159SMatthias Ringwald             break;
4593c18be159SMatthias Ringwald 
4594c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4595c18be159SMatthias Ringwald             switch(sm_pdu_code){
4596c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4597c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4598c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4599c18be159SMatthias Ringwald                     break;
4600c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4601c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4602c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4603c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4604c18be159SMatthias Ringwald                     break;
4605c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4606c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4607c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4608c18be159SMatthias Ringwald                     break;
4609c18be159SMatthias Ringwald                 default:
4610c18be159SMatthias Ringwald                     // Unexpected PDU
4611c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4612c18be159SMatthias Ringwald                     break;
4613c18be159SMatthias Ringwald             }
4614c18be159SMatthias Ringwald 
4615c18be159SMatthias Ringwald             // all keys received
461661d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4617c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4618c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4619c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4620c18be159SMatthias Ringwald                 } else {
4621c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4622c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4623c18be159SMatthias Ringwald                 }
4624c18be159SMatthias Ringwald             }
4625c18be159SMatthias Ringwald             break;
4626c18be159SMatthias Ringwald #endif
4627c18be159SMatthias Ringwald 
46283deb3ec6SMatthias Ringwald         default:
46293deb3ec6SMatthias Ringwald             // Unexpected PDU
46303deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46312d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46323deb3ec6SMatthias Ringwald             break;
46333deb3ec6SMatthias Ringwald     }
46343deb3ec6SMatthias Ringwald 
463570b44dd4SMatthias Ringwald     // try to send next pdu
463670b44dd4SMatthias Ringwald     sm_trigger_run();
46373deb3ec6SMatthias Ringwald }
46383deb3ec6SMatthias Ringwald 
46393deb3ec6SMatthias Ringwald // Security Manager Client API
4640a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46413deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46423deb3ec6SMatthias Ringwald }
46433deb3ec6SMatthias Ringwald 
46444acf7b7bSMatthias 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)){
4645a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4646a680ba6bSMatthias Ringwald }
4647a680ba6bSMatthias Ringwald 
4648*b96d60a6SMatthias 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)){
4649*b96d60a6SMatthias Ringwald     sm_get_ltk_callback = get_ltk_callback;
4650*b96d60a6SMatthias Ringwald }
4651*b96d60a6SMatthias Ringwald 
465289a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
465389a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
465489a78d34SMatthias Ringwald }
465589a78d34SMatthias Ringwald 
465667f708e0SMatthias Ringwald void sm_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
465767f708e0SMatthias Ringwald     btstack_linked_list_remove(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
465867f708e0SMatthias Ringwald }
465967f708e0SMatthias Ringwald 
46603deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46613deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46623deb3ec6SMatthias Ringwald }
46633deb3ec6SMatthias Ringwald 
46643deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46653deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46663deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46673deb3ec6SMatthias Ringwald }
46683deb3ec6SMatthias Ringwald 
46693deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
467098d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
467198d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
467298d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
467398d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
467498d95509SMatthias Ringwald     }
467598d95509SMatthias Ringwald #endif
46763deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
46773deb3ec6SMatthias Ringwald }
46783deb3ec6SMatthias Ringwald 
46793deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
46803deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
46813deb3ec6SMatthias Ringwald }
46823deb3ec6SMatthias Ringwald 
468342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
46843deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
46853deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
46863deb3ec6SMatthias Ringwald }
468742134bc6SMatthias Ringwald #endif
46883deb3ec6SMatthias Ringwald 
46893deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
46906535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
46913deb3ec6SMatthias Ringwald }
46923deb3ec6SMatthias Ringwald 
46933deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
46946535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
46953deb3ec6SMatthias Ringwald }
46963deb3ec6SMatthias Ringwald 
46973deb3ec6SMatthias Ringwald // Testing support only
46983deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
46996535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4700103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4701841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
47023deb3ec6SMatthias Ringwald }
47033deb3ec6SMatthias Ringwald 
47043deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4705841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
47063deb3ec6SMatthias Ringwald }
47073deb3ec6SMatthias Ringwald 
4708d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4709d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4710d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4711d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
471234b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
471370b44dd4SMatthias Ringwald     sm_trigger_run();
4714d1a1f6a4SMatthias Ringwald }
4715674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
471634b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4717674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4718674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4719674e5b4aSMatthias Ringwald }
4720d1a1f6a4SMatthias Ringwald #endif
4721d1a1f6a4SMatthias Ringwald 
4722192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4723192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4724192365feSMatthias Ringwald     test_pairing_failure = reason;
4725192365feSMatthias Ringwald }
4726192365feSMatthias Ringwald #endif
4727192365feSMatthias Ringwald 
47283deb3ec6SMatthias Ringwald void sm_init(void){
47292d2d4d3cSMatthias Ringwald 
47302d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47312d2d4d3cSMatthias Ringwald 
4732899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4733899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4734899e6e02SMatthias Ringwald 
47353deb3ec6SMatthias Ringwald     // defaults
47363deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47373deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4738b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4739b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4740b4343428SMatthias Ringwald 
47413deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47423deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47433deb3ec6SMatthias Ringwald 
47445ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47451979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4746caf15bf3SMatthias Ringwald 
4747d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4748d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47497a766ebfSMatthias Ringwald #endif
47508d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4751fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47523deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47533deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47543deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47553deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47563deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47573deb3ec6SMatthias Ringwald 
47583deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47597149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47603deb3ec6SMatthias Ringwald 
4761841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47623deb3ec6SMatthias Ringwald 
476384c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
476484c0c5c7SMatthias Ringwald 
4765e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4766e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4767e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4768e03e489aSMatthias Ringwald 
4769d1a1f6a4SMatthias Ringwald     //
4770d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4771d1a1f6a4SMatthias Ringwald 
477251bd74d1SMatthias Ringwald     // init le_device_db
477351bd74d1SMatthias Ringwald     le_device_db_init();
477451bd74d1SMatthias Ringwald 
4775b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4776e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
477727c32905SMatthias Ringwald 
477809e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4779674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4780a3aba2f9SMatthias Ringwald #endif
47812d2d4d3cSMatthias Ringwald 
47822d2d4d3cSMatthias Ringwald     sm_initialized = true;
47833deb3ec6SMatthias Ringwald }
47843deb3ec6SMatthias Ringwald 
478515537ea4SMatthias Ringwald void sm_deinit(void){
478615537ea4SMatthias Ringwald     sm_initialized = false;
478715537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
478815537ea4SMatthias Ringwald }
478915537ea4SMatthias Ringwald 
47904b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
47914b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4792caf15bf3SMatthias Ringwald }
4793caf15bf3SMatthias Ringwald 
47946c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
47951979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
47966c39055aSMatthias Ringwald }
47976c39055aSMatthias Ringwald 
4798711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4799711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
48003deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
48013deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
48023deb3ec6SMatthias Ringwald }
48033deb3ec6SMatthias Ringwald 
480477e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
480577e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
480677e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
480777e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
480877e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
480977e2e5edSMatthias Ringwald }
481077e2e5edSMatthias Ringwald #endif
481177e2e5edSMatthias Ringwald 
48126bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4813711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4814711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48153deb3ec6SMatthias Ringwald     if (!sm_conn) return;
48166bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
48176bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
48183deb3ec6SMatthias Ringwald }
48193deb3ec6SMatthias Ringwald 
48203deb3ec6SMatthias Ringwald // request pairing
4821711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4822711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48233deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48243deb3ec6SMatthias Ringwald 
48257af5dcd5SMatthias Ringwald     bool have_ltk;
48267af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48273deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
482842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
482924c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
483024c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
483124c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48327af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48337af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48347af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48357af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48367af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48377af5dcd5SMatthias Ringwald                         if (have_ltk){
48387af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
483924c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48407af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48417af5dcd5SMatthias Ringwald                             break;
48427af5dcd5SMatthias Ringwald                         }
48437af5dcd5SMatthias Ringwald                         /* fall through */
48447af5dcd5SMatthias Ringwald 
48457af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48467af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48477af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48487af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48497af5dcd5SMatthias Ringwald                         break;
48507af5dcd5SMatthias Ringwald                     default:
48517af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48527af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48537af5dcd5SMatthias Ringwald                         break;
48547af5dcd5SMatthias Ringwald                 }
485524c20dc4SMatthias Ringwald                 break;
485624c20dc4SMatthias Ringwald             default:
485724c20dc4SMatthias Ringwald                 break;
485824c20dc4SMatthias Ringwald         }
48593deb3ec6SMatthias Ringwald     } else {
48603deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4861175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4862175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48633deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48643deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48653dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4866f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4867f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4868f53ec649SMatthias Ringwald                         if (have_ltk){
4869c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48705567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4871c245ca32SMatthias Ringwald                             break;
4872f53ec649SMatthias Ringwald                         }
4873cf373d3aSMatthias Ringwald                         /* fall through */
4874c245ca32SMatthias Ringwald 
487534c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48763deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
48773deb3ec6SMatthias Ringwald                         break;
48783deb3ec6SMatthias Ringwald                     default:
4879d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
488009ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48813deb3ec6SMatthias Ringwald                         break;
48823deb3ec6SMatthias Ringwald                 }
4883175b7faaSMatthias Ringwald                 break;
4884cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4885cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4886cb6d7eb0SMatthias Ringwald                 break;
4887175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
488809ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4889175b7faaSMatthias Ringwald                 break;
4890175b7faaSMatthias Ringwald             default:
4891175b7faaSMatthias Ringwald                 break;
48923deb3ec6SMatthias Ringwald         }
48933deb3ec6SMatthias Ringwald     }
489470b44dd4SMatthias Ringwald     sm_trigger_run();
48953deb3ec6SMatthias Ringwald }
48963deb3ec6SMatthias Ringwald 
48973deb3ec6SMatthias Ringwald // called by client app on authorization request
4898711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4899711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49003deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49013deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4902589f5a99SMatthias 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);
49033deb3ec6SMatthias Ringwald }
49043deb3ec6SMatthias Ringwald 
4905711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4906711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49073deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49083deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4909589f5a99SMatthias 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);
49103deb3ec6SMatthias Ringwald }
49113deb3ec6SMatthias Ringwald 
49123deb3ec6SMatthias Ringwald // GAP Bonding API
49133deb3ec6SMatthias Ringwald 
4914711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4915711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49163deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49173deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
49180af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
49190af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
49200af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49210af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49220af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49230af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49240af429c6SMatthias Ringwald #endif
49250af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4926de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4927de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4928de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
492947fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49300af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4931de2fd182SMatthias Ringwald                     break;
493247fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4933de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4934de2fd182SMatthias Ringwald                     break;
4935de2fd182SMatthias Ringwald                 case JUST_WORKS:
4936de2fd182SMatthias Ringwald                 case OOB:
4937de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4938de2fd182SMatthias Ringwald                     break;
49397bbeb3adSMilanka Ringwald                 default:
49407bbeb3adSMilanka Ringwald                     btstack_assert(false);
49417bbeb3adSMilanka Ringwald                     break;
4942de2fd182SMatthias Ringwald             }
49430af429c6SMatthias Ringwald             break;
49440af429c6SMatthias Ringwald         default:
49450af429c6SMatthias Ringwald             break;
49463deb3ec6SMatthias Ringwald     }
494770b44dd4SMatthias Ringwald     sm_trigger_run();
49483deb3ec6SMatthias Ringwald }
49493deb3ec6SMatthias Ringwald 
4950711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4951711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49523deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49533deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49543deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4955136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4956c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4957bbf8db22SMatthias Ringwald         } else {
4958f3582630SMatthias 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);
4959136d331aSMatthias Ringwald         }
49603deb3ec6SMatthias Ringwald     }
49610346c37cSMatthias Ringwald 
49620346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4963c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4964dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4965446a8c36SMatthias Ringwald     }
49660346c37cSMatthias Ringwald #endif
49670346c37cSMatthias Ringwald 
496870b44dd4SMatthias Ringwald     sm_trigger_run();
49693deb3ec6SMatthias Ringwald }
49703deb3ec6SMatthias Ringwald 
4971c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4972c8c46d51SMatthias Ringwald     // for now, it's the same
4973c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4974c8c46d51SMatthias Ringwald }
4975c8c46d51SMatthias Ringwald 
4976711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4977711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49783deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49793deb3ec6SMatthias Ringwald     sm_reset_tk();
4980f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
49813deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
49823deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4983f3582630SMatthias 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);
49843deb3ec6SMatthias Ringwald     }
49851c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49866535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
49876535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
498807036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
498907036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
499007036a04SMatthias Ringwald     }
49911c516d8fSMatthias Ringwald #endif
499270b44dd4SMatthias Ringwald     sm_trigger_run();
49933deb3ec6SMatthias Ringwald }
49943deb3ec6SMatthias Ringwald 
49953d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
49963d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49973d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49983d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4999dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
50004ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
5001dd4a08fbSMatthias Ringwald     switch (action){
5002dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
5003dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
50044ea43905SMatthias Ringwald             flags |= (1u << action);
5005dd4a08fbSMatthias Ringwald             break;
5006dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
5007dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
50084ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
5009dd4a08fbSMatthias Ringwald             break;
5010dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
50114ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
5012dd4a08fbSMatthias Ringwald                 // erase actions queued
5013dd4a08fbSMatthias Ringwald                 num_actions--;
50144ea43905SMatthias Ringwald                 if (num_actions == 0u){
5015dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50164ea43905SMatthias Ringwald                     flags &= 0x19u;
5017dd4a08fbSMatthias Ringwald                 }
5018dd4a08fbSMatthias Ringwald                 break;
5019dd4a08fbSMatthias Ringwald             }
5020dd4a08fbSMatthias Ringwald             num_actions++;
50214ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5022dd4a08fbSMatthias Ringwald             break;
5023dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50244ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5025dd4a08fbSMatthias Ringwald                 // enter actions queued
5026dd4a08fbSMatthias Ringwald                 num_actions--;
50274ea43905SMatthias Ringwald                 if (num_actions == 0u){
5028dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50294ea43905SMatthias Ringwald                     flags &= 0x19u;
5030dd4a08fbSMatthias Ringwald                 }
5031dd4a08fbSMatthias Ringwald                 break;
5032dd4a08fbSMatthias Ringwald             }
5033dd4a08fbSMatthias Ringwald             num_actions++;
50344ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5035dd4a08fbSMatthias Ringwald             break;
5036dd4a08fbSMatthias Ringwald         default:
5037dd4a08fbSMatthias Ringwald             break;
5038dd4a08fbSMatthias Ringwald     }
5039dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
504070b44dd4SMatthias Ringwald     sm_trigger_run();
50413d7fe1e9SMatthias Ringwald }
50423d7fe1e9SMatthias Ringwald 
5043c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5044d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5045d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5046d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
504770b44dd4SMatthias Ringwald     sm_trigger_run();
5048d1a1f6a4SMatthias Ringwald }
5049c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50508334d3d8SMatthias Ringwald 
50518334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50528334d3d8SMatthias Ringwald 
5053c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5054c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5055d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5056d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5057c59d0c92SMatthias Ringwald     return 0;
5058c59d0c92SMatthias Ringwald }
5059c59d0c92SMatthias Ringwald #endif
5060c59d0c92SMatthias Ringwald 
50613deb3ec6SMatthias Ringwald /**
5062ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5063ba394633SMatthias Ringwald  * @param con_handle
5064ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5065ba394633SMatthias Ringwald  */
5066ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5067ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5068ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5069ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5070ba394633SMatthias Ringwald }
5071ba394633SMatthias Ringwald 
5072ba394633SMatthias Ringwald /**
50733deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50743deb3ec6SMatthias Ringwald  * @param handle
50756b65794dSMilanka Ringwald  * @return index from le_device_db or -1 if not found/identified
50763deb3ec6SMatthias Ringwald  */
5077711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5078711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50793deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
50803deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
50813deb3ec6SMatthias Ringwald }
50823deb3ec6SMatthias Ringwald 
50838f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
508447ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
508547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
508647ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
508747ba4de1SMatthias Ringwald             return 0;
508847ba4de1SMatthias Ringwald         default:
50898f57b085SMatthias Ringwald             return 1;
50908f57b085SMatthias Ringwald     }
509147ba4de1SMatthias Ringwald }
5092d70217a2SMatthias Ringwald 
509333373e40SMatthias Ringwald static uint8_t own_address_type(void){
5094b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5095b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5096b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5097b95a5a35SMatthias Ringwald         default:
5098b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5099b95a5a35SMatthias Ringwald     }
510033373e40SMatthias Ringwald }
51018f57b085SMatthias Ringwald 
51023deb3ec6SMatthias Ringwald // GAP LE API
51033deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
51043deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51053deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5106b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
51078f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51083deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51093deb3ec6SMatthias Ringwald     gap_random_address_trigger();
51103deb3ec6SMatthias Ringwald }
51113deb3ec6SMatthias Ringwald 
51123deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
51133deb3ec6SMatthias Ringwald     return gap_random_adress_type;
51143deb3ec6SMatthias Ringwald }
51153deb3ec6SMatthias Ringwald 
51163deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
51173deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
51188f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
51193deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51203deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51213deb3ec6SMatthias Ringwald }
51223deb3ec6SMatthias Ringwald 
5123667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51248f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51256535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5126e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
51277e252622SMatthias Ringwald }
51287e252622SMatthias Ringwald 
5129d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51303deb3ec6SMatthias Ringwald /*
51313deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51323deb3ec6SMatthias Ringwald  * @param adv_int_min
51333deb3ec6SMatthias Ringwald  * @param adv_int_max
51343deb3ec6SMatthias Ringwald  * @param adv_type
51353deb3ec6SMatthias Ringwald  * @param direct_address_type
51363deb3ec6SMatthias Ringwald  * @param direct_address
51373deb3ec6SMatthias Ringwald  * @param channel_map
51383deb3ec6SMatthias Ringwald  * @param filter_policy
51393deb3ec6SMatthias Ringwald  *
51403deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51413deb3ec6SMatthias Ringwald  */
51423deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51433deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5144b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51453deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51463deb3ec6SMatthias Ringwald }
5147d70217a2SMatthias Ringwald #endif
5148dcd6c9b5SMatthias Ringwald 
5149dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5150dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5151dcd6c9b5SMatthias Ringwald      // wrong connection
5152dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5153dcd6c9b5SMatthias Ringwald     // already encrypted
5154dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5155dcd6c9b5SMatthias Ringwald     // irk status?
5156dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5157dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5158dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5159dcd6c9b5SMatthias Ringwald             return 0;
5160dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5161dcd6c9b5SMatthias Ringwald             break;
5162dcd6c9b5SMatthias Ringwald         default:
5163dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5164dcd6c9b5SMatthias Ringwald             return 1;
5165dcd6c9b5SMatthias Ringwald     }
5166f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5167f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5168b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5169b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5170b15d5ceaSMatthias Ringwald     } else {
5171dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5172dcd6c9b5SMatthias Ringwald     }
5173b15d5ceaSMatthias Ringwald }
51743cdbe9dbSMatthias Ringwald 
51753cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
51763cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51773cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
51783cdbe9dbSMatthias Ringwald #else
51793cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
51803cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
51813cdbe9dbSMatthias Ringwald #endif
51823cdbe9dbSMatthias Ringwald }
5183052bbdc5SMatthias Ringwald 
5184052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5185052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5186052bbdc5SMatthias Ringwald }
51874f384501SMatthias Ringwald 
51884f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
51894f384501SMatthias Ringwald     uint16_t i;
51904f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
51914f384501SMatthias Ringwald         bd_addr_t entry_address;
51924f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
51934f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
51944f384501SMatthias Ringwald         // skip unused entries
51954f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
51964f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
51974f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
51984f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
51994f384501SMatthias Ringwald #endif
52004f384501SMatthias Ringwald             le_device_db_remove(i);
52014f384501SMatthias Ringwald             break;
52024f384501SMatthias Ringwald         }
52034f384501SMatthias Ringwald     }
52044f384501SMatthias Ringwald }
5205