xref: /btstack/src/ble/sm.c (revision e91ddb40755e32b7f518eeedb40e9a37edf017f9)
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
233deb3ec6SMatthias Ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
243deb3ec6SMatthias Ringwald  * RINGWALD 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 
3853deb3ec6SMatthias Ringwald // @returns 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);
3893deb3ec6SMatthias Ringwald 
3903deb3ec6SMatthias Ringwald static void sm_run(void);
391711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle);
392711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle);
39377e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
39477e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type);
39577e2e5edSMatthias Ringwald #endif
3963deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other);
3973deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void);
398d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg);
399d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg);
400d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg);
401d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg);
402d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg);
403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg);
404d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg);
405d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg);
406d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg);
407d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg);
4082a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
409d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg);
410d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg);
4112a526f21SMatthias Ringwald #endif
412d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg);
413d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg);
414d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg);
415d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg);
416d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4176d80b495SMatthias 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));
41834b6528fSMatthias Ringwald static void sm_ec_generate_new_key(void);
4196ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg);
4206ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg);
4212a526f21SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method);
422d1a1f6a4SMatthias Ringwald #endif
4230ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason);
4243deb3ec6SMatthias Ringwald 
4253deb3ec6SMatthias Ringwald static void log_info_hex16(const char * name, uint16_t value){
4263deb3ec6SMatthias Ringwald     log_info("%-6s 0x%04x", name, value);
4273deb3ec6SMatthias Ringwald }
4283deb3ec6SMatthias Ringwald 
4291fbd72c5SMatthias Ringwald // static inline uint8_t sm_pairing_packet_get_code(sm_pairing_packet_t packet){
4301fbd72c5SMatthias Ringwald //     return packet[0];
4311fbd72c5SMatthias Ringwald // }
4321fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_io_capability(sm_pairing_packet_t packet){
4331fbd72c5SMatthias Ringwald     return packet[1];
4341fbd72c5SMatthias Ringwald }
4351fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_oob_data_flag(sm_pairing_packet_t packet){
4361fbd72c5SMatthias Ringwald     return packet[2];
4371fbd72c5SMatthias Ringwald }
4381fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_auth_req(sm_pairing_packet_t packet){
4391fbd72c5SMatthias Ringwald     return packet[3];
4401fbd72c5SMatthias Ringwald }
4411fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_max_encryption_key_size(sm_pairing_packet_t packet){
4421fbd72c5SMatthias Ringwald     return packet[4];
4431fbd72c5SMatthias Ringwald }
4441fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_initiator_key_distribution(sm_pairing_packet_t packet){
4451fbd72c5SMatthias Ringwald     return packet[5];
4461fbd72c5SMatthias Ringwald }
4471fbd72c5SMatthias Ringwald static inline uint8_t sm_pairing_packet_get_responder_key_distribution(sm_pairing_packet_t packet){
4481fbd72c5SMatthias Ringwald     return packet[6];
4491fbd72c5SMatthias Ringwald }
4501fbd72c5SMatthias Ringwald 
4511fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_code(sm_pairing_packet_t packet, uint8_t code){
4521fbd72c5SMatthias Ringwald     packet[0] = code;
4531fbd72c5SMatthias Ringwald }
4541fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_io_capability(sm_pairing_packet_t packet, uint8_t io_capability){
4551fbd72c5SMatthias Ringwald     packet[1] = io_capability;
4561fbd72c5SMatthias Ringwald }
4571fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_oob_data_flag(sm_pairing_packet_t packet, uint8_t oob_data_flag){
4581fbd72c5SMatthias Ringwald     packet[2] = oob_data_flag;
4591fbd72c5SMatthias Ringwald }
4601fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_auth_req(sm_pairing_packet_t packet, uint8_t auth_req){
4611fbd72c5SMatthias Ringwald     packet[3] = auth_req;
4621fbd72c5SMatthias Ringwald }
4631fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_max_encryption_key_size(sm_pairing_packet_t packet, uint8_t max_encryption_key_size){
4641fbd72c5SMatthias Ringwald     packet[4] = max_encryption_key_size;
4651fbd72c5SMatthias Ringwald }
4661fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_initiator_key_distribution(sm_pairing_packet_t packet, uint8_t initiator_key_distribution){
4671fbd72c5SMatthias Ringwald     packet[5] = initiator_key_distribution;
4681fbd72c5SMatthias Ringwald }
4691fbd72c5SMatthias Ringwald static inline void sm_pairing_packet_set_responder_key_distribution(sm_pairing_packet_t packet, uint8_t responder_key_distribution){
4701fbd72c5SMatthias Ringwald     packet[6] = responder_key_distribution;
4711fbd72c5SMatthias Ringwald }
4721fbd72c5SMatthias Ringwald 
4733deb3ec6SMatthias Ringwald // @returns 1 if all bytes are 0
4741979f09cSMatthias Ringwald static bool sm_is_null(uint8_t * data, int size){
4753deb3ec6SMatthias Ringwald     int i;
4763764b551SMatthias Ringwald     for (i=0; i < size ; i++){
47784c0c5c7SMatthias Ringwald         if (data[i] != 0) {
4781979f09cSMatthias Ringwald             return false;
47984c0c5c7SMatthias Ringwald         }
4803deb3ec6SMatthias Ringwald     }
4811979f09cSMatthias Ringwald     return true;
4823deb3ec6SMatthias Ringwald }
4833deb3ec6SMatthias Ringwald 
4841979f09cSMatthias Ringwald static bool sm_is_null_random(uint8_t random[8]){
4853764b551SMatthias Ringwald     return sm_is_null(random, 8);
4863764b551SMatthias Ringwald }
4873764b551SMatthias Ringwald 
4881979f09cSMatthias Ringwald static bool sm_is_null_key(uint8_t * key){
4893764b551SMatthias Ringwald     return sm_is_null(key, 16);
4903764b551SMatthias Ringwald }
4913764b551SMatthias Ringwald 
49270b44dd4SMatthias Ringwald // sm_trigger_run allows to schedule callback from main run loop // reduces stack depth
49370b44dd4SMatthias Ringwald static void sm_run_timer_handler(btstack_timer_source_t * ts){
49470b44dd4SMatthias Ringwald 	UNUSED(ts);
49570b44dd4SMatthias Ringwald 	sm_run();
49670b44dd4SMatthias Ringwald }
49770b44dd4SMatthias Ringwald static void sm_trigger_run(void){
4982d2d4d3cSMatthias Ringwald     if (!sm_initialized) return;
49984c0c5c7SMatthias Ringwald 	(void)btstack_run_loop_remove_timer(&sm_run_timer);
50070b44dd4SMatthias Ringwald 	btstack_run_loop_set_timer(&sm_run_timer, 0);
50170b44dd4SMatthias Ringwald 	btstack_run_loop_add_timer(&sm_run_timer);
50270b44dd4SMatthias Ringwald }
50370b44dd4SMatthias Ringwald 
5043deb3ec6SMatthias Ringwald // Key utils
5053deb3ec6SMatthias Ringwald static void sm_reset_tk(void){
5063deb3ec6SMatthias Ringwald     int i;
5073deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
5083deb3ec6SMatthias Ringwald         setup->sm_tk[i] = 0;
5093deb3ec6SMatthias Ringwald     }
5103deb3ec6SMatthias Ringwald }
5113deb3ec6SMatthias Ringwald 
5123deb3ec6SMatthias Ringwald // "For example, if a 128-bit encryption key is 0x123456789ABCDEF0123456789ABCDEF0
5133deb3ec6SMatthias Ringwald // and it is reduced to 7 octets (56 bits), then the resulting key is 0x0000000000000000003456789ABCDEF0.""
5143deb3ec6SMatthias Ringwald static void sm_truncate_key(sm_key_t key, int max_encryption_size){
5153deb3ec6SMatthias Ringwald     int i;
5163deb3ec6SMatthias Ringwald     for (i = max_encryption_size ; i < 16 ; i++){
5173deb3ec6SMatthias Ringwald         key[15-i] = 0;
5183deb3ec6SMatthias Ringwald     }
5193deb3ec6SMatthias Ringwald }
5203deb3ec6SMatthias Ringwald 
521899e6e02SMatthias Ringwald // ER / IR checks
52221045273SMatthias Ringwald static void sm_er_ir_set_default(void){
523899e6e02SMatthias Ringwald     int i;
524899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
525899e6e02SMatthias Ringwald         sm_persistent_er[i] = 0x30 + i;
526899e6e02SMatthias Ringwald         sm_persistent_ir[i] = 0x90 + i;
527899e6e02SMatthias Ringwald     }
528899e6e02SMatthias Ringwald }
529899e6e02SMatthias Ringwald 
530899e6e02SMatthias Ringwald static int sm_er_is_default(void){
531899e6e02SMatthias Ringwald     int i;
532899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
533899e6e02SMatthias Ringwald         if (sm_persistent_er[i] != (0x30+i)) return 0;
534899e6e02SMatthias Ringwald     }
535899e6e02SMatthias Ringwald     return 1;
536899e6e02SMatthias Ringwald }
537899e6e02SMatthias Ringwald 
538899e6e02SMatthias Ringwald static int sm_ir_is_default(void){
539899e6e02SMatthias Ringwald     int i;
540899e6e02SMatthias Ringwald     for (i=0;i<16;i++){
541899e6e02SMatthias Ringwald         if (sm_persistent_ir[i] != (0x90+i)) return 0;
542899e6e02SMatthias Ringwald     }
543899e6e02SMatthias Ringwald     return 1;
544899e6e02SMatthias Ringwald }
545899e6e02SMatthias Ringwald 
54673102768SMatthias Ringwald static void sm_dispatch_event(uint8_t packet_type, uint16_t channel, uint8_t * packet, uint16_t size){
54773102768SMatthias Ringwald     UNUSED(channel);
54873102768SMatthias Ringwald 
54973102768SMatthias Ringwald     // log event
55073102768SMatthias Ringwald     hci_dump_packet(packet_type, 1, packet, size);
55173102768SMatthias Ringwald     // dispatch to all event handlers
55273102768SMatthias Ringwald     btstack_linked_list_iterator_t it;
55373102768SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_event_handlers);
55473102768SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
55573102768SMatthias Ringwald         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
55673102768SMatthias Ringwald         entry->callback(packet_type, 0, packet, size);
55773102768SMatthias Ringwald     }
55873102768SMatthias Ringwald }
55973102768SMatthias Ringwald 
56073102768SMatthias 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){
56173102768SMatthias Ringwald     event[0] = type;
56273102768SMatthias Ringwald     event[1] = event_size - 2;
56373102768SMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
56473102768SMatthias Ringwald     event[4] = addr_type;
56573102768SMatthias Ringwald     reverse_bd_addr(address, &event[5]);
56673102768SMatthias Ringwald }
56773102768SMatthias Ringwald 
56873102768SMatthias Ringwald static void sm_notify_client_base(uint8_t type, hci_con_handle_t con_handle, uint8_t addr_type, bd_addr_t address){
56973102768SMatthias Ringwald     uint8_t event[11];
57073102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57173102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57273102768SMatthias Ringwald }
57373102768SMatthias Ringwald 
57473102768SMatthias 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){
57573102768SMatthias Ringwald     uint8_t event[15];
57673102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
57773102768SMatthias Ringwald     little_endian_store_32(event, 11, passkey);
57873102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
57973102768SMatthias Ringwald }
58073102768SMatthias Ringwald 
58173102768SMatthias 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){
58273102768SMatthias Ringwald     // fetch addr and addr type from db, only called for valid entries
58373102768SMatthias Ringwald     bd_addr_t identity_address;
58473102768SMatthias Ringwald     int identity_address_type;
58573102768SMatthias Ringwald     le_device_db_info(index, &identity_address_type, identity_address, NULL);
58673102768SMatthias Ringwald 
58773102768SMatthias Ringwald     uint8_t event[20];
58873102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
58973102768SMatthias Ringwald     event[11] = identity_address_type;
59073102768SMatthias Ringwald     reverse_bd_addr(identity_address, &event[12]);
59173102768SMatthias Ringwald     little_endian_store_16(event, 18, index);
59273102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, event, sizeof(event));
59373102768SMatthias Ringwald }
59473102768SMatthias Ringwald 
59573102768SMatthias 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){
59673102768SMatthias Ringwald     uint8_t event[12];
59773102768SMatthias Ringwald     sm_setup_event_base(event, sizeof(event), type, con_handle, addr_type, address);
59873102768SMatthias Ringwald     event[11] = status;
59973102768SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
60073102768SMatthias Ringwald }
60173102768SMatthias Ringwald 
60273102768SMatthias Ringwald 
60373102768SMatthias Ringwald static void sm_reencryption_started(sm_connection_t * sm_conn){
60473102768SMatthias Ringwald 
6053ab61f77SMatthias Ringwald     if (sm_conn->sm_reencryption_active) return;
6063ab61f77SMatthias Ringwald 
6077b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = true;
60873102768SMatthias Ringwald 
60973102768SMatthias Ringwald     int       identity_addr_type;
61073102768SMatthias Ringwald     bd_addr_t identity_addr;
6113c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6123c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
61373102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6143c0e26deSMatthias Ringwald     } else {
6153c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6163c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6173c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6183c0e26deSMatthias Ringwald     }
61973102768SMatthias Ringwald 
62073102768SMatthias Ringwald     sm_notify_client_base(SM_EVENT_REENCRYPTION_STARTED, sm_conn->sm_handle, identity_addr_type, identity_addr);
62173102768SMatthias Ringwald }
62273102768SMatthias Ringwald 
62373102768SMatthias Ringwald static void sm_reencryption_complete(sm_connection_t * sm_conn, uint8_t status){
62473102768SMatthias Ringwald 
62560be5b21SMatthias Ringwald     if (!sm_conn->sm_reencryption_active) return;
62660be5b21SMatthias Ringwald 
6277b001f4eSMatthias Ringwald     sm_conn->sm_reencryption_active = false;
62873102768SMatthias Ringwald 
62973102768SMatthias Ringwald     int       identity_addr_type;
63073102768SMatthias Ringwald     bd_addr_t identity_addr;
6313c0e26deSMatthias Ringwald     if (sm_conn->sm_le_db_index >= 0){
6323c0e26deSMatthias Ringwald         // fetch addr and addr type from db, only called for valid entries
63373102768SMatthias Ringwald         le_device_db_info(sm_conn->sm_le_db_index, &identity_addr_type, identity_addr, NULL);
6343c0e26deSMatthias Ringwald     } else {
6353c0e26deSMatthias Ringwald         // for legacy pairing with LTK re-construction, use current peer addr
6363c0e26deSMatthias Ringwald         identity_addr_type = sm_conn->sm_peer_addr_type;
6373c0e26deSMatthias Ringwald         memcpy(identity_addr, sm_conn->sm_peer_address, 6);
6383c0e26deSMatthias Ringwald     }
63973102768SMatthias Ringwald 
64073102768SMatthias Ringwald     sm_notify_client_status(SM_EVENT_REENCRYPTION_COMPLETE, sm_conn->sm_handle, identity_addr_type, identity_addr, status);
64173102768SMatthias Ringwald }
64273102768SMatthias Ringwald 
643d3c12277SMatthias Ringwald static void sm_pairing_started(sm_connection_t * sm_conn){
644d3c12277SMatthias Ringwald 
645d3c12277SMatthias Ringwald     if (sm_conn->sm_pairing_active) return;
646d3c12277SMatthias Ringwald 
647d3c12277SMatthias Ringwald     sm_conn->sm_pairing_active = true;
648d3c12277SMatthias Ringwald 
649d3c12277SMatthias Ringwald     uint8_t event[11];
650d3c12277SMatthias 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);
651d3c12277SMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
652d3c12277SMatthias Ringwald }
653d3c12277SMatthias Ringwald 
6540ccf6c9cSMatthias Ringwald static void sm_pairing_complete(sm_connection_t * sm_conn, uint8_t status, uint8_t reason){
655f61072f5SMatthias Ringwald 
656d77906ffSMatthias Ringwald     if (!sm_conn->sm_pairing_active) return;
657d77906ffSMatthias Ringwald 
65869f82ad8SMatthias Ringwald     sm_conn->sm_pairing_active = false;
65969f82ad8SMatthias Ringwald 
6600ccf6c9cSMatthias Ringwald     uint8_t event[13];
6610ccf6c9cSMatthias 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);
6620ccf6c9cSMatthias Ringwald     event[11] = status;
6630ccf6c9cSMatthias Ringwald     event[12] = reason;
6640ccf6c9cSMatthias Ringwald     sm_dispatch_event(HCI_EVENT_PACKET, 0, (uint8_t*) &event, sizeof(event));
6650ccf6c9cSMatthias Ringwald }
6660ccf6c9cSMatthias Ringwald 
6673deb3ec6SMatthias Ringwald // SMP Timeout implementation
6683deb3ec6SMatthias Ringwald 
6693deb3ec6SMatthias Ringwald // Upon transmission of the Pairing Request command or reception of the Pairing Request command,
6703deb3ec6SMatthias Ringwald // the Security Manager Timer shall be reset and started.
6713deb3ec6SMatthias Ringwald //
6723deb3ec6SMatthias Ringwald // The Security Manager Timer shall be reset when an L2CAP SMP command is queued for transmission.
6733deb3ec6SMatthias Ringwald //
6743deb3ec6SMatthias Ringwald // If the Security Manager Timer reaches 30 seconds, the procedure shall be considered to have failed,
6753deb3ec6SMatthias Ringwald // and the local higher layer shall be notified. No further SMP commands shall be sent over the L2CAP
6763deb3ec6SMatthias Ringwald // Security Manager Channel. A new SM procedure shall only be performed when a new physical link has been
6773deb3ec6SMatthias Ringwald // established.
6783deb3ec6SMatthias Ringwald 
679ec820d77SMatthias Ringwald static void sm_timeout_handler(btstack_timer_source_t * timer){
6803deb3ec6SMatthias Ringwald     log_info("SM timeout");
681c5b64319SMatthias Ringwald     sm_connection_t * sm_conn = (sm_connection_t*) btstack_run_loop_get_timer_context(timer);
6823deb3ec6SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_TIMEOUT;
68368a18fb9SMatthias Ringwald     sm_reencryption_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT);
6840ccf6c9cSMatthias Ringwald     sm_pairing_complete(sm_conn, ERROR_CODE_CONNECTION_TIMEOUT, 0);
6853deb3ec6SMatthias Ringwald     sm_done_for_handle(sm_conn->sm_handle);
6863deb3ec6SMatthias Ringwald 
6873deb3ec6SMatthias Ringwald     // trigger handling of next ready connection
6883deb3ec6SMatthias Ringwald     sm_run();
6893deb3ec6SMatthias Ringwald }
6903deb3ec6SMatthias Ringwald static void sm_timeout_start(sm_connection_t * sm_conn){
691528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
69291a977e8SMatthias Ringwald     btstack_run_loop_set_timer_context(&setup->sm_timeout, sm_conn);
693528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&setup->sm_timeout, sm_timeout_handler);
694528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&setup->sm_timeout, 30000); // 30 seconds sm timeout
695528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&setup->sm_timeout);
6963deb3ec6SMatthias Ringwald }
6973deb3ec6SMatthias Ringwald static void sm_timeout_stop(void){
698528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&setup->sm_timeout);
6993deb3ec6SMatthias Ringwald }
7003deb3ec6SMatthias Ringwald static void sm_timeout_reset(sm_connection_t * sm_conn){
7013deb3ec6SMatthias Ringwald     sm_timeout_stop();
7023deb3ec6SMatthias Ringwald     sm_timeout_start(sm_conn);
7033deb3ec6SMatthias Ringwald }
7043deb3ec6SMatthias Ringwald 
7053deb3ec6SMatthias Ringwald // end of sm timeout
7063deb3ec6SMatthias Ringwald 
7073deb3ec6SMatthias Ringwald // GAP Random Address updates
7083deb3ec6SMatthias Ringwald static gap_random_address_type_t gap_random_adress_type;
709ec820d77SMatthias Ringwald static btstack_timer_source_t gap_random_address_update_timer;
7103deb3ec6SMatthias Ringwald static uint32_t gap_random_adress_update_period;
7113deb3ec6SMatthias Ringwald 
7123deb3ec6SMatthias Ringwald static void gap_random_address_trigger(void){
713899e6e02SMatthias Ringwald     log_info("gap_random_address_trigger, state %u", rau_state);
714d1a1f6a4SMatthias Ringwald     if (rau_state != RAU_IDLE) return;
715fbd4e238SMatthias Ringwald     rau_state = RAU_GET_RANDOM;
71670b44dd4SMatthias Ringwald     sm_trigger_run();
7173deb3ec6SMatthias Ringwald }
7183deb3ec6SMatthias Ringwald 
719ec820d77SMatthias Ringwald static void gap_random_address_update_handler(btstack_timer_source_t * timer){
7209ec2630cSMatthias Ringwald     UNUSED(timer);
7219ec2630cSMatthias Ringwald 
7223deb3ec6SMatthias Ringwald     log_info("GAP Random Address Update due");
723528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
724528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7253deb3ec6SMatthias Ringwald     gap_random_address_trigger();
7263deb3ec6SMatthias Ringwald }
7273deb3ec6SMatthias Ringwald 
7283deb3ec6SMatthias Ringwald static void gap_random_address_update_start(void){
729528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&gap_random_address_update_timer, gap_random_address_update_handler);
730528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&gap_random_address_update_timer, gap_random_adress_update_period);
731528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&gap_random_address_update_timer);
7323deb3ec6SMatthias Ringwald }
7333deb3ec6SMatthias Ringwald 
7343deb3ec6SMatthias Ringwald static void gap_random_address_update_stop(void){
735528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&gap_random_address_update_timer);
7363deb3ec6SMatthias Ringwald }
7373deb3ec6SMatthias Ringwald 
7383deb3ec6SMatthias Ringwald // ah(k,r) helper
7393deb3ec6SMatthias Ringwald // r = padding || r
7403deb3ec6SMatthias Ringwald // r - 24 bit value
7414a6806f3SMatthias Ringwald static void sm_ah_r_prime(uint8_t r[3], uint8_t * r_prime){
7423deb3ec6SMatthias Ringwald     // r'= padding || r
7433deb3ec6SMatthias Ringwald     memset(r_prime, 0, 16);
7446535961aSMatthias Ringwald     (void)memcpy(&r_prime[13], r, 3);
7453deb3ec6SMatthias Ringwald }
7463deb3ec6SMatthias Ringwald 
7473deb3ec6SMatthias Ringwald // d1 helper
7483deb3ec6SMatthias Ringwald // d' = padding || r || d
7493deb3ec6SMatthias Ringwald // d,r - 16 bit values
7504a6806f3SMatthias Ringwald static void sm_d1_d_prime(uint16_t d, uint16_t r, uint8_t * d1_prime){
7513deb3ec6SMatthias Ringwald     // d'= padding || r || d
7523deb3ec6SMatthias Ringwald     memset(d1_prime, 0, 16);
753f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 12, r);
754f8fbdce0SMatthias Ringwald     big_endian_store_16(d1_prime, 14, d);
7553deb3ec6SMatthias Ringwald }
7563deb3ec6SMatthias Ringwald 
7573deb3ec6SMatthias Ringwald // calculate arguments for first AES128 operation in C1 function
7584a6806f3SMatthias 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){
7593deb3ec6SMatthias Ringwald 
7603deb3ec6SMatthias Ringwald     // p1 = pres || preq || rat’ || iat’
7613deb3ec6SMatthias Ringwald     // "The octet of iat’ becomes the least significant octet of p1 and the most signifi-
7623deb3ec6SMatthias Ringwald     // cant octet of pres becomes the most significant octet of p1.
7633deb3ec6SMatthias Ringwald     // For example, if the 8-bit iat’ is 0x01, the 8-bit rat’ is 0x00, the 56-bit preq
7643deb3ec6SMatthias Ringwald     // is 0x07071000000101 and the 56 bit pres is 0x05000800000302 then
7653deb3ec6SMatthias Ringwald     // p1 is 0x05000800000302070710000001010001."
7663deb3ec6SMatthias Ringwald 
7673deb3ec6SMatthias Ringwald     sm_key_t p1;
7689c80e4ccSMatthias Ringwald     reverse_56(pres, &p1[0]);
7699c80e4ccSMatthias Ringwald     reverse_56(preq, &p1[7]);
7703deb3ec6SMatthias Ringwald     p1[14] = rat;
7713deb3ec6SMatthias Ringwald     p1[15] = iat;
7728314c363SMatthias Ringwald     log_info_key("p1", p1);
7738314c363SMatthias Ringwald     log_info_key("r", r);
7743deb3ec6SMatthias Ringwald 
7753deb3ec6SMatthias Ringwald     // t1 = r xor p1
7763deb3ec6SMatthias Ringwald     int i;
7773deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
7783deb3ec6SMatthias Ringwald         t1[i] = r[i] ^ p1[i];
7793deb3ec6SMatthias Ringwald     }
7808314c363SMatthias Ringwald     log_info_key("t1", t1);
7813deb3ec6SMatthias Ringwald }
7823deb3ec6SMatthias Ringwald 
7833deb3ec6SMatthias Ringwald // calculate arguments for second AES128 operation in C1 function
7844a6806f3SMatthias Ringwald static void sm_c1_t3(sm_key_t t2, bd_addr_t ia, bd_addr_t ra, uint8_t * t3){
7853deb3ec6SMatthias Ringwald      // p2 = padding || ia || ra
7863deb3ec6SMatthias Ringwald     // "The least significant octet of ra becomes the least significant octet of p2 and
7873deb3ec6SMatthias Ringwald     // the most significant octet of padding becomes the most significant octet of p2.
7883deb3ec6SMatthias Ringwald     // For example, if 48-bit ia is 0xA1A2A3A4A5A6 and the 48-bit ra is
7893deb3ec6SMatthias Ringwald     // 0xB1B2B3B4B5B6 then p2 is 0x00000000A1A2A3A4A5A6B1B2B3B4B5B6.
7903deb3ec6SMatthias Ringwald 
7913deb3ec6SMatthias Ringwald     sm_key_t p2;
7923deb3ec6SMatthias Ringwald     memset(p2, 0, 16);
7936535961aSMatthias Ringwald     (void)memcpy(&p2[4], ia, 6);
7946535961aSMatthias Ringwald     (void)memcpy(&p2[10], ra, 6);
7958314c363SMatthias Ringwald     log_info_key("p2", p2);
7963deb3ec6SMatthias Ringwald 
7973deb3ec6SMatthias Ringwald     // c1 = e(k, t2_xor_p2)
7983deb3ec6SMatthias Ringwald     int i;
7993deb3ec6SMatthias Ringwald     for (i=0;i<16;i++){
8003deb3ec6SMatthias Ringwald         t3[i] = t2[i] ^ p2[i];
8013deb3ec6SMatthias Ringwald     }
8028314c363SMatthias Ringwald     log_info_key("t3", t3);
8033deb3ec6SMatthias Ringwald }
8043deb3ec6SMatthias Ringwald 
8054a6806f3SMatthias Ringwald static void sm_s1_r_prime(sm_key_t r1, sm_key_t r2, uint8_t * r_prime){
8068314c363SMatthias Ringwald     log_info_key("r1", r1);
8078314c363SMatthias Ringwald     log_info_key("r2", r2);
8086535961aSMatthias Ringwald     (void)memcpy(&r_prime[8], &r2[8], 8);
8096535961aSMatthias Ringwald     (void)memcpy(&r_prime[0], &r1[8], 8);
8103deb3ec6SMatthias Ringwald }
8113deb3ec6SMatthias Ringwald 
812fbe050beSMatthias Ringwald 
8133deb3ec6SMatthias Ringwald // decide on stk generation based on
8143deb3ec6SMatthias Ringwald // - pairing request
8153deb3ec6SMatthias Ringwald // - io capabilities
8163deb3ec6SMatthias Ringwald // - OOB data availability
8173deb3ec6SMatthias Ringwald static void sm_setup_tk(void){
8183deb3ec6SMatthias Ringwald 
8198334d3d8SMatthias Ringwald     // horizontal: initiator capabilities
8208334d3d8SMatthias Ringwald     // vertial:    responder capabilities
8218334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method [5] [5] = {
8228334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8238334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT },
8248334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8258334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,       JUST_WORKS,      JUST_WORKS,    JUST_WORKS    },
8268334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,    PK_INIT_INPUT,   JUST_WORKS,    PK_RESP_INPUT },
8278334d3d8SMatthias Ringwald     };
8288334d3d8SMatthias Ringwald 
8298334d3d8SMatthias Ringwald     // uses numeric comparison if one side has DisplayYesNo and KeyboardDisplay combinations
8308334d3d8SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
8318334d3d8SMatthias Ringwald     static const stk_generation_method_t stk_generation_method_with_secure_connection[5][5] = {
8328334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         PK_INIT_INPUT,   JUST_WORKS,    PK_INIT_INPUT      },
8338334d3d8SMatthias Ringwald             { JUST_WORKS,      NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8348334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   PK_RESP_INPUT,      PK_BOTH_INPUT,   JUST_WORKS,    PK_RESP_INPUT      },
8358334d3d8SMatthias Ringwald             { JUST_WORKS,      JUST_WORKS,         JUST_WORKS,      JUST_WORKS,    JUST_WORKS         },
8368334d3d8SMatthias Ringwald             { PK_RESP_INPUT,   NUMERIC_COMPARISON, PK_INIT_INPUT,   JUST_WORKS,    NUMERIC_COMPARISON },
8378334d3d8SMatthias Ringwald     };
8388334d3d8SMatthias Ringwald #endif
8398334d3d8SMatthias Ringwald 
8403deb3ec6SMatthias Ringwald     // default: just works
8413deb3ec6SMatthias Ringwald     setup->sm_stk_generation_method = JUST_WORKS;
8423deb3ec6SMatthias Ringwald 
84327c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
84427c32905SMatthias Ringwald     setup->sm_use_secure_connections = ( sm_pairing_packet_get_auth_req(setup->sm_m_preq)
84527c32905SMatthias Ringwald                                        & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
8464ea43905SMatthias Ringwald                                        & SM_AUTHREQ_SECURE_CONNECTION ) != 0u;
84727c32905SMatthias Ringwald #else
84827c32905SMatthias Ringwald     setup->sm_use_secure_connections = 0;
84927c32905SMatthias Ringwald #endif
85098d95509SMatthias Ringwald     log_info("Secure pairing: %u", setup->sm_use_secure_connections);
85127c32905SMatthias Ringwald 
85265a9a04eSMatthias Ringwald 
85365a9a04eSMatthias Ringwald     // decide if OOB will be used based on SC vs. Legacy and oob flags
8541979f09cSMatthias Ringwald     bool use_oob;
85565a9a04eSMatthias Ringwald     if (setup->sm_use_secure_connections){
85665a9a04eSMatthias Ringwald         // In LE Secure Connections pairing, the out of band method is used if at least
85765a9a04eSMatthias Ringwald         // one device has the peer device's out of band authentication data available.
8581979f09cSMatthias 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;
85965a9a04eSMatthias Ringwald     } else {
86065a9a04eSMatthias Ringwald         // In LE legacy pairing, the out of band method is used if both the devices have
86165a9a04eSMatthias Ringwald         // the other device's out of band authentication data available.
8621979f09cSMatthias 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;
86365a9a04eSMatthias Ringwald     }
86465a9a04eSMatthias Ringwald     if (use_oob){
86565a9a04eSMatthias Ringwald         log_info("SM: have OOB data");
86665a9a04eSMatthias Ringwald         log_info_key("OOB", setup->sm_tk);
86765a9a04eSMatthias Ringwald         setup->sm_stk_generation_method = OOB;
86865a9a04eSMatthias Ringwald         return;
86965a9a04eSMatthias Ringwald     }
87065a9a04eSMatthias Ringwald 
87127c32905SMatthias Ringwald     // If both devices have not set the MITM option in the Authentication Requirements
87227c32905SMatthias Ringwald     // Flags, then the IO capabilities shall be ignored and the Just Works association
87327c32905SMatthias Ringwald     // model shall be used.
8744ea43905SMatthias Ringwald     if (((sm_pairing_packet_get_auth_req(setup->sm_m_preq) & SM_AUTHREQ_MITM_PROTECTION) == 0u)
8754ea43905SMatthias Ringwald         &&  ((sm_pairing_packet_get_auth_req(setup->sm_s_pres) & SM_AUTHREQ_MITM_PROTECTION) == 0u)){
87627c32905SMatthias Ringwald         log_info("SM: MITM not required by both -> JUST WORKS");
87727c32905SMatthias Ringwald         return;
87827c32905SMatthias Ringwald     }
87927c32905SMatthias Ringwald 
8803deb3ec6SMatthias Ringwald     // Reset TK as it has been setup in sm_init_setup
8813deb3ec6SMatthias Ringwald     sm_reset_tk();
8823deb3ec6SMatthias Ringwald 
8833deb3ec6SMatthias Ringwald     // Also use just works if unknown io capabilites
8848da2e96dSMatthias 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)){
8853deb3ec6SMatthias Ringwald         return;
8863deb3ec6SMatthias Ringwald     }
8873deb3ec6SMatthias Ringwald 
8883deb3ec6SMatthias Ringwald     // Otherwise the IO capabilities of the devices shall be used to determine the
8893deb3ec6SMatthias Ringwald     // pairing method as defined in Table 2.4.
89027c32905SMatthias Ringwald     // see http://stackoverflow.com/a/1052837/393697 for how to specify pointer to 2-dimensional array
89127c32905SMatthias Ringwald     const stk_generation_method_t (*generation_method)[5] = stk_generation_method;
89227c32905SMatthias Ringwald 
89327c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
894c6b7cbd9SMatthias Ringwald     // table not define by default
89527c32905SMatthias Ringwald     if (setup->sm_use_secure_connections){
89627c32905SMatthias Ringwald         generation_method = stk_generation_method_with_secure_connection;
89727c32905SMatthias Ringwald     }
89827c32905SMatthias Ringwald #endif
89927c32905SMatthias 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)];
90027c32905SMatthias Ringwald 
9013deb3ec6SMatthias Ringwald     log_info("sm_setup_tk: master io cap: %u, slave io cap: %u -> method %u",
9021ad129beSMatthias 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);
9033deb3ec6SMatthias Ringwald }
9043deb3ec6SMatthias Ringwald 
9053deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_set(uint8_t key_set){
9063deb3ec6SMatthias Ringwald     int flags = 0;
9073deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ENC_KEY){
9083deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
9093deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
9103deb3ec6SMatthias Ringwald     }
9113deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_ID_KEY){
9123deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
9133deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
9143deb3ec6SMatthias Ringwald     }
9153deb3ec6SMatthias Ringwald     if (key_set & SM_KEYDIST_SIGN){
9163deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
9173deb3ec6SMatthias Ringwald     }
9183deb3ec6SMatthias Ringwald     return flags;
9193deb3ec6SMatthias Ringwald }
9203deb3ec6SMatthias Ringwald 
9219a90d41aSMatthias Ringwald static void sm_setup_key_distribution(uint8_t keys_to_send, uint8_t keys_to_receive){
9223deb3ec6SMatthias Ringwald     setup->sm_key_distribution_received_set = 0;
9239a90d41aSMatthias Ringwald     setup->sm_key_distribution_expected_set = sm_key_distribution_flags_for_set(keys_to_receive);
9249a90d41aSMatthias Ringwald     setup->sm_key_distribution_send_set = sm_key_distribution_flags_for_set(keys_to_send);
925715a43d1SMatthias Ringwald     setup->sm_key_distribution_sent_set = 0;
9269790be5fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
927715a43d1SMatthias Ringwald     setup->sm_le_device_index = -1;
9289790be5fSMatthias Ringwald #endif
9293deb3ec6SMatthias Ringwald }
9303deb3ec6SMatthias Ringwald 
9313deb3ec6SMatthias Ringwald // CSRK Key Lookup
9323deb3ec6SMatthias Ringwald 
9333deb3ec6SMatthias Ringwald 
9343deb3ec6SMatthias Ringwald static int sm_address_resolution_idle(void){
9353deb3ec6SMatthias Ringwald     return sm_address_resolution_mode == ADDRESS_RESOLUTION_IDLE;
9363deb3ec6SMatthias Ringwald }
9373deb3ec6SMatthias Ringwald 
938711e6c80SMatthias 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){
9396535961aSMatthias Ringwald     (void)memcpy(sm_address_resolution_address, addr, 6);
9403deb3ec6SMatthias Ringwald     sm_address_resolution_addr_type = addr_type;
9413deb3ec6SMatthias Ringwald     sm_address_resolution_test = 0;
9423deb3ec6SMatthias Ringwald     sm_address_resolution_mode = mode;
9433deb3ec6SMatthias Ringwald     sm_address_resolution_context = context;
944711e6c80SMatthias Ringwald     sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_STARTED, con_handle, addr_type, addr);
9453deb3ec6SMatthias Ringwald }
9463deb3ec6SMatthias Ringwald 
9473deb3ec6SMatthias Ringwald int sm_address_resolution_lookup(uint8_t address_type, bd_addr_t address){
9483deb3ec6SMatthias Ringwald     // check if already in list
949665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
9503deb3ec6SMatthias Ringwald     sm_lookup_entry_t * entry;
951665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &sm_address_resolution_general_queue);
952665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
953665d90f2SMatthias Ringwald         entry = (sm_lookup_entry_t *) btstack_linked_list_iterator_next(&it);
9543deb3ec6SMatthias Ringwald         if (entry->address_type != address_type) continue;
9553deb3ec6SMatthias Ringwald         if (memcmp(entry->address, address, 6))  continue;
9563deb3ec6SMatthias Ringwald         // already in list
9573deb3ec6SMatthias Ringwald         return BTSTACK_BUSY;
9583deb3ec6SMatthias Ringwald     }
9593deb3ec6SMatthias Ringwald     entry = btstack_memory_sm_lookup_entry_get();
9603deb3ec6SMatthias Ringwald     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
9613deb3ec6SMatthias Ringwald     entry->address_type = (bd_addr_type_t) address_type;
9626535961aSMatthias Ringwald     (void)memcpy(entry->address, address, 6);
963665d90f2SMatthias Ringwald     btstack_linked_list_add(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
96470b44dd4SMatthias Ringwald     sm_trigger_run();
9653deb3ec6SMatthias Ringwald     return 0;
9663deb3ec6SMatthias Ringwald }
9673deb3ec6SMatthias Ringwald 
968d1a1f6a4SMatthias Ringwald // CMAC calculation using AES Engineq
969d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
970514d35fcSMatthias Ringwald 
971d1a1f6a4SMatthias Ringwald static void sm_cmac_done_trampoline(void * arg){
972d1a1f6a4SMatthias Ringwald     UNUSED(arg);
973d1a1f6a4SMatthias Ringwald     sm_cmac_active = 0;
974d1a1f6a4SMatthias Ringwald     (*sm_cmac_done_callback)(sm_cmac_hash);
97570b44dd4SMatthias Ringwald     sm_trigger_run();
9763deb3ec6SMatthias Ringwald }
977514d35fcSMatthias Ringwald 
9784dfd504aSMatthias Ringwald int sm_cmac_ready(void){
9794ea43905SMatthias Ringwald     return sm_cmac_active == 0u;
9803deb3ec6SMatthias Ringwald }
9816d80b495SMatthias Ringwald #endif
9823deb3ec6SMatthias Ringwald 
9836d80b495SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
984514d35fcSMatthias Ringwald // generic cmac calculation
985d1a1f6a4SMatthias 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)){
986d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
987d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
988d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_message(&sm_cmac_request, key, message_len, message, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
9893deb3ec6SMatthias Ringwald }
9907a766ebfSMatthias Ringwald #endif
9913deb3ec6SMatthias Ringwald 
992514d35fcSMatthias Ringwald // cmac for ATT Message signing
9937a766ebfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
994d1a1f6a4SMatthias Ringwald 
995d1a1f6a4SMatthias 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)){
996d1a1f6a4SMatthias Ringwald     sm_cmac_active = 1;
997d1a1f6a4SMatthias Ringwald     sm_cmac_done_callback = done_callback;
998d1a1f6a4SMatthias Ringwald     btstack_crypto_aes128_cmac_generator(&sm_cmac_request, key, message_len, get_byte_callback, sm_cmac_hash, sm_cmac_done_trampoline, NULL);
999d1a1f6a4SMatthias Ringwald }
1000d1a1f6a4SMatthias Ringwald 
10014dfd504aSMatthias Ringwald static uint8_t sm_cmac_signed_write_message_get_byte(uint16_t offset){
1002d1a1f6a4SMatthias Ringwald     if (offset >= sm_cmac_signed_write_message_len) {
1003d1a1f6a4SMatthias Ringwald         log_error("sm_cmac_signed_write_message_get_byte. out of bounds, access %u, len %u", offset, sm_cmac_signed_write_message_len);
10044dfd504aSMatthias Ringwald         return 0;
10054dfd504aSMatthias Ringwald     }
10064dfd504aSMatthias Ringwald 
1007d1a1f6a4SMatthias Ringwald     offset = sm_cmac_signed_write_message_len - 1 - offset;
10084dfd504aSMatthias Ringwald 
1009d1a1f6a4SMatthias Ringwald     // sm_cmac_signed_write_header[3] | message[] | sm_cmac_signed_write_sign_counter[4]
10104dfd504aSMatthias Ringwald     if (offset < 3){
1011d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_header[offset];
10124dfd504aSMatthias Ringwald     }
1013d1a1f6a4SMatthias Ringwald     int actual_message_len_incl_header = sm_cmac_signed_write_message_len - 4;
10144dfd504aSMatthias Ringwald     if (offset <  actual_message_len_incl_header){
1015d1a1f6a4SMatthias Ringwald         return sm_cmac_signed_write_message[offset - 3];
10164dfd504aSMatthias Ringwald     }
1017d1a1f6a4SMatthias Ringwald     return sm_cmac_signed_write_sign_counter[offset - actual_message_len_incl_header];
10184dfd504aSMatthias Ringwald }
10194dfd504aSMatthias Ringwald 
10204dfd504aSMatthias 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)){
1021514d35fcSMatthias Ringwald     // ATT Message Signing
1022d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_header[0] = opcode;
1023d1a1f6a4SMatthias Ringwald     little_endian_store_16(sm_cmac_signed_write_header, 1, con_handle);
1024d1a1f6a4SMatthias Ringwald     little_endian_store_32(sm_cmac_signed_write_sign_counter, 0, sign_counter);
1025514d35fcSMatthias Ringwald     uint16_t total_message_len = 3 + message_len + 4;  // incl. virtually prepended att opcode, handle and appended sign_counter in LE
1026d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message     = message;
1027d1a1f6a4SMatthias Ringwald     sm_cmac_signed_write_message_len = total_message_len;
1028d1a1f6a4SMatthias Ringwald     sm_cmac_generator_start(k, total_message_len, &sm_cmac_signed_write_message_get_byte, done_handler);
10293deb3ec6SMatthias Ringwald }
10307a766ebfSMatthias Ringwald #endif
10313deb3ec6SMatthias Ringwald 
10323deb3ec6SMatthias Ringwald static void sm_trigger_user_response(sm_connection_t * sm_conn){
1033446a8c36SMatthias Ringwald     // notify client for: JUST WORKS confirm, Numeric comparison confirm, PASSKEY display or input
10343deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_IDLE;
1035d77906ffSMatthias Ringwald     sm_conn->sm_pairing_active = true;
10363deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
10373deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
103842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
10393deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10405611a760SMatthias 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);
10413deb3ec6SMatthias Ringwald             } else {
1042c9b8fdd9SMatthias 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));
10433deb3ec6SMatthias Ringwald             }
10443deb3ec6SMatthias Ringwald             break;
10453deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
104642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1047c9b8fdd9SMatthias 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));
10483deb3ec6SMatthias Ringwald             } else {
10493deb3ec6SMatthias Ringwald                 setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10505611a760SMatthias 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);
10513deb3ec6SMatthias Ringwald             }
10523deb3ec6SMatthias Ringwald             break;
105347fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
10543deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10555611a760SMatthias 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);
10563deb3ec6SMatthias Ringwald             break;
105747fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
1058446a8c36SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
1059c8c46d51SMatthias 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));
106027c32905SMatthias Ringwald             break;
10613deb3ec6SMatthias Ringwald         case JUST_WORKS:
10623deb3ec6SMatthias Ringwald             setup->sm_user_response = SM_USER_RESPONSE_PENDING;
10635611a760SMatthias 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);
10643deb3ec6SMatthias Ringwald             break;
10653deb3ec6SMatthias Ringwald         case OOB:
10663deb3ec6SMatthias Ringwald             // client already provided OOB data, let's skip notification.
10673deb3ec6SMatthias Ringwald             break;
10687bbeb3adSMilanka Ringwald         default:
10697bbeb3adSMilanka Ringwald             btstack_assert(false);
10707bbeb3adSMilanka Ringwald             break;
10713deb3ec6SMatthias Ringwald     }
10723deb3ec6SMatthias Ringwald }
10733deb3ec6SMatthias Ringwald 
107461d1a45eSMatthias Ringwald static bool sm_key_distribution_all_received(void) {
1075b2296177SMatthias Ringwald     log_debug("sm_key_distribution_all_received: received 0x%02x, expecting 0x%02x", setup->sm_key_distribution_received_set, bution_expected_set);
1076b2296177SMatthias Ringwald     return (setup->sm_key_distribution_expected_set & setup->sm_key_distribution_received_set) == setup->sm_key_distribution_expected_set;
10773deb3ec6SMatthias Ringwald }
10783deb3ec6SMatthias Ringwald 
1079711e6c80SMatthias Ringwald static void sm_done_for_handle(hci_con_handle_t con_handle){
10807149bde5SMatthias Ringwald     if (sm_active_connection_handle == con_handle){
10813deb3ec6SMatthias Ringwald         sm_timeout_stop();
10827149bde5SMatthias Ringwald         sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
1083711e6c80SMatthias Ringwald         log_info("sm: connection 0x%x released setup context", con_handle);
1084c085d9ffSMatthias Ringwald 
1085c085d9ffSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1086c085d9ffSMatthias Ringwald         // generate new ec key after each pairing (that used it)
1087c085d9ffSMatthias Ringwald         if (setup->sm_use_secure_connections){
1088c085d9ffSMatthias Ringwald             sm_ec_generate_new_key();
1089c085d9ffSMatthias Ringwald         }
1090c085d9ffSMatthias Ringwald #endif
10913deb3ec6SMatthias Ringwald     }
10923deb3ec6SMatthias Ringwald }
10933deb3ec6SMatthias Ringwald 
10947d1c0c3aSMatthias Ringwald static void sm_master_pairing_success(sm_connection_t *connection) {// master -> all done
10951dca9d8aSMatthias Ringwald     connection->sm_engine_state = SM_INITIATOR_CONNECTED;
10960ccf6c9cSMatthias Ringwald     sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
10971dca9d8aSMatthias Ringwald     sm_done_for_handle(connection->sm_handle);
10981dca9d8aSMatthias Ringwald }
10991dca9d8aSMatthias Ringwald 
11003deb3ec6SMatthias Ringwald static int sm_key_distribution_flags_for_auth_req(void){
1101bb09604fSMatthias Ringwald 
1102bb09604fSMatthias Ringwald     int flags = SM_KEYDIST_ID_KEY;
11033deb3ec6SMatthias Ringwald     if (sm_auth_req & SM_AUTHREQ_BONDING){
1104bb09604fSMatthias Ringwald         // encryption and signing information only if bonding requested
11053deb3ec6SMatthias Ringwald         flags |= SM_KEYDIST_ENC_KEY;
1106bb09604fSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
1107bb09604fSMatthias Ringwald         flags |= SM_KEYDIST_SIGN;
1108bb09604fSMatthias Ringwald #endif
11097ece0eaaSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
11107ece0eaaSMatthias Ringwald         // LinkKey for CTKD requires SC
11117ece0eaaSMatthias Ringwald         if (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION){
11127ece0eaaSMatthias Ringwald         	flags |= SM_KEYDIST_LINK_KEY;
11137ece0eaaSMatthias Ringwald         }
11147ece0eaaSMatthias Ringwald #endif
11153deb3ec6SMatthias Ringwald     }
11163deb3ec6SMatthias Ringwald     return flags;
11173deb3ec6SMatthias Ringwald }
11183deb3ec6SMatthias Ringwald 
1119d7471931SMatthias Ringwald static void sm_reset_setup(void){
11203deb3ec6SMatthias Ringwald     // fill in sm setup
1121901c000fSMatthias Ringwald     setup->sm_state_vars = 0;
1122dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = 0;
1123d0ea782aSMatthias Ringwald     setup->sm_have_oob_data = 0;
11243deb3ec6SMatthias Ringwald     sm_reset_tk();
1125d7471931SMatthias Ringwald }
1126d7471931SMatthias Ringwald 
1127d7471931SMatthias Ringwald static void sm_init_setup(sm_connection_t * sm_conn){
1128d7471931SMatthias Ringwald     // fill in sm setup
11293deb3ec6SMatthias Ringwald     setup->sm_peer_addr_type = sm_conn->sm_peer_addr_type;
11306535961aSMatthias Ringwald     (void)memcpy(setup->sm_peer_address, sm_conn->sm_peer_address, 6);
11313deb3ec6SMatthias Ringwald 
1132a680ba6bSMatthias Ringwald     // query client for Legacy Pairing OOB data
11339305033eSMatthias Ringwald     if (sm_get_oob_data != NULL) {
1134a680ba6bSMatthias Ringwald         setup->sm_have_oob_data = (*sm_get_oob_data)(sm_conn->sm_peer_addr_type, sm_conn->sm_peer_address, setup->sm_tk);
11353deb3ec6SMatthias Ringwald     }
11363deb3ec6SMatthias Ringwald 
1137a680ba6bSMatthias Ringwald     // if available and SC supported, also ask for SC OOB Data
1138a680ba6bSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11394acf7b7bSMatthias Ringwald     memset(setup->sm_ra, 0, 16);
11404acf7b7bSMatthias Ringwald     memset(setup->sm_rb, 0, 16);
1141a680ba6bSMatthias Ringwald     if (setup->sm_have_oob_data && (sm_auth_req & SM_AUTHREQ_SECURE_CONNECTION)){
11429305033eSMatthias Ringwald         if (sm_get_sc_oob_data != NULL){
11434acf7b7bSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1144a680ba6bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
1145a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
1146a680ba6bSMatthias Ringwald                     sm_conn->sm_peer_address,
1147a680ba6bSMatthias Ringwald                     setup->sm_peer_confirm,
11484acf7b7bSMatthias Ringwald                     setup->sm_ra);
11494acf7b7bSMatthias Ringwald             } else {
11504acf7b7bSMatthias Ringwald                 setup->sm_have_oob_data = (*sm_get_sc_oob_data)(
11514acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_addr_type,
11524acf7b7bSMatthias Ringwald                     sm_conn->sm_peer_address,
11534acf7b7bSMatthias Ringwald                     setup->sm_peer_confirm,
11544acf7b7bSMatthias Ringwald                     setup->sm_rb);
11554acf7b7bSMatthias Ringwald             }
1156a680ba6bSMatthias Ringwald         } else {
1157a680ba6bSMatthias Ringwald             setup->sm_have_oob_data = 0;
1158a680ba6bSMatthias Ringwald         }
1159a680ba6bSMatthias Ringwald     }
1160a680ba6bSMatthias Ringwald #endif
1161a680ba6bSMatthias Ringwald 
11623deb3ec6SMatthias Ringwald     sm_pairing_packet_t * local_packet;
116342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
11643deb3ec6SMatthias Ringwald         // slave
11653deb3ec6SMatthias Ringwald         local_packet = &setup->sm_s_pres;
11663deb3ec6SMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_peer_addr_type;
1167d5314cbeSMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_own_addr_type;
11686535961aSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_peer_address, 6);
1169d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_own_address, 6);
11703deb3ec6SMatthias Ringwald     } else {
11713deb3ec6SMatthias Ringwald         // master
11723deb3ec6SMatthias Ringwald         local_packet = &setup->sm_m_preq;
11733deb3ec6SMatthias Ringwald         setup->sm_s_addr_type = sm_conn->sm_peer_addr_type;
1174d5314cbeSMatthias Ringwald         setup->sm_m_addr_type = sm_conn->sm_own_addr_type;
11756535961aSMatthias Ringwald         (void)memcpy(setup->sm_s_address, sm_conn->sm_peer_address, 6);
1176d5314cbeSMatthias Ringwald         (void)memcpy(setup->sm_m_address, sm_conn->sm_own_address, 6);
11773deb3ec6SMatthias Ringwald 
1178d0ea782aSMatthias Ringwald         uint8_t key_distribution_flags = sm_key_distribution_flags_for_auth_req();
11791ad129beSMatthias Ringwald         sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
11801ad129beSMatthias Ringwald         sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
11813deb3ec6SMatthias Ringwald     }
11823deb3ec6SMatthias Ringwald 
118357132f12SMatthias Ringwald     uint8_t auth_req = sm_auth_req & ~SM_AUTHREQ_CT2;
1184d0ea782aSMatthias Ringwald     uint8_t max_encryption_key_size = sm_max_encryption_key_size;
11852c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
11862c041b42SMatthias Ringwald     // enable SC for SC only mode
11872c041b42SMatthias Ringwald     if (sm_sc_only_mode){
11882c041b42SMatthias Ringwald         auth_req |= SM_AUTHREQ_SECURE_CONNECTION;
1189d0ea782aSMatthias Ringwald         max_encryption_key_size = 16;
11902c041b42SMatthias Ringwald     }
11912c041b42SMatthias Ringwald #endif
119257132f12SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
119357132f12SMatthias Ringwald 	// set CT2 if SC + Bonding + CTKD
119457132f12SMatthias Ringwald 	const uint8_t auth_req_for_ct2 = SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING;
119557132f12SMatthias Ringwald 	if ((auth_req & auth_req_for_ct2) == auth_req_for_ct2){
119657132f12SMatthias Ringwald 		auth_req |= SM_AUTHREQ_CT2;
119757132f12SMatthias Ringwald 	}
119857132f12SMatthias Ringwald #endif
11991ad129beSMatthias Ringwald     sm_pairing_packet_set_io_capability(*local_packet, sm_io_capabilities);
1200a680ba6bSMatthias Ringwald     sm_pairing_packet_set_oob_data_flag(*local_packet, setup->sm_have_oob_data);
1201df86eb96SMatthias Ringwald     sm_pairing_packet_set_auth_req(*local_packet, auth_req);
1202d0ea782aSMatthias Ringwald     sm_pairing_packet_set_max_encryption_key_size(*local_packet, max_encryption_key_size);
12033deb3ec6SMatthias Ringwald }
12043deb3ec6SMatthias Ringwald 
12053deb3ec6SMatthias Ringwald static int sm_stk_generation_init(sm_connection_t * sm_conn){
12063deb3ec6SMatthias Ringwald 
12073deb3ec6SMatthias Ringwald     sm_pairing_packet_t * remote_packet;
12089a90d41aSMatthias Ringwald     uint8_t               keys_to_send;
12099a90d41aSMatthias Ringwald     uint8_t               keys_to_receive;
121042134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
121152f9cf63SMatthias Ringwald         // slave / responder
12123deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_m_preq;
12139a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_responder_key_distribution(setup->sm_m_preq);
12149a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_initiator_key_distribution(setup->sm_m_preq);
12153deb3ec6SMatthias Ringwald     } else {
12163deb3ec6SMatthias Ringwald         // master / initiator
12173deb3ec6SMatthias Ringwald         remote_packet   = &setup->sm_s_pres;
12189a90d41aSMatthias Ringwald         keys_to_send    = sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres);
12199a90d41aSMatthias Ringwald         keys_to_receive = sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres);
12203deb3ec6SMatthias Ringwald     }
12213deb3ec6SMatthias Ringwald 
12223deb3ec6SMatthias Ringwald     // check key size
12232c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12242c041b42SMatthias Ringwald     // SC Only mandates 128 bit key size
12252c041b42SMatthias Ringwald     if (sm_sc_only_mode && (sm_pairing_packet_get_max_encryption_key_size(*remote_packet) < 16)) {
12262c041b42SMatthias Ringwald         return SM_REASON_ENCRYPTION_KEY_SIZE;
12272c041b42SMatthias Ringwald     }
12282c041b42SMatthias Ringwald #endif
12291ad129beSMatthias Ringwald     sm_conn->sm_actual_encryption_key_size = sm_calc_actual_encryption_key_size(sm_pairing_packet_get_max_encryption_key_size(*remote_packet));
12304ea43905SMatthias Ringwald     if (sm_conn->sm_actual_encryption_key_size == 0u) return SM_REASON_ENCRYPTION_KEY_SIZE;
12313deb3ec6SMatthias Ringwald 
1232eddc894fSMatthias Ringwald     // decide on STK generation method / SC
12333deb3ec6SMatthias Ringwald     sm_setup_tk();
12343deb3ec6SMatthias Ringwald     log_info("SMP: generation method %u", setup->sm_stk_generation_method);
12353deb3ec6SMatthias Ringwald 
12363deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
12373deb3ec6SMatthias Ringwald     if (!sm_validate_stk_generation_method()) return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12383deb3ec6SMatthias Ringwald 
1239eddc894fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
12402c041b42SMatthias Ringwald     // Check LE SC Only mode
12413cdbe9dbSMatthias Ringwald     if (sm_sc_only_mode && (setup->sm_use_secure_connections == false)){
12423cdbe9dbSMatthias Ringwald         log_info("SC Only mode active but SC not possible");
12433cdbe9dbSMatthias Ringwald         return SM_REASON_AUTHENTHICATION_REQUIREMENTS;
12443cdbe9dbSMatthias Ringwald     }
12453cdbe9dbSMatthias Ringwald 
12469a90d41aSMatthias Ringwald     // LTK (= encryption information & master identification) only used exchanged for LE Legacy Connection
1247eddc894fSMatthias Ringwald     if (setup->sm_use_secure_connections){
12489a90d41aSMatthias Ringwald         keys_to_send &= ~SM_KEYDIST_ENC_KEY;
12499a90d41aSMatthias Ringwald         keys_to_receive  &= ~SM_KEYDIST_ENC_KEY;
1250eddc894fSMatthias Ringwald     }
1251eddc894fSMatthias Ringwald #endif
1252eddc894fSMatthias Ringwald 
125352f9cf63SMatthias Ringwald     // identical to responder
12549a90d41aSMatthias Ringwald     sm_setup_key_distribution(keys_to_send, keys_to_receive);
125552f9cf63SMatthias Ringwald 
12563deb3ec6SMatthias Ringwald     // JUST WORKS doens't provide authentication
1257c1ab6cc1SMatthias Ringwald     sm_conn->sm_connection_authenticated = (setup->sm_stk_generation_method == JUST_WORKS) ? 0 : 1;
12583deb3ec6SMatthias Ringwald 
12593deb3ec6SMatthias Ringwald     return 0;
12603deb3ec6SMatthias Ringwald }
12613deb3ec6SMatthias Ringwald 
12623deb3ec6SMatthias Ringwald static void sm_address_resolution_handle_event(address_resolution_event_t event){
12633deb3ec6SMatthias Ringwald 
12643deb3ec6SMatthias Ringwald     // cache and reset context
12653deb3ec6SMatthias Ringwald     int matched_device_id = sm_address_resolution_test;
12663deb3ec6SMatthias Ringwald     address_resolution_mode_t mode = sm_address_resolution_mode;
12673deb3ec6SMatthias Ringwald     void * context = sm_address_resolution_context;
12683deb3ec6SMatthias Ringwald 
12693deb3ec6SMatthias Ringwald     // reset context
12703deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
12713deb3ec6SMatthias Ringwald     sm_address_resolution_context = NULL;
12723deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;
1273711e6c80SMatthias Ringwald     hci_con_handle_t con_handle = 0;
12743deb3ec6SMatthias Ringwald 
12753deb3ec6SMatthias Ringwald     sm_connection_t * sm_connection;
1276d2e90122SMatthias Ringwald     sm_key_t ltk;
12771979f09cSMatthias Ringwald     bool have_ltk;
12786c44b759SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
12791979f09cSMatthias Ringwald     bool trigger_pairing;
128042134bc6SMatthias Ringwald #endif
12813deb3ec6SMatthias Ringwald     switch (mode){
12823deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_GENERAL:
12833deb3ec6SMatthias Ringwald             break;
12843deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FOR_CONNECTION:
12853deb3ec6SMatthias Ringwald             sm_connection = (sm_connection_t *) context;
1286711e6c80SMatthias Ringwald             con_handle = sm_connection->sm_handle;
12876c44b759SMatthias Ringwald 
12886c44b759SMatthias Ringwald             // have ltk -> start encryption / send security request
12896c44b759SMatthias Ringwald             // Core 5, Vol 3, Part C, 10.3.2 Initiating a Service Request
12906c44b759SMatthias Ringwald             // "When a bond has been created between two devices, any reconnection should result in the local device
12916c44b759SMatthias Ringwald             //  enabling or requesting encryption with the remote device before initiating any service request."
12926c44b759SMatthias Ringwald 
12933deb3ec6SMatthias Ringwald             switch (event){
1294a66b030fSMatthias Ringwald                 case ADDRESS_RESOLUTION_SUCCEEDED:
12953deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
12963deb3ec6SMatthias Ringwald                     sm_connection->sm_le_db_index = matched_device_id;
1297a66b030fSMatthias Ringwald                     log_info("ADDRESS_RESOLUTION_SUCCEEDED, index %d", sm_connection->sm_le_db_index);
12986c44b759SMatthias Ringwald 
12996c44b759SMatthias Ringwald                     le_device_db_encryption_get(sm_connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
13006c44b759SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
13016c44b759SMatthias Ringwald 
13026c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13036c44b759SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
1304212d735eSMatthias Ringwald                         // IRK required before, continue
13056c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13066c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
13076c39055aSMatthias Ringwald                             break;
13086c39055aSMatthias Ringwald                         }
1309212d735eSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK){
1310212d735eSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
1311212d735eSMatthias Ringwald                             break;
1312212d735eSMatthias Ringwald                         }
13137af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13147af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13156c44b759SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
13167af5dcd5SMatthias Ringwald                         // trigger security request for Proactive Authentication if LTK available
13177af5dcd5SMatthias Ringwald                         trigger_security_request = trigger_security_request || have_ltk;
13186c44b759SMatthias Ringwald #endif
13197af5dcd5SMatthias Ringwald 
13207af5dcd5SMatthias Ringwald                         log_info("peripheral: pairing request local %u, have_ltk %u => trigger_security_request %u",
13211979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, (int) have_ltk, trigger_security_request);
13227af5dcd5SMatthias Ringwald 
13237af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13247af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13257af5dcd5SMatthias Ringwald                             if (have_ltk){
13267af5dcd5SMatthias Ringwald                                 sm_reencryption_started(sm_connection);
13277af5dcd5SMatthias Ringwald                             } else {
13287af5dcd5SMatthias Ringwald                                 sm_pairing_started(sm_connection);
13297af5dcd5SMatthias Ringwald                             }
13307af5dcd5SMatthias Ringwald                             sm_trigger_run();
13316c44b759SMatthias Ringwald                         }
13326c44b759SMatthias Ringwald #endif
13336c44b759SMatthias Ringwald                     } else {
13346c44b759SMatthias Ringwald 
133542134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
13366c44b759SMatthias Ringwald                         // check if pairing already requested and reset requests
13376c44b759SMatthias Ringwald                         trigger_pairing = sm_connection->sm_pairing_requested || sm_connection->sm_security_request_received;
13386c44b759SMatthias Ringwald                         log_info("central: pairing request local %u, remote %u => trigger_pairing %u. have_ltk %u",
13391979f09cSMatthias Ringwald                                  sm_connection->sm_pairing_requested, sm_connection->sm_security_request_received, (int) trigger_pairing, (int) have_ltk);
13403deb3ec6SMatthias Ringwald                         sm_connection->sm_security_request_received = 0;
134109ea1b62SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
134232bc5d65SMatthias Ringwald                         bool trigger_reencryption = false;
1343c245ca32SMatthias Ringwald 
1344d4af1595SMatthias Ringwald                         if (have_ltk){
13456a43f611SMatthias Ringwald #ifdef ENABLE_LE_PROACTIVE_AUTHENTICATION
1346b187cc61SMatthias Ringwald                             trigger_reencryption = true;
134732bc5d65SMatthias Ringwald #else
134832bc5d65SMatthias Ringwald                             if (trigger_pairing){
134932bc5d65SMatthias Ringwald                                 trigger_reencryption = true;
135032bc5d65SMatthias Ringwald                             } else {
135132bc5d65SMatthias Ringwald                                 log_info("central: defer enabling encryption for bonded device");
135232bc5d65SMatthias Ringwald                             }
135332bc5d65SMatthias Ringwald #endif
135432bc5d65SMatthias Ringwald                         }
135532bc5d65SMatthias Ringwald 
135632bc5d65SMatthias Ringwald                         if (trigger_reencryption){
13576c44b759SMatthias Ringwald                             log_info("central: enable encryption for bonded device");
13585567aa60SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
1359d4af1595SMatthias Ringwald                             break;
1360d4af1595SMatthias Ringwald                         }
13616c44b759SMatthias Ringwald 
13626c44b759SMatthias Ringwald                         // pairing_request -> send pairing request
13636c44b759SMatthias Ringwald                         if (trigger_pairing){
13643deb3ec6SMatthias Ringwald                             sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
1365d4af1595SMatthias Ringwald                             break;
13663deb3ec6SMatthias Ringwald                         }
136742134bc6SMatthias Ringwald #endif
1368298ab52bSMatthias Ringwald                     }
13693deb3ec6SMatthias Ringwald                     break;
13703deb3ec6SMatthias Ringwald                 case ADDRESS_RESOLUTION_FAILED:
13713deb3ec6SMatthias Ringwald                     sm_connection->sm_irk_lookup_state = IRK_LOOKUP_FAILED;
13726c39055aSMatthias Ringwald                     if (sm_connection->sm_role) {
13737af5dcd5SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
13746c39055aSMatthias Ringwald                         // LTK request received before, IRK required -> negative LTK reply
13756c39055aSMatthias Ringwald                         if (sm_connection->sm_engine_state == SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK){
13766c39055aSMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
13776c39055aSMatthias Ringwald                         }
13787af5dcd5SMatthias Ringwald                         // send security request if requested
13797af5dcd5SMatthias Ringwald                         bool trigger_security_request = (sm_connection->sm_pairing_requested != 0) || (sm_slave_request_security != 0);
13807af5dcd5SMatthias Ringwald                         sm_connection->sm_pairing_requested = 0;
13817af5dcd5SMatthias Ringwald                         if (trigger_security_request){
13827af5dcd5SMatthias Ringwald                             sm_connection->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
13837af5dcd5SMatthias Ringwald                             sm_pairing_started(sm_connection);
13847af5dcd5SMatthias Ringwald                         }
13856c39055aSMatthias Ringwald                         break;
13867af5dcd5SMatthias Ringwald #endif
13876c39055aSMatthias Ringwald                     }
138842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
138909ea1b62SMatthias Ringwald                     if (!sm_connection->sm_pairing_requested && !sm_connection->sm_security_request_received) break;
13903deb3ec6SMatthias Ringwald                     sm_connection->sm_security_request_received = 0;
139109ea1b62SMatthias Ringwald                     sm_connection->sm_pairing_requested = 0;
13923deb3ec6SMatthias Ringwald                     sm_connection->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
139342134bc6SMatthias Ringwald #endif
13943deb3ec6SMatthias Ringwald                     break;
13957bbeb3adSMilanka Ringwald 
13967bbeb3adSMilanka Ringwald                 default:
13977bbeb3adSMilanka Ringwald                     btstack_assert(false);
13987bbeb3adSMilanka Ringwald                     break;
13993deb3ec6SMatthias Ringwald             }
14003deb3ec6SMatthias Ringwald             break;
14013deb3ec6SMatthias Ringwald         default:
14023deb3ec6SMatthias Ringwald             break;
14033deb3ec6SMatthias Ringwald     }
14043deb3ec6SMatthias Ringwald 
14053deb3ec6SMatthias Ringwald     switch (event){
1406a66b030fSMatthias Ringwald         case ADDRESS_RESOLUTION_SUCCEEDED:
1407711e6c80SMatthias Ringwald             sm_notify_client_index(SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address, matched_device_id);
14083deb3ec6SMatthias Ringwald             break;
14093deb3ec6SMatthias Ringwald         case ADDRESS_RESOLUTION_FAILED:
1410711e6c80SMatthias Ringwald             sm_notify_client_base(SM_EVENT_IDENTITY_RESOLVING_FAILED, con_handle, sm_address_resolution_addr_type, sm_address_resolution_address);
14113deb3ec6SMatthias Ringwald             break;
14127bbeb3adSMilanka Ringwald         default:
14137bbeb3adSMilanka Ringwald             btstack_assert(false);
14147bbeb3adSMilanka Ringwald             break;
14153deb3ec6SMatthias Ringwald     }
14163deb3ec6SMatthias Ringwald }
14173deb3ec6SMatthias Ringwald 
141855f09f49SMatthias Ringwald static void sm_store_bonding_information(sm_connection_t * sm_conn){
14193deb3ec6SMatthias Ringwald     int le_db_index = -1;
14203deb3ec6SMatthias Ringwald 
14213deb3ec6SMatthias Ringwald     // lookup device based on IRK
14223deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
14233deb3ec6SMatthias Ringwald         int i;
1424092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14253deb3ec6SMatthias Ringwald             sm_key_t irk;
14263deb3ec6SMatthias Ringwald             bd_addr_t address;
1427c7e2c1a5SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14283deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, irk);
1429adf5eaa9SMatthias Ringwald             // skip unused entries
1430c7e2c1a5SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
1431c7e2c1a5SMatthias Ringwald             // compare IRK
1432c7e2c1a5SMatthias Ringwald             if (memcmp(irk, setup->sm_peer_irk, 16) != 0) continue;
1433c7e2c1a5SMatthias Ringwald 
14343deb3ec6SMatthias Ringwald             log_info("sm: device found for IRK, updating");
14353deb3ec6SMatthias Ringwald             le_db_index = i;
14363deb3ec6SMatthias Ringwald             break;
14373deb3ec6SMatthias Ringwald         }
1438c7e2c1a5SMatthias Ringwald     } else {
1439c7e2c1a5SMatthias Ringwald         // assert IRK is set to zero
1440c7e2c1a5SMatthias Ringwald         memset(setup->sm_peer_irk, 0, 16);
14413deb3ec6SMatthias Ringwald     }
14423deb3ec6SMatthias Ringwald 
14433deb3ec6SMatthias Ringwald     // if not found, lookup via public address if possible
14443deb3ec6SMatthias Ringwald     log_info("sm peer addr type %u, peer addres %s", setup->sm_peer_addr_type, bd_addr_to_str(setup->sm_peer_address));
1445c1ab6cc1SMatthias Ringwald     if ((le_db_index < 0) && (setup->sm_peer_addr_type == BD_ADDR_TYPE_LE_PUBLIC)){
14463deb3ec6SMatthias Ringwald         int i;
1447092ec58eSMatthias Ringwald         for (i=0; i < le_device_db_max_count(); i++){
14483deb3ec6SMatthias Ringwald             bd_addr_t address;
1449adf5eaa9SMatthias Ringwald             int address_type = BD_ADDR_TYPE_UNKNOWN;
14503deb3ec6SMatthias Ringwald             le_device_db_info(i, &address_type, address, NULL);
1451adf5eaa9SMatthias Ringwald             // skip unused entries
1452adf5eaa9SMatthias Ringwald             if (address_type == BD_ADDR_TYPE_UNKNOWN) continue;
14533deb3ec6SMatthias Ringwald             log_info("device %u, sm peer addr type %u, peer addres %s", i, address_type, bd_addr_to_str(address));
14545df9dc78SMatthias Ringwald             if ((address_type == BD_ADDR_TYPE_LE_PUBLIC) && (memcmp(address, setup->sm_peer_address, 6) == 0)){
14553deb3ec6SMatthias Ringwald                 log_info("sm: device found for public address, updating");
14563deb3ec6SMatthias Ringwald                 le_db_index = i;
14573deb3ec6SMatthias Ringwald                 break;
14583deb3ec6SMatthias Ringwald             }
14593deb3ec6SMatthias Ringwald         }
14603deb3ec6SMatthias Ringwald     }
14613deb3ec6SMatthias Ringwald 
14623deb3ec6SMatthias Ringwald     // if not found, add to db
146302b02cffSMatthias Ringwald     bool new_to_le_device_db = false;
14643deb3ec6SMatthias Ringwald     if (le_db_index < 0) {
14653deb3ec6SMatthias Ringwald         le_db_index = le_device_db_add(setup->sm_peer_addr_type, setup->sm_peer_address, setup->sm_peer_irk);
146602b02cffSMatthias Ringwald         new_to_le_device_db = true;
14673deb3ec6SMatthias Ringwald     }
14683deb3ec6SMatthias Ringwald 
14693deb3ec6SMatthias Ringwald     if (le_db_index >= 0){
14703deb3ec6SMatthias Ringwald 
147102b02cffSMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
147202b02cffSMatthias Ringwald         if (!new_to_le_device_db){
147302b02cffSMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(le_db_index);
147402b02cffSMatthias Ringwald         }
147502b02cffSMatthias Ringwald         hci_load_le_device_db_entry_into_resolving_list(le_db_index);
147602b02cffSMatthias Ringwald #else
147702b02cffSMatthias Ringwald         UNUSED(new_to_le_device_db);
147802b02cffSMatthias Ringwald #endif
147902b02cffSMatthias Ringwald 
148048163929SMatthias 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);
1481e1086030SMatthias Ringwald         sm_conn->sm_irk_lookup_state = IRK_LOOKUP_SUCCEEDED;
14827710ebd2SMatthias Ringwald         sm_conn->sm_le_db_index = le_db_index;
148348163929SMatthias Ringwald 
1484eda85fbfSMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
14853deb3ec6SMatthias Ringwald         // store local CSRK
1486715a43d1SMatthias Ringwald         setup->sm_le_device_index = le_db_index;
1487715a43d1SMatthias Ringwald         if ((setup->sm_key_distribution_sent_set) & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14883deb3ec6SMatthias Ringwald             log_info("sm: store local CSRK");
14893deb3ec6SMatthias Ringwald             le_device_db_local_csrk_set(le_db_index, setup->sm_local_csrk);
14903deb3ec6SMatthias Ringwald             le_device_db_local_counter_set(le_db_index, 0);
14913deb3ec6SMatthias Ringwald         }
14923deb3ec6SMatthias Ringwald 
14933deb3ec6SMatthias Ringwald         // store remote CSRK
14943deb3ec6SMatthias Ringwald         if (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
14953deb3ec6SMatthias Ringwald             log_info("sm: store remote CSRK");
14963deb3ec6SMatthias Ringwald             le_device_db_remote_csrk_set(le_db_index, setup->sm_peer_csrk);
14973deb3ec6SMatthias Ringwald             le_device_db_remote_counter_set(le_db_index, 0);
14983deb3ec6SMatthias Ringwald         }
1499eda85fbfSMatthias Ringwald #endif
150078f44163SMatthias Ringwald         // store encryption information for secure connections: LTK generated by ECDH
150178f44163SMatthias Ringwald         if (setup->sm_use_secure_connections){
1502e6343eb6SMatthias Ringwald             log_info("sm: store SC LTK (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
150378f44163SMatthias Ringwald             uint8_t zero_rand[8];
150478f44163SMatthias Ringwald             memset(zero_rand, 0, 8);
150578f44163SMatthias Ringwald             le_device_db_encryption_set(le_db_index, 0, zero_rand, setup->sm_ltk, sm_conn->sm_actual_encryption_key_size,
15063dc3a67dSMatthias Ringwald                                         sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 1);
150778f44163SMatthias Ringwald         }
150878f44163SMatthias Ringwald 
1509e6343eb6SMatthias Ringwald         // store encryption information for legacy pairing: peer LTK, EDIV, RAND
151078f44163SMatthias Ringwald         else if ( (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION)
151178f44163SMatthias Ringwald         && (setup->sm_key_distribution_received_set & SM_KEYDIST_FLAG_MASTER_IDENTIFICATION )){
1512e6343eb6SMatthias Ringwald             log_info("sm: set encryption information (key size %u, authenticated %u)", sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated);
15133deb3ec6SMatthias Ringwald             le_device_db_encryption_set(le_db_index, setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
15143dc3a67dSMatthias Ringwald                                         sm_conn->sm_actual_encryption_key_size, sm_conn->sm_connection_authenticated, sm_conn->sm_connection_authorization_state == AUTHORIZATION_GRANTED, 0);
151578f44163SMatthias Ringwald 
15163deb3ec6SMatthias Ringwald         }
15173deb3ec6SMatthias Ringwald     }
151855f09f49SMatthias Ringwald }
151955f09f49SMatthias Ringwald 
152055f09f49SMatthias Ringwald static void sm_key_distribution_handle_all_received(sm_connection_t * sm_conn){
152155f09f49SMatthias Ringwald 
152255f09f49SMatthias Ringwald     // only store pairing information if both sides are bondable, i.e., the bonadble flag is set
152355f09f49SMatthias Ringwald     bool bonding_enabled = (sm_pairing_packet_get_auth_req(setup->sm_m_preq)
152455f09f49SMatthias Ringwald                             & sm_pairing_packet_get_auth_req(setup->sm_s_pres)
152555f09f49SMatthias Ringwald                             & SM_AUTHREQ_BONDING ) != 0u;
152655f09f49SMatthias Ringwald 
152755f09f49SMatthias Ringwald     if (bonding_enabled){
152855f09f49SMatthias Ringwald         sm_store_bonding_information(sm_conn);
152927ef8bc8SMatthias Ringwald     } else {
153027ef8bc8SMatthias Ringwald         log_info("Ignoring received keys, bonding not enabled");
153127ef8bc8SMatthias Ringwald     }
15323deb3ec6SMatthias Ringwald }
15333deb3ec6SMatthias Ringwald 
1534688a08f9SMatthias Ringwald static void sm_pairing_error(sm_connection_t * sm_conn, uint8_t reason){
1535f4935286SMatthias Ringwald     sm_conn->sm_pairing_failed_reason = reason;
1536688a08f9SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_SEND_PAIRING_FAILED;
1537688a08f9SMatthias Ringwald }
1538688a08f9SMatthias Ringwald 
1539688a08f9SMatthias Ringwald static inline void sm_pdu_received_in_wrong_state(sm_connection_t * sm_conn){
1540688a08f9SMatthias Ringwald     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
1541688a08f9SMatthias Ringwald }
1542688a08f9SMatthias Ringwald 
15439af0f475SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
1544688a08f9SMatthias Ringwald 
1545dc300847SMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn);
1546945888f5SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method);
1547f1c1783eSMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method);
1548dc300847SMatthias Ringwald 
1549b35a3de2SMatthias Ringwald static void sm_sc_start_calculating_local_confirm(sm_connection_t * sm_conn){
1550b90c4e75SMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
15511f9d84e9SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
1552b90c4e75SMatthias Ringwald     } else {
1553b90c4e75SMatthias 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);
1554b35a3de2SMatthias Ringwald     }
1555b35a3de2SMatthias Ringwald }
1556b35a3de2SMatthias Ringwald 
1557688a08f9SMatthias Ringwald static void sm_sc_state_after_receiving_random(sm_connection_t * sm_conn){
155842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1559688a08f9SMatthias Ringwald         // Responder
15604acf7b7bSMatthias Ringwald         if (setup->sm_stk_generation_method == OOB){
15614acf7b7bSMatthias Ringwald             // generate Nb
15624acf7b7bSMatthias Ringwald             log_info("Generate Nb");
15636ca80073SMatthias 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);
15644acf7b7bSMatthias Ringwald         } else {
1565688a08f9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
15664acf7b7bSMatthias Ringwald         }
1567688a08f9SMatthias Ringwald     } else {
1568688a08f9SMatthias Ringwald         // Initiator role
1569688a08f9SMatthias Ringwald         switch (setup->sm_stk_generation_method){
1570688a08f9SMatthias Ringwald             case JUST_WORKS:
1571dc300847SMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1572688a08f9SMatthias Ringwald                 break;
1573688a08f9SMatthias Ringwald 
157447fb4255SMatthias Ringwald             case NUMERIC_COMPARISON:
1575bd57ffebSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_G2;
1576688a08f9SMatthias Ringwald                 break;
1577688a08f9SMatthias Ringwald             case PK_INIT_INPUT:
1578688a08f9SMatthias Ringwald             case PK_RESP_INPUT:
157947fb4255SMatthias Ringwald             case PK_BOTH_INPUT:
15804ea43905SMatthias Ringwald                 if (setup->sm_passkey_bit < 20u) {
1581b35a3de2SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(sm_conn);
1582688a08f9SMatthias Ringwald                 } else {
1583dc300847SMatthias Ringwald                     sm_sc_prepare_dhkey_check(sm_conn);
1584688a08f9SMatthias Ringwald                 }
1585688a08f9SMatthias Ringwald                 break;
1586688a08f9SMatthias Ringwald             case OOB:
158765a9a04eSMatthias Ringwald                 sm_sc_prepare_dhkey_check(sm_conn);
1588688a08f9SMatthias Ringwald                 break;
15897bbeb3adSMilanka Ringwald             default:
15907bbeb3adSMilanka Ringwald                 btstack_assert(false);
15917bbeb3adSMilanka Ringwald                 break;
1592688a08f9SMatthias Ringwald         }
1593688a08f9SMatthias Ringwald     }
1594688a08f9SMatthias Ringwald }
1595688a08f9SMatthias Ringwald 
1596aec94140SMatthias Ringwald static void sm_sc_cmac_done(uint8_t * hash){
1597688a08f9SMatthias Ringwald     log_info("sm_sc_cmac_done: ");
1598688a08f9SMatthias Ringwald     log_info_hexdump(hash, 16);
1599688a08f9SMatthias Ringwald 
1600c59d0c92SMatthias Ringwald     if (sm_sc_oob_state == SM_SC_OOB_W4_CONFIRM){
1601c59d0c92SMatthias Ringwald         sm_sc_oob_state = SM_SC_OOB_IDLE;
1602a680ba6bSMatthias Ringwald         (*sm_sc_oob_callback)(hash, sm_sc_oob_random);
1603c59d0c92SMatthias Ringwald         return;
1604c59d0c92SMatthias Ringwald     }
1605c59d0c92SMatthias Ringwald 
1606bd57ffebSMatthias Ringwald     sm_connection_t * sm_conn = sm_cmac_connection;
1607bd57ffebSMatthias Ringwald     sm_cmac_connection = NULL;
16086857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
16092bacf595SMatthias Ringwald     link_key_type_t link_key_type;
1610b4f65634SMatthias Ringwald #endif
1611bd57ffebSMatthias Ringwald 
1612bd57ffebSMatthias Ringwald     switch (sm_conn->sm_engine_state){
1613aec94140SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CONFIRMATION:
16146535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_confirm, hash, 16);
1615bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_CONFIRMATION;
1616aec94140SMatthias Ringwald             break;
1617688a08f9SMatthias Ringwald         case SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION:
1618688a08f9SMatthias Ringwald             // check
1619688a08f9SMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_confirm, 16)){
1620bd57ffebSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_CONFIRM_VALUE_FAILED);
1621688a08f9SMatthias Ringwald                 break;
1622688a08f9SMatthias Ringwald             }
1623bd57ffebSMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
1624688a08f9SMatthias Ringwald             break;
1625901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2: {
1626901c000fSMatthias Ringwald             uint32_t vab = big_endian_read_32(hash, 12) % 1000000;
1627901c000fSMatthias Ringwald             big_endian_store_32(setup->sm_tk, 12, vab);
1628901c000fSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
1629901c000fSMatthias Ringwald             sm_trigger_user_response(sm_conn);
1630019005a0SMatthias Ringwald             break;
1631019005a0SMatthias Ringwald         }
16320346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
16336535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1634bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_MACKEY;
16350346c37cSMatthias Ringwald             break;
16360346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
16376535961aSMatthias Ringwald             (void)memcpy(setup->sm_mackey, hash, 16);
1638bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_LTK;
16390346c37cSMatthias Ringwald             break;
16400346c37cSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
1641b18300a6SMatthias Ringwald             // truncate sm_ltk, but keep full LTK for cross-transport key derivation in sm_local_ltk
1642b18300a6SMatthias Ringwald             // Errata Service Release to the Bluetooth Specification: ESR09
1643b18300a6SMatthias Ringwald             //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1644b18300a6SMatthias Ringwald             //   Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
16456535961aSMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
16466535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_ltk, hash, 16);
1647893e9333SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1648bd57ffebSMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK;
1649019005a0SMatthias Ringwald             break;
1650901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
16516535961aSMatthias Ringwald             (void)memcpy(setup->sm_local_dhkey_check, hash, 16);
165242134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1653901c000fSMatthias Ringwald                 // responder
1654901c000fSMatthias Ringwald                 if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_COMMAND_RECEIVED){
1655901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
1656901c000fSMatthias Ringwald                 } else {
1657901c000fSMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
1658901c000fSMatthias Ringwald                 }
1659901c000fSMatthias Ringwald             } else {
1660901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1661901c000fSMatthias Ringwald             }
1662901c000fSMatthias Ringwald             break;
1663901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
1664901c000fSMatthias Ringwald             if (0 != memcmp(hash, setup->sm_peer_dhkey_check, 16) ){
1665901c000fSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
1666aec94140SMatthias Ringwald                 break;
1667aec94140SMatthias Ringwald             }
166842134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
1669901c000fSMatthias Ringwald                 // responder
1670901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_DHKEY_CHECK_COMMAND;
1671901c000fSMatthias Ringwald             } else {
1672901c000fSMatthias Ringwald                 // initiator
1673901c000fSMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
1674bd57ffebSMatthias Ringwald             }
1675901c000fSMatthias Ringwald             break;
16766857ad8fSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
167757132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_ILK:
16786535961aSMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
167957132f12SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY;
16802bacf595SMatthias Ringwald             break;
168157132f12SMatthias Ringwald         case SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY:
16822bacf595SMatthias Ringwald             reverse_128(hash, setup->sm_t);
16832bacf595SMatthias Ringwald             link_key_type = sm_conn->sm_connection_authenticated ?
16842bacf595SMatthias Ringwald                 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256 : UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
16858974e43fSMatthias Ringwald             log_info("Derived classic link key from LE using h6, type %u", (int) link_key_type);
168655160b1cSMatthias Ringwald 			gap_store_link_key_for_bd_addr(setup->sm_peer_address, setup->sm_t, link_key_type);
16878974e43fSMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
16882bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
16892bacf595SMatthias Ringwald             } else {
16902bacf595SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
16912bacf595SMatthias Ringwald             }
16920ccf6c9cSMatthias Ringwald             sm_pairing_complete(sm_conn, ERROR_CODE_SUCCESS, 0);
16932bacf595SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
16942bacf595SMatthias Ringwald             break;
1695e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_ILK:
1696e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_t, hash, 16);
1697e0a03c85SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_W2_CALCULATE_LE_LTK;
1698e0a03c85SMatthias Ringwald             break;
1699e0a03c85SMatthias Ringwald         case SM_BR_EDR_W4_CALCULATE_LE_LTK:
1700e0a03c85SMatthias Ringwald             log_info("Derived LE LTK from BR/EDR Link Key");
1701e0a03c85SMatthias Ringwald             log_info_key("Link Key", hash);
1702e0a03c85SMatthias Ringwald             (void)memcpy(setup->sm_ltk, hash, 16);
1703e0a03c85SMatthias Ringwald             sm_truncate_key(setup->sm_ltk, sm_conn->sm_actual_encryption_key_size);
1704e0a03c85SMatthias Ringwald             sm_conn->sm_connection_authenticated = setup->sm_link_key_type == AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256;
1705e0a03c85SMatthias Ringwald             sm_store_bonding_information(sm_conn);
1706c18be159SMatthias Ringwald             sm_done_for_handle(sm_conn->sm_handle);
1707e0a03c85SMatthias Ringwald             break;
1708bdb14b0eSMatthias Ringwald #endif
1709bd57ffebSMatthias Ringwald         default:
1710bd57ffebSMatthias Ringwald             log_error("sm_sc_cmac_done in state %u", sm_conn->sm_engine_state);
1711bd57ffebSMatthias Ringwald             break;
1712bd57ffebSMatthias Ringwald     }
171370b44dd4SMatthias Ringwald     sm_trigger_run();
1714aec94140SMatthias Ringwald }
1715aec94140SMatthias Ringwald 
1716688a08f9SMatthias 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){
1717dc300847SMatthias Ringwald     const uint16_t message_len = 65;
1718aec94140SMatthias Ringwald     sm_cmac_connection = sm_conn;
17196535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
17206535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
1721aec94140SMatthias Ringwald     sm_cmac_sc_buffer[64] = z;
1722aec94140SMatthias Ringwald     log_info("f4 key");
1723aec94140SMatthias Ringwald     log_info_hexdump(x, 16);
1724aec94140SMatthias Ringwald     log_info("f4 message");
1725dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1726d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1727aec94140SMatthias Ringwald }
1728aec94140SMatthias Ringwald 
17290346c37cSMatthias Ringwald static const uint8_t f5_key_id[] = { 0x62, 0x74, 0x6c, 0x65 };
17300346c37cSMatthias Ringwald static const uint8_t f5_length[] = { 0x01, 0x00};
17310346c37cSMatthias Ringwald 
17320346c37cSMatthias Ringwald static void f5_calculate_salt(sm_connection_t * sm_conn){
17338334d3d8SMatthias Ringwald 
17348334d3d8SMatthias Ringwald     static const sm_key_t f5_salt = { 0x6C ,0x88, 0x83, 0x91, 0xAA, 0xF5, 0xA5, 0x38, 0x60, 0x37, 0x0B, 0xDB, 0x5A, 0x60, 0x83, 0xBE};
17358334d3d8SMatthias Ringwald 
173640c5d850SMatthias Ringwald     log_info("f5_calculate_salt");
17370346c37cSMatthias Ringwald     // calculate salt for f5
17380346c37cSMatthias Ringwald     const uint16_t message_len = 32;
17390346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17406535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, setup->sm_dhkey, message_len);
1741d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(f5_salt, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17420346c37cSMatthias Ringwald }
17430346c37cSMatthias Ringwald 
17440346c37cSMatthias 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){
17450346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17460346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17470346c37cSMatthias Ringwald 
17480346c37cSMatthias Ringwald     // f5(W, N1, N2, A1, A2) = AES-CMACT (Counter = 0 || keyID || N1 || N2|| A1|| A2 || Length = 256) -- this is the MacKey
17490346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 0;
17506535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 01, f5_key_id, 4);
17516535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 05, n1, 16);
17526535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 21, n2, 16);
17536535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 37, a1, 7);
17546535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 44, a2, 7);
17556535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, f5_length, 2);
17560346c37cSMatthias Ringwald     log_info("f5 key");
17570346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17580346c37cSMatthias Ringwald     log_info("f5 message for MacKey");
17590346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1760d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17610346c37cSMatthias Ringwald }
17620346c37cSMatthias Ringwald 
17630346c37cSMatthias Ringwald static void f5_calculate_mackey(sm_connection_t * sm_conn){
17640346c37cSMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
17650346c37cSMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
17660346c37cSMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
17676535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
17686535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
176942134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
17700346c37cSMatthias Ringwald         // responder
17710346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_peer_nonce, setup->sm_local_nonce, bd_addr_master, bd_addr_slave);
17720346c37cSMatthias Ringwald     } else {
17730346c37cSMatthias Ringwald         // initiator
17740346c37cSMatthias Ringwald         f5_mackkey(sm_conn, setup->sm_t, setup->sm_local_nonce, setup->sm_peer_nonce, bd_addr_master, bd_addr_slave);
17750346c37cSMatthias Ringwald     }
17760346c37cSMatthias Ringwald }
17770346c37cSMatthias Ringwald 
17780346c37cSMatthias Ringwald // note: must be called right after f5_mackey, as sm_cmac_buffer[1..52] will be reused
17790346c37cSMatthias Ringwald static inline void f5_ltk(sm_connection_t * sm_conn, sm_key_t t){
17800346c37cSMatthias Ringwald     const uint16_t message_len = 53;
17810346c37cSMatthias Ringwald     sm_cmac_connection = sm_conn;
17820346c37cSMatthias Ringwald     sm_cmac_sc_buffer[0] = 1;
17830346c37cSMatthias Ringwald     // 1..52 setup before
17840346c37cSMatthias Ringwald     log_info("f5 key");
17850346c37cSMatthias Ringwald     log_info_hexdump(t, 16);
17860346c37cSMatthias Ringwald     log_info("f5 message for LTK");
17870346c37cSMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1788d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(t, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
17890346c37cSMatthias Ringwald }
1790f92edc8eSMatthias Ringwald 
17910346c37cSMatthias Ringwald static void f5_calculate_ltk(sm_connection_t * sm_conn){
17920346c37cSMatthias Ringwald     f5_ltk(sm_conn, setup->sm_t);
17930346c37cSMatthias Ringwald }
17940346c37cSMatthias Ringwald 
179531f061fbSMatthias 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){
17966535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, n1, 16);
17976535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 16, n2, 16);
17986535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, r, 16);
17996535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 48, io_cap, 3);
18006535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 51, a1, 7);
18016535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 58, a2, 7);
180231f061fbSMatthias Ringwald }
180331f061fbSMatthias Ringwald 
180431f061fbSMatthias Ringwald static void f6_engine(sm_connection_t * sm_conn, const sm_key_t w){
180531f061fbSMatthias Ringwald     const uint16_t message_len = 65;
180631f061fbSMatthias Ringwald     sm_cmac_connection = sm_conn;
1807dc300847SMatthias Ringwald     log_info("f6 key");
1808dc300847SMatthias Ringwald     log_info_hexdump(w, 16);
1809dc300847SMatthias Ringwald     log_info("f6 message");
1810dc300847SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1811d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, 65, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1812dc300847SMatthias Ringwald }
1813dc300847SMatthias Ringwald 
1814f92edc8eSMatthias Ringwald // g2(U, V, X, Y) = AES-CMACX(U || V || Y) mod 2^32
1815f92edc8eSMatthias Ringwald // - U is 256 bits
1816f92edc8eSMatthias Ringwald // - V is 256 bits
1817f92edc8eSMatthias Ringwald // - X is 128 bits
1818f92edc8eSMatthias Ringwald // - Y is 128 bits
1819bd57ffebSMatthias 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){
1820bd57ffebSMatthias Ringwald     const uint16_t message_len = 80;
1821bd57ffebSMatthias Ringwald     sm_cmac_connection = sm_conn;
18226535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer, u, 32);
18236535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 32, v, 32);
18246535961aSMatthias Ringwald     (void)memcpy(sm_cmac_sc_buffer + 64, y, 16);
1825f92edc8eSMatthias Ringwald     log_info("g2 key");
1826f92edc8eSMatthias Ringwald     log_info_hexdump(x, 16);
1827f92edc8eSMatthias Ringwald     log_info("g2 message");
18282bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1829d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(x, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
1830f92edc8eSMatthias Ringwald }
1831f92edc8eSMatthias Ringwald 
1832b35a3de2SMatthias Ringwald static void g2_calculate(sm_connection_t * sm_conn) {
1833f92edc8eSMatthias Ringwald     // calc Va if numeric comparison
183442134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1835f92edc8eSMatthias Ringwald         // responder
1836fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, setup->sm_local_nonce);;
1837f92edc8eSMatthias Ringwald     } else {
1838f92edc8eSMatthias Ringwald         // initiator
1839fc5bff5fSMatthias Ringwald         g2_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, setup->sm_peer_nonce);
1840f92edc8eSMatthias Ringwald     }
1841f92edc8eSMatthias Ringwald }
1842f92edc8eSMatthias Ringwald 
1843945888f5SMatthias Ringwald static void sm_sc_calculate_local_confirm(sm_connection_t * sm_conn){
18449af0f475SMatthias Ringwald     uint8_t z = 0;
184540c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
18469af0f475SMatthias Ringwald         // some form of passkey
18479af0f475SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
18484ea43905SMatthias Ringwald         z = 0x80u | ((pk >> setup->sm_passkey_bit) & 1u);
18499af0f475SMatthias Ringwald         setup->sm_passkey_bit++;
18509af0f475SMatthias Ringwald     }
1851fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, ec_q, setup->sm_peer_q, setup->sm_local_nonce, z);
18529af0f475SMatthias Ringwald }
1853688a08f9SMatthias Ringwald 
1854688a08f9SMatthias Ringwald static void sm_sc_calculate_remote_confirm(sm_connection_t * sm_conn){
1855a680ba6bSMatthias Ringwald     // OOB
1856a680ba6bSMatthias Ringwald     if (setup->sm_stk_generation_method == OOB){
18574acf7b7bSMatthias Ringwald         if (IS_RESPONDER(sm_conn->sm_role)){
18584acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_ra, 0);
18594acf7b7bSMatthias Ringwald         } else {
18604acf7b7bSMatthias Ringwald             f4_engine(sm_conn, setup->sm_peer_q, setup->sm_peer_q, setup->sm_rb, 0);
18614acf7b7bSMatthias Ringwald         }
1862a680ba6bSMatthias Ringwald         return;
1863a680ba6bSMatthias Ringwald     }
1864a680ba6bSMatthias Ringwald 
1865688a08f9SMatthias Ringwald     uint8_t z = 0;
186640c5d850SMatthias Ringwald     if (sm_passkey_entry(setup->sm_stk_generation_method)){
1867688a08f9SMatthias Ringwald         // some form of passkey
1868688a08f9SMatthias Ringwald         uint32_t pk = big_endian_read_32(setup->sm_tk, 12);
1869688a08f9SMatthias Ringwald         // sm_passkey_bit was increased before sending confirm value
18704ea43905SMatthias Ringwald         z = 0x80u | ((pk >> (setup->sm_passkey_bit-1u)) & 1u);
1871688a08f9SMatthias Ringwald     }
1872fc5bff5fSMatthias Ringwald     f4_engine(sm_conn, setup->sm_peer_q, ec_q, setup->sm_peer_nonce, z);
1873688a08f9SMatthias Ringwald }
1874688a08f9SMatthias Ringwald 
18750346c37cSMatthias Ringwald static void sm_sc_prepare_dhkey_check(sm_connection_t * sm_conn){
1876505f1c30SMatthias Ringwald     log_info("sm_sc_prepare_dhkey_check, DHKEY calculated %u", (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED) ? 1 : 0);
18773cf37b8cSMatthias Ringwald 
18783cf37b8cSMatthias Ringwald     if (setup->sm_state_vars & SM_STATE_VAR_DHKEY_CALCULATED){
18793cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
18803cf37b8cSMatthias Ringwald         return;
18813cf37b8cSMatthias Ringwald     } else {
18823cf37b8cSMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W4_CALCULATE_DHKEY;
18833cf37b8cSMatthias Ringwald     }
1884d1a1f6a4SMatthias Ringwald }
18853cf37b8cSMatthias Ringwald 
1886d1a1f6a4SMatthias Ringwald static void sm_sc_dhkey_calculated(void * arg){
1887f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
1888f3582630SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
1889f3582630SMatthias Ringwald     if (sm_conn == NULL) return;
1890f3582630SMatthias Ringwald 
1891d1a1f6a4SMatthias Ringwald     log_info("dhkey");
1892d1a1f6a4SMatthias Ringwald     log_info_hexdump(&setup->sm_dhkey[0], 32);
1893d1a1f6a4SMatthias Ringwald     setup->sm_state_vars |= SM_STATE_VAR_DHKEY_CALCULATED;
1894d1a1f6a4SMatthias Ringwald     // trigger next step
1895d1a1f6a4SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_CALCULATE_DHKEY){
1896d1a1f6a4SMatthias Ringwald         sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F5_SALT;
1897d1a1f6a4SMatthias Ringwald     }
189870b44dd4SMatthias Ringwald     sm_trigger_run();
1899dc300847SMatthias Ringwald }
1900dc300847SMatthias Ringwald 
1901dc300847SMatthias Ringwald static void sm_sc_calculate_f6_for_dhkey_check(sm_connection_t * sm_conn){
1902dc300847SMatthias Ringwald     // calculate DHKCheck
1903dc300847SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1904dc300847SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1905dc300847SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19066535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19076535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1908dc300847SMatthias Ringwald     uint8_t iocap_a[3];
1909dc300847SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1910dc300847SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1911dc300847SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1912dc300847SMatthias Ringwald     uint8_t iocap_b[3];
1913dc300847SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1914dc300847SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1915dc300847SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
191642134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1917dc300847SMatthias Ringwald         // responder
191831f061fbSMatthias Ringwald         f6_setup(setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
191931f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1920dc300847SMatthias Ringwald     } else {
1921dc300847SMatthias Ringwald         // initiator
192231f061fbSMatthias Ringwald         f6_setup( setup->sm_local_nonce, setup->sm_peer_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
192331f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1924dc300847SMatthias Ringwald     }
1925dc300847SMatthias Ringwald }
1926dc300847SMatthias Ringwald 
1927019005a0SMatthias Ringwald static void sm_sc_calculate_f6_to_verify_dhkey_check(sm_connection_t * sm_conn){
1928019005a0SMatthias Ringwald     // validate E = f6()
1929019005a0SMatthias Ringwald     sm_key56_t bd_addr_master, bd_addr_slave;
1930019005a0SMatthias Ringwald     bd_addr_master[0] =  setup->sm_m_addr_type;
1931019005a0SMatthias Ringwald     bd_addr_slave[0]  =  setup->sm_s_addr_type;
19326535961aSMatthias Ringwald     (void)memcpy(&bd_addr_master[1], setup->sm_m_address, 6);
19336535961aSMatthias Ringwald     (void)memcpy(&bd_addr_slave[1], setup->sm_s_address, 6);
1934019005a0SMatthias Ringwald 
1935019005a0SMatthias Ringwald     uint8_t iocap_a[3];
1936019005a0SMatthias Ringwald     iocap_a[0] = sm_pairing_packet_get_auth_req(setup->sm_m_preq);
1937019005a0SMatthias Ringwald     iocap_a[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq);
1938019005a0SMatthias Ringwald     iocap_a[2] = sm_pairing_packet_get_io_capability(setup->sm_m_preq);
1939019005a0SMatthias Ringwald     uint8_t iocap_b[3];
1940019005a0SMatthias Ringwald     iocap_b[0] = sm_pairing_packet_get_auth_req(setup->sm_s_pres);
1941019005a0SMatthias Ringwald     iocap_b[1] = sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres);
1942019005a0SMatthias Ringwald     iocap_b[2] = sm_pairing_packet_get_io_capability(setup->sm_s_pres);
194342134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
1944019005a0SMatthias Ringwald         // responder
194531f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_rb, iocap_a, bd_addr_master, bd_addr_slave);
194631f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1947019005a0SMatthias Ringwald     } else {
1948019005a0SMatthias Ringwald         // initiator
194931f061fbSMatthias Ringwald         f6_setup(setup->sm_peer_nonce, setup->sm_local_nonce, setup->sm_ra, iocap_b, bd_addr_slave, bd_addr_master);
195031f061fbSMatthias Ringwald         f6_engine(sm_conn, setup->sm_mackey);
1951019005a0SMatthias Ringwald     }
1952019005a0SMatthias Ringwald }
19532bacf595SMatthias Ringwald 
195455c62cf5SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
19552bacf595SMatthias Ringwald 
19562bacf595SMatthias Ringwald //
19572bacf595SMatthias Ringwald // Link Key Conversion Function h6
19582bacf595SMatthias Ringwald //
195957132f12SMatthias Ringwald // h6(W, keyID) = AES-CMAC_W(keyID)
19602bacf595SMatthias Ringwald // - W is 128 bits
19612bacf595SMatthias Ringwald // - keyID is 32 bits
19622bacf595SMatthias Ringwald static void h6_engine(sm_connection_t * sm_conn, const sm_key_t w, const uint32_t key_id){
19632bacf595SMatthias Ringwald     const uint16_t message_len = 4;
19642bacf595SMatthias Ringwald     sm_cmac_connection = sm_conn;
19652bacf595SMatthias Ringwald     big_endian_store_32(sm_cmac_sc_buffer, 0, key_id);
19662bacf595SMatthias Ringwald     log_info("h6 key");
19672bacf595SMatthias Ringwald     log_info_hexdump(w, 16);
19682bacf595SMatthias Ringwald     log_info("h6 message");
19692bacf595SMatthias Ringwald     log_info_hexdump(sm_cmac_sc_buffer, message_len);
1970d1a1f6a4SMatthias Ringwald     sm_cmac_message_start(w, message_len, sm_cmac_sc_buffer, &sm_sc_cmac_done);
19712bacf595SMatthias Ringwald }
197257132f12SMatthias Ringwald //
197357132f12SMatthias Ringwald // Link Key Conversion Function h7
197457132f12SMatthias Ringwald //
197557132f12SMatthias Ringwald // h7(SALT, W) = AES-CMAC_SALT(W)
197657132f12SMatthias Ringwald // - SALT is 128 bits
197757132f12SMatthias Ringwald // - W    is 128 bits
197857132f12SMatthias Ringwald static void h7_engine(sm_connection_t * sm_conn, const sm_key_t salt, const sm_key_t w) {
197957132f12SMatthias Ringwald 	const uint16_t message_len = 16;
198057132f12SMatthias Ringwald 	sm_cmac_connection = sm_conn;
198157132f12SMatthias Ringwald 	log_info("h7 key");
198257132f12SMatthias Ringwald 	log_info_hexdump(salt, 16);
198357132f12SMatthias Ringwald 	log_info("h7 message");
198457132f12SMatthias Ringwald 	log_info_hexdump(w, 16);
198557132f12SMatthias Ringwald 	sm_cmac_message_start(salt, message_len, w, &sm_sc_cmac_done);
198657132f12SMatthias Ringwald }
19872bacf595SMatthias Ringwald 
1988b18300a6SMatthias Ringwald // For SC, setup->sm_local_ltk holds full LTK (sm_ltk is already truncated)
1989b18300a6SMatthias Ringwald // Errata Service Release to the Bluetooth Specification: ESR09
1990b18300a6SMatthias Ringwald //   E6405 – Cross transport key derivation from a key of size less than 128 bits
1991b18300a6SMatthias Ringwald //   "Note: When the BR/EDR link key is being derived from the LTK, the derivation is done before the LTK gets masked."
199257132f12SMatthias Ringwald 
1993c82679c3SMatthias Ringwald static void h6_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
1994b18300a6SMatthias Ringwald     h6_engine(sm_conn, setup->sm_local_ltk, 0x746D7031);    // "tmp1"
19952bacf595SMatthias Ringwald }
19962bacf595SMatthias Ringwald 
1997e0a03c85SMatthias Ringwald static void h6_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
1998e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_link_key, 0x746D7032);    // "tmp2"
1999e0a03c85SMatthias Ringwald }
2000e0a03c85SMatthias Ringwald 
20012bacf595SMatthias Ringwald static void h6_calculate_br_edr_link_key(sm_connection_t * sm_conn){
20022bacf595SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x6c656272);    // "lebr"
20032bacf595SMatthias Ringwald }
20042bacf595SMatthias Ringwald 
2005e0a03c85SMatthias Ringwald static void h6_calculate_le_ltk(sm_connection_t * sm_conn){
2006e0a03c85SMatthias Ringwald     h6_engine(sm_conn, setup->sm_t, 0x62726C65);    // "brle"
2007e0a03c85SMatthias Ringwald }
2008e0a03c85SMatthias Ringwald 
2009c82679c3SMatthias Ringwald static void h7_calculate_ilk_from_le_ltk(sm_connection_t * sm_conn){
201057132f12SMatthias Ringwald 	const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x31};  // "tmp1"
201157132f12SMatthias Ringwald 	h7_engine(sm_conn, salt, setup->sm_local_ltk);
201257132f12SMatthias Ringwald }
2013e0a03c85SMatthias Ringwald 
2014e0a03c85SMatthias Ringwald static void h7_calculate_ilk_from_br_edr(sm_connection_t * sm_conn){
2015e0a03c85SMatthias Ringwald     const uint8_t salt[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x74, 0x6D, 0x70, 0x32};  // "tmp2"
2016e0a03c85SMatthias Ringwald     h7_engine(sm_conn, salt, setup->sm_link_key);
2017e0a03c85SMatthias Ringwald }
2018e0a03c85SMatthias Ringwald 
2019c18be159SMatthias Ringwald static void sm_ctkd_fetch_br_edr_link_key(sm_connection_t * sm_conn){
2020e0a03c85SMatthias Ringwald     hci_connection_t * hci_connection = hci_connection_for_handle(sm_conn->sm_handle);
2021e0a03c85SMatthias Ringwald     btstack_assert(hci_connection != NULL);
2022e0a03c85SMatthias Ringwald     reverse_128(hci_connection->link_key, setup->sm_link_key);
2023e0a03c85SMatthias Ringwald     setup->sm_link_key_type =  hci_connection->link_key_type;
2024e0a03c85SMatthias Ringwald }
2025e0a03c85SMatthias Ringwald 
2026c18be159SMatthias Ringwald static void sm_ctkd_start_from_br_edr(sm_connection_t * connection){
2027c18be159SMatthias 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;
2028c18be159SMatthias Ringwald     connection->sm_engine_state = use_h7 ? SM_BR_EDR_W2_CALCULATE_ILK_USING_H7 : SM_BR_EDR_W2_CALCULATE_ILK_USING_H6;
2029c18be159SMatthias Ringwald }
2030c18be159SMatthias Ringwald 
20319af0f475SMatthias Ringwald #endif
20329af0f475SMatthias Ringwald 
203355c62cf5SMatthias Ringwald #endif
203455c62cf5SMatthias Ringwald 
2035613da3deSMatthias Ringwald // key management legacy connections:
2036613da3deSMatthias Ringwald // - potentially two different LTKs based on direction. each device stores LTK provided by peer
2037613da3deSMatthias Ringwald // - master stores LTK, EDIV, RAND. responder optionally stored master LTK (only if it needs to reconnect)
2038613da3deSMatthias Ringwald // - initiators reconnects: initiator uses stored LTK, EDIV, RAND generated by responder
2039613da3deSMatthias Ringwald // - responder  reconnects: responder uses LTK receveived from master
2040613da3deSMatthias Ringwald 
2041613da3deSMatthias Ringwald // key management secure connections:
2042613da3deSMatthias Ringwald // - both devices store same LTK from ECDH key exchange.
2043613da3deSMatthias Ringwald 
204442134bc6SMatthias Ringwald #if defined(ENABLE_LE_SECURE_CONNECTIONS) || defined(ENABLE_LE_CENTRAL)
20455829ebe2SMatthias Ringwald static void sm_load_security_info(sm_connection_t * sm_connection){
20465829ebe2SMatthias Ringwald     int encryption_key_size;
20475829ebe2SMatthias Ringwald     int authenticated;
20485829ebe2SMatthias Ringwald     int authorized;
20493dc3a67dSMatthias Ringwald     int secure_connection;
20505829ebe2SMatthias Ringwald 
20515829ebe2SMatthias Ringwald     // fetch data from device db - incl. authenticated/authorized/key size. Note all sm_connection_X require encryption enabled
20525829ebe2SMatthias Ringwald     le_device_db_encryption_get(sm_connection->sm_le_db_index, &setup->sm_peer_ediv, setup->sm_peer_rand, setup->sm_peer_ltk,
20533dc3a67dSMatthias Ringwald                                 &encryption_key_size, &authenticated, &authorized, &secure_connection);
20543dc3a67dSMatthias 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);
20555829ebe2SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = encryption_key_size;
20565829ebe2SMatthias Ringwald     sm_connection->sm_connection_authenticated = authenticated;
20575829ebe2SMatthias Ringwald     sm_connection->sm_connection_authorization_state = authorized ? AUTHORIZATION_GRANTED : AUTHORIZATION_UNKNOWN;
20583dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = secure_connection;
20595829ebe2SMatthias Ringwald }
206042134bc6SMatthias Ringwald #endif
2061bd57ffebSMatthias Ringwald 
206242134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
206359066796SMatthias Ringwald static void sm_start_calculating_ltk_from_ediv_and_rand(sm_connection_t * sm_connection){
20646535961aSMatthias Ringwald     (void)memcpy(setup->sm_local_rand, sm_connection->sm_local_rand, 8);
206559066796SMatthias Ringwald     setup->sm_local_ediv = sm_connection->sm_local_ediv;
206659066796SMatthias Ringwald     // re-establish used key encryption size
206759066796SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
20684ea43905SMatthias Ringwald     sm_connection->sm_actual_encryption_key_size = (setup->sm_local_rand[7u] & 0x0fu) + 1u;
206959066796SMatthias Ringwald     // no db for authenticated flag hack: flag is stored in bit 4 of LSB
20704ea43905SMatthias Ringwald     sm_connection->sm_connection_authenticated = (setup->sm_local_rand[7u] & 0x10u) >> 4u;
20713dc3a67dSMatthias Ringwald     // Legacy paring -> not SC
20723dc3a67dSMatthias Ringwald     sm_connection->sm_connection_sc = 0;
207359066796SMatthias Ringwald     log_info("sm: received ltk request with key size %u, authenticated %u",
207459066796SMatthias Ringwald             sm_connection->sm_actual_encryption_key_size, sm_connection->sm_connection_authenticated);
207559066796SMatthias Ringwald }
207642134bc6SMatthias Ringwald #endif
207759066796SMatthias Ringwald 
20783deb3ec6SMatthias Ringwald // distributed key generation
2079d7f1c72eSMatthias Ringwald static bool sm_run_dpkg(void){
20803deb3ec6SMatthias Ringwald     switch (dkg_state){
20813deb3ec6SMatthias Ringwald         case DKG_CALC_IRK:
20823deb3ec6SMatthias Ringwald             // already busy?
20833deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2084d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_IRK started");
20853deb3ec6SMatthias Ringwald                 // IRK = d1(IR, 1, 0)
2086d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(1, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2087d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2088d1a1f6a4SMatthias 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);
2089d7f1c72eSMatthias Ringwald                 return true;
20903deb3ec6SMatthias Ringwald             }
20913deb3ec6SMatthias Ringwald             break;
20923deb3ec6SMatthias Ringwald         case DKG_CALC_DHK:
20933deb3ec6SMatthias Ringwald             // already busy?
20943deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2095d1a1f6a4SMatthias Ringwald                 log_info("DKG_CALC_DHK started");
20963deb3ec6SMatthias Ringwald                 // DHK = d1(IR, 3, 0)
2097d1a1f6a4SMatthias Ringwald                 sm_d1_d_prime(3, 0, sm_aes128_plaintext);  // plaintext = d1 prime
2098d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2099d1a1f6a4SMatthias 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);
2100d7f1c72eSMatthias Ringwald                 return true;
21013deb3ec6SMatthias Ringwald             }
21023deb3ec6SMatthias Ringwald             break;
21033deb3ec6SMatthias Ringwald         default:
21043deb3ec6SMatthias Ringwald             break;
21053deb3ec6SMatthias Ringwald     }
2106d7f1c72eSMatthias Ringwald     return false;
2107d7f1c72eSMatthias Ringwald }
21083deb3ec6SMatthias Ringwald 
21093deb3ec6SMatthias Ringwald // random address updates
2110d7f1c72eSMatthias Ringwald static bool sm_run_rau(void){
21113deb3ec6SMatthias Ringwald     switch (rau_state){
2112fbd4e238SMatthias Ringwald         case RAU_GET_RANDOM:
2113fbd4e238SMatthias Ringwald             rau_state = RAU_W4_RANDOM;
21145b4dd597SMatthias Ringwald             btstack_crypto_random_generate(&sm_crypto_random_request, sm_random_address, 6, &sm_handle_random_result_rau, NULL);
2115d7f1c72eSMatthias Ringwald             return true;
21163deb3ec6SMatthias Ringwald         case RAU_GET_ENC:
21173deb3ec6SMatthias Ringwald             // already busy?
21183deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_IDLE) {
2119d1a1f6a4SMatthias Ringwald                 sm_ah_r_prime(sm_random_address, sm_aes128_plaintext);
2120d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2121d1a1f6a4SMatthias Ringwald                 btstack_crypto_aes128_encrypt(&sm_crypto_aes128_request, sm_persistent_irk, sm_aes128_plaintext, sm_aes128_ciphertext, sm_handle_encryption_result_rau, NULL);
2122d7f1c72eSMatthias Ringwald                 return true;
21233deb3ec6SMatthias Ringwald             }
21243deb3ec6SMatthias Ringwald             break;
21253deb3ec6SMatthias Ringwald         default:
21263deb3ec6SMatthias Ringwald             break;
21273deb3ec6SMatthias Ringwald     }
2128d7f1c72eSMatthias Ringwald     return false;
2129d7f1c72eSMatthias Ringwald }
21303deb3ec6SMatthias Ringwald 
21313deb3ec6SMatthias Ringwald // CSRK Lookup
2132d7f1c72eSMatthias Ringwald static bool sm_run_csrk(void){
2133d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
2134d7f1c72eSMatthias Ringwald 
21353deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, find connection that require csrk lookup
21363deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()){
21373deb3ec6SMatthias Ringwald         hci_connections_get_iterator(&it);
2138665d90f2SMatthias Ringwald         while(btstack_linked_list_iterator_has_next(&it)){
2139665d90f2SMatthias Ringwald             hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
21403deb3ec6SMatthias Ringwald             sm_connection_t  * sm_connection  = &hci_connection->sm_connection;
21413deb3ec6SMatthias Ringwald             if (sm_connection->sm_irk_lookup_state == IRK_LOOKUP_W4_READY){
21423deb3ec6SMatthias Ringwald                 // and start lookup
21433deb3ec6SMatthias 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);
21443deb3ec6SMatthias Ringwald                 sm_connection->sm_irk_lookup_state = IRK_LOOKUP_STARTED;
21453deb3ec6SMatthias Ringwald                 break;
21463deb3ec6SMatthias Ringwald             }
21473deb3ec6SMatthias Ringwald         }
21483deb3ec6SMatthias Ringwald     }
21493deb3ec6SMatthias Ringwald 
21503deb3ec6SMatthias Ringwald     // -- if csrk lookup ready, resolved addresses for received addresses
21513deb3ec6SMatthias Ringwald     if (sm_address_resolution_idle()) {
2152665d90f2SMatthias Ringwald         if (!btstack_linked_list_empty(&sm_address_resolution_general_queue)){
21533deb3ec6SMatthias Ringwald             sm_lookup_entry_t * entry = (sm_lookup_entry_t *) sm_address_resolution_general_queue;
2154665d90f2SMatthias Ringwald             btstack_linked_list_remove(&sm_address_resolution_general_queue, (btstack_linked_item_t *) entry);
21553deb3ec6SMatthias Ringwald             sm_address_resolution_start_lookup(entry->address_type, 0, entry->address, ADDRESS_RESOLUTION_GENERAL, NULL);
21563deb3ec6SMatthias Ringwald             btstack_memory_sm_lookup_entry_free(entry);
21573deb3ec6SMatthias Ringwald         }
21583deb3ec6SMatthias Ringwald     }
21593deb3ec6SMatthias Ringwald 
21603deb3ec6SMatthias Ringwald     // -- Continue with CSRK device lookup by public or resolvable private address
21613deb3ec6SMatthias Ringwald     if (!sm_address_resolution_idle()){
2162092ec58eSMatthias Ringwald         log_info("LE Device Lookup: device %u/%u", sm_address_resolution_test, le_device_db_max_count());
2163092ec58eSMatthias Ringwald         while (sm_address_resolution_test < le_device_db_max_count()){
2164adf5eaa9SMatthias Ringwald             int addr_type = BD_ADDR_TYPE_UNKNOWN;
21653deb3ec6SMatthias Ringwald             bd_addr_t addr;
21663deb3ec6SMatthias Ringwald             sm_key_t irk;
21673deb3ec6SMatthias Ringwald             le_device_db_info(sm_address_resolution_test, &addr_type, addr, irk);
21683deb3ec6SMatthias Ringwald             log_info("device type %u, addr: %s", addr_type, bd_addr_to_str(addr));
21693deb3ec6SMatthias Ringwald 
2170adf5eaa9SMatthias Ringwald             // skip unused entries
2171adf5eaa9SMatthias Ringwald             if (addr_type == BD_ADDR_TYPE_UNKNOWN){
2172adf5eaa9SMatthias Ringwald                 sm_address_resolution_test++;
2173adf5eaa9SMatthias Ringwald                 continue;
2174adf5eaa9SMatthias Ringwald             }
2175adf5eaa9SMatthias Ringwald 
21765df9dc78SMatthias Ringwald             if ((sm_address_resolution_addr_type == addr_type) && (memcmp(addr, sm_address_resolution_address, 6) == 0)){
21773deb3ec6SMatthias Ringwald                 log_info("LE Device Lookup: found CSRK by { addr_type, address} ");
2178a66b030fSMatthias Ringwald                 sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
21793deb3ec6SMatthias Ringwald                 break;
21803deb3ec6SMatthias Ringwald             }
21813deb3ec6SMatthias Ringwald 
2182a9987c8eSMatthias Ringwald             // if connection type is public, it must be a different one
2183a9987c8eSMatthias Ringwald             if (sm_address_resolution_addr_type == BD_ADDR_TYPE_LE_PUBLIC){
21843deb3ec6SMatthias Ringwald                 sm_address_resolution_test++;
21853deb3ec6SMatthias Ringwald                 continue;
21863deb3ec6SMatthias Ringwald             }
21873deb3ec6SMatthias Ringwald 
21883deb3ec6SMatthias Ringwald             if (sm_aes128_state == SM_AES128_ACTIVE) break;
21893deb3ec6SMatthias Ringwald 
21903deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: calculate AH");
21918314c363SMatthias Ringwald             log_info_key("IRK", irk);
21923deb3ec6SMatthias Ringwald 
21936535961aSMatthias Ringwald             (void)memcpy(sm_aes128_key, irk, 16);
2194d1a1f6a4SMatthias Ringwald             sm_ah_r_prime(sm_address_resolution_address, sm_aes128_plaintext);
21953deb3ec6SMatthias Ringwald             sm_address_resolution_ah_calculation_active = 1;
2196d1a1f6a4SMatthias Ringwald             sm_aes128_state = SM_AES128_ACTIVE;
2197d1a1f6a4SMatthias 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);
2198d7f1c72eSMatthias Ringwald             return true;
21993deb3ec6SMatthias Ringwald         }
22003deb3ec6SMatthias Ringwald 
2201092ec58eSMatthias Ringwald         if (sm_address_resolution_test >= le_device_db_max_count()){
22023deb3ec6SMatthias Ringwald             log_info("LE Device Lookup: not found");
22033deb3ec6SMatthias Ringwald             sm_address_resolution_handle_event(ADDRESS_RESOLUTION_FAILED);
22043deb3ec6SMatthias Ringwald         }
22053deb3ec6SMatthias Ringwald     }
2206d7f1c72eSMatthias Ringwald     return false;
2207d7f1c72eSMatthias Ringwald }
22083deb3ec6SMatthias Ringwald 
2209d7f1c72eSMatthias Ringwald // SC OOB
2210d7f1c72eSMatthias Ringwald static bool sm_run_oob(void){
2211c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2212c59d0c92SMatthias Ringwald     switch (sm_sc_oob_state){
2213c59d0c92SMatthias Ringwald         case SM_SC_OOB_W2_CALC_CONFIRM:
2214c59d0c92SMatthias Ringwald             if (!sm_cmac_ready()) break;
2215c59d0c92SMatthias Ringwald             sm_sc_oob_state = SM_SC_OOB_W4_CONFIRM;
2216c59d0c92SMatthias Ringwald             f4_engine(NULL, ec_q, ec_q, sm_sc_oob_random, 0);
2217d7f1c72eSMatthias Ringwald             return true;
2218c59d0c92SMatthias Ringwald         default:
2219c59d0c92SMatthias Ringwald             break;
2220c59d0c92SMatthias Ringwald     }
2221c59d0c92SMatthias Ringwald #endif
2222d7f1c72eSMatthias Ringwald     return false;
2223d7f1c72eSMatthias Ringwald }
2224275aafe8SMatthias Ringwald 
2225687a03c8SMatthias Ringwald static void sm_send_connectionless(sm_connection_t * sm_connection, const uint8_t * buffer, uint16_t size){
2226687a03c8SMatthias Ringwald     l2cap_send_connectionless(sm_connection->sm_handle, sm_connection->sm_cid, (uint8_t*) buffer, size);
2227687a03c8SMatthias Ringwald }
2228687a03c8SMatthias Ringwald 
222941d32297SMatthias Ringwald // handle basic actions that don't requires the full context
2230d7f1c72eSMatthias Ringwald static bool sm_run_basic(void){
2231d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
223241d32297SMatthias Ringwald     hci_connections_get_iterator(&it);
2233e9af1bf6SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
223441d32297SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
223541d32297SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
223641d32297SMatthias Ringwald         switch(sm_connection->sm_engine_state){
2237f4935286SMatthias Ringwald 
2238f4935286SMatthias Ringwald             // general
2239f4935286SMatthias Ringwald             case SM_GENERAL_SEND_PAIRING_FAILED: {
2240f4935286SMatthias Ringwald                 uint8_t buffer[2];
2241f4935286SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_FAILED;
2242f4935286SMatthias Ringwald                 buffer[1] = sm_connection->sm_pairing_failed_reason;
2243f4935286SMatthias Ringwald                 sm_connection->sm_engine_state = sm_connection->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
2244687a03c8SMatthias Ringwald                 sm_send_connectionless(sm_connection, (uint8_t*) buffer, sizeof(buffer));
2245f4935286SMatthias Ringwald                 sm_pairing_complete(sm_connection, ERROR_CODE_AUTHENTICATION_FAILURE, sm_connection->sm_pairing_failed_reason);
2246f4935286SMatthias Ringwald                 sm_done_for_handle(sm_connection->sm_handle);
2247f4935286SMatthias Ringwald                 break;
2248f4935286SMatthias Ringwald             }
2249f4935286SMatthias Ringwald 
225041d32297SMatthias Ringwald             // responder side
225141d32297SMatthias Ringwald             case SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY:
225241d32297SMatthias Ringwald                 sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
225341d32297SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2254d7f1c72eSMatthias Ringwald                 return true;
22554b8b5afeSMatthias Ringwald 
22564b8b5afeSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
22574b8b5afeSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
22584b8b5afeSMatthias Ringwald                 switch (sm_connection->sm_irk_lookup_state){
22594b8b5afeSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
2260e9af1bf6SMatthias Ringwald                         log_info("LTK Request: IRK Lookup Failed)");
22614b8b5afeSMatthias Ringwald                         sm_connection->sm_engine_state = SM_RESPONDER_IDLE;
22624b8b5afeSMatthias Ringwald                         hci_send_cmd(&hci_le_long_term_key_negative_reply, sm_connection->sm_handle);
2263d7f1c72eSMatthias Ringwald                         return true;
22644b8b5afeSMatthias Ringwald                     default:
22654b8b5afeSMatthias Ringwald                         break;
22664b8b5afeSMatthias Ringwald                 }
22674b8b5afeSMatthias Ringwald                 break;
22684b8b5afeSMatthias Ringwald #endif
226941d32297SMatthias Ringwald             default:
227041d32297SMatthias Ringwald                 break;
227141d32297SMatthias Ringwald         }
227241d32297SMatthias Ringwald     }
2273d7f1c72eSMatthias Ringwald     return false;
2274d7f1c72eSMatthias Ringwald }
22753deb3ec6SMatthias Ringwald 
2276d7f1c72eSMatthias Ringwald static void sm_run_activate_connection(void){
22773deb3ec6SMatthias Ringwald     // Find connections that requires setup context and make active if no other is locked
2278d7f1c72eSMatthias Ringwald     btstack_linked_list_iterator_t it;
22793deb3ec6SMatthias Ringwald     hci_connections_get_iterator(&it);
22807149bde5SMatthias Ringwald     while((sm_active_connection_handle == HCI_CON_HANDLE_INVALID) && btstack_linked_list_iterator_has_next(&it)){
2281665d90f2SMatthias Ringwald         hci_connection_t * hci_connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
22823deb3ec6SMatthias Ringwald         sm_connection_t  * sm_connection = &hci_connection->sm_connection;
22833deb3ec6SMatthias Ringwald         // - if no connection locked and we're ready/waiting for setup context, fetch it and start
22841979f09cSMatthias Ringwald         bool done = true;
22853deb3ec6SMatthias Ringwald         int err;
228642134bc6SMatthias Ringwald         UNUSED(err);
228734b6528fSMatthias Ringwald 
228834b6528fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
228934b6528fSMatthias Ringwald         // assert ec key is ready
2290505f1c30SMatthias Ringwald         if (   (sm_connection->sm_engine_state == SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED)
2291178e8c1bSMatthias Ringwald             || (sm_connection->sm_engine_state == SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST)
2292178e8c1bSMatthias Ringwald 			|| (sm_connection->sm_engine_state == SM_RESPONDER_SEND_SECURITY_REQUEST)){
229334b6528fSMatthias Ringwald             if (ec_key_generation_state == EC_KEY_GENERATION_IDLE){
229434b6528fSMatthias Ringwald                 sm_ec_generate_new_key();
229534b6528fSMatthias Ringwald             }
229634b6528fSMatthias Ringwald             if (ec_key_generation_state != EC_KEY_GENERATION_DONE){
229734b6528fSMatthias Ringwald                 continue;
229834b6528fSMatthias Ringwald             }
229934b6528fSMatthias Ringwald         }
230034b6528fSMatthias Ringwald #endif
230134b6528fSMatthias Ringwald 
23023deb3ec6SMatthias Ringwald         switch (sm_connection->sm_engine_state) {
230342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
23043deb3ec6SMatthias Ringwald             case SM_RESPONDER_SEND_SECURITY_REQUEST:
23053deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
230642134bc6SMatthias Ringwald             case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
2307549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
230806cd539fSMatthias Ringwald             case SM_SC_RECEIVED_LTK_REQUEST:
230987014f74SMatthias Ringwald #endif
231087014f74SMatthias Ringwald #endif
231134c39fbdSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
23125567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK:
231334c39fbdSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2314549ad5d2SMatthias Ringwald #endif
2315c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2316c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
2317c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
2318c18be159SMatthias Ringwald #endif
231987014f74SMatthias Ringwald 				// just lock context
232087014f74SMatthias Ringwald 				break;
23213deb3ec6SMatthias Ringwald             default:
23221979f09cSMatthias Ringwald                 done = false;
23233deb3ec6SMatthias Ringwald                 break;
23243deb3ec6SMatthias Ringwald         }
23253deb3ec6SMatthias Ringwald         if (done){
23267149bde5SMatthias Ringwald             sm_active_connection_handle = sm_connection->sm_handle;
23277149bde5SMatthias 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);
23283deb3ec6SMatthias Ringwald         }
23293deb3ec6SMatthias Ringwald     }
2330d7f1c72eSMatthias Ringwald }
2331d7f1c72eSMatthias Ringwald 
2332403280b9SMatthias Ringwald static void sm_run_send_keypress_notification(sm_connection_t * connection){
2333403280b9SMatthias Ringwald     int i;
2334403280b9SMatthias Ringwald     uint8_t flags       = setup->sm_keypress_notification & 0x1fu;
2335403280b9SMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
2336403280b9SMatthias Ringwald     uint8_t action = 0;
2337403280b9SMatthias Ringwald     for (i=SM_KEYPRESS_PASSKEY_ENTRY_STARTED;i<=SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED;i++){
2338403280b9SMatthias Ringwald         if (flags & (1u<<i)){
2339403280b9SMatthias Ringwald             bool clear_flag = true;
2340403280b9SMatthias Ringwald             switch (i){
2341403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
2342403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_CLEARED:
2343403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
2344403280b9SMatthias Ringwald                 default:
2345403280b9SMatthias Ringwald                     break;
2346403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
2347403280b9SMatthias Ringwald                 case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
2348403280b9SMatthias Ringwald                     num_actions--;
2349403280b9SMatthias Ringwald                     clear_flag = num_actions == 0u;
2350403280b9SMatthias Ringwald                     break;
2351403280b9SMatthias Ringwald             }
2352403280b9SMatthias Ringwald             if (clear_flag){
2353403280b9SMatthias Ringwald                 flags &= ~(1<<i);
2354403280b9SMatthias Ringwald             }
2355403280b9SMatthias Ringwald             action = i;
2356403280b9SMatthias Ringwald             break;
2357403280b9SMatthias Ringwald         }
2358403280b9SMatthias Ringwald     }
2359403280b9SMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
2360403280b9SMatthias Ringwald 
2361403280b9SMatthias Ringwald     // send keypress notification
2362403280b9SMatthias Ringwald     uint8_t buffer[2];
2363403280b9SMatthias Ringwald     buffer[0] = SM_CODE_KEYPRESS_NOTIFICATION;
2364403280b9SMatthias Ringwald     buffer[1] = action;
2365687a03c8SMatthias Ringwald     sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2366403280b9SMatthias Ringwald 
2367403280b9SMatthias Ringwald     // try
2368403280b9SMatthias Ringwald     l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2369403280b9SMatthias Ringwald }
2370403280b9SMatthias Ringwald 
2371403280b9SMatthias Ringwald static void sm_run_distribute_keys(sm_connection_t * connection){
2372403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION){
2373403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2374403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
2375403280b9SMatthias Ringwald         uint8_t buffer[17];
2376403280b9SMatthias Ringwald         buffer[0] = SM_CODE_ENCRYPTION_INFORMATION;
2377403280b9SMatthias Ringwald         reverse_128(setup->sm_ltk, &buffer[1]);
2378687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2379403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2380403280b9SMatthias Ringwald         return;
2381403280b9SMatthias Ringwald     }
2382403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_MASTER_IDENTIFICATION){
2383403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2384403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
2385403280b9SMatthias Ringwald         uint8_t buffer[11];
2386403280b9SMatthias Ringwald         buffer[0] = SM_CODE_MASTER_IDENTIFICATION;
2387403280b9SMatthias Ringwald         little_endian_store_16(buffer, 1, setup->sm_local_ediv);
2388403280b9SMatthias Ringwald         reverse_64(setup->sm_local_rand, &buffer[3]);
2389687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2390403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2391403280b9SMatthias Ringwald         return;
2392403280b9SMatthias Ringwald     }
2393403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_INFORMATION){
2394403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2395403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
2396403280b9SMatthias Ringwald         uint8_t buffer[17];
2397403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_INFORMATION;
2398403280b9SMatthias Ringwald         reverse_128(sm_persistent_irk, &buffer[1]);
2399687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2400403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2401403280b9SMatthias Ringwald         return;
2402403280b9SMatthias Ringwald     }
2403403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION){
2404403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2405403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
2406403280b9SMatthias Ringwald         bd_addr_t local_address;
2407403280b9SMatthias Ringwald         uint8_t buffer[8];
2408403280b9SMatthias Ringwald         buffer[0] = SM_CODE_IDENTITY_ADDRESS_INFORMATION;
2409403280b9SMatthias Ringwald         switch (gap_random_address_get_mode()){
2410403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_OFF:
2411403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_TYPE_STATIC:
2412403280b9SMatthias Ringwald                 // public or static random
2413403280b9SMatthias Ringwald                 gap_le_get_own_address(&buffer[1], local_address);
2414403280b9SMatthias Ringwald                 break;
2415403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
2416403280b9SMatthias Ringwald             case GAP_RANDOM_ADDRESS_RESOLVABLE:
2417403280b9SMatthias Ringwald                 // fallback to public
2418403280b9SMatthias Ringwald                 gap_local_bd_addr(local_address);
2419403280b9SMatthias Ringwald                 buffer[1] = 0;
2420403280b9SMatthias Ringwald                 break;
2421403280b9SMatthias Ringwald             default:
2422403280b9SMatthias Ringwald                 btstack_assert(false);
2423403280b9SMatthias Ringwald                 break;
2424403280b9SMatthias Ringwald         }
2425403280b9SMatthias Ringwald         reverse_bd_addr(local_address, &buffer[2]);
2426687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2427403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2428403280b9SMatthias Ringwald         return;
2429403280b9SMatthias Ringwald     }
2430403280b9SMatthias Ringwald     if (setup->sm_key_distribution_send_set &   SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION){
2431403280b9SMatthias Ringwald         setup->sm_key_distribution_send_set &= ~SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2432403280b9SMatthias Ringwald         setup->sm_key_distribution_sent_set |=  SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
2433403280b9SMatthias Ringwald 
2434403280b9SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
2435403280b9SMatthias Ringwald         // hack to reproduce test runs
2436403280b9SMatthias Ringwald                     if (test_use_fixed_local_csrk){
2437403280b9SMatthias Ringwald                         memset(setup->sm_local_csrk, 0xcc, 16);
2438403280b9SMatthias Ringwald                     }
2439403280b9SMatthias Ringwald 
2440403280b9SMatthias Ringwald                     // store local CSRK
2441403280b9SMatthias Ringwald                     if (setup->sm_le_device_index >= 0){
2442403280b9SMatthias Ringwald                         log_info("sm: store local CSRK");
2443403280b9SMatthias Ringwald                         le_device_db_local_csrk_set(setup->sm_le_device_index, setup->sm_local_csrk);
2444403280b9SMatthias Ringwald                         le_device_db_local_counter_set(setup->sm_le_device_index, 0);
2445403280b9SMatthias Ringwald                     }
2446403280b9SMatthias Ringwald #endif
2447403280b9SMatthias Ringwald 
2448403280b9SMatthias Ringwald         uint8_t buffer[17];
2449403280b9SMatthias Ringwald         buffer[0] = SM_CODE_SIGNING_INFORMATION;
2450403280b9SMatthias Ringwald         reverse_128(setup->sm_local_csrk, &buffer[1]);
2451687a03c8SMatthias Ringwald         sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2452403280b9SMatthias Ringwald         sm_timeout_reset(connection);
2453403280b9SMatthias Ringwald         return;
2454403280b9SMatthias Ringwald     }
2455403280b9SMatthias Ringwald     btstack_assert(false);
2456403280b9SMatthias Ringwald }
2457403280b9SMatthias Ringwald 
2458bbd73538SMatthias Ringwald static bool sm_ctkd_from_le(sm_connection_t *sm_connection) {
2459bbd73538SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
2460bbd73538SMatthias Ringwald     // requirements to derive link key from  LE:
2461bbd73538SMatthias Ringwald     // - use secure connections
2462bbd73538SMatthias Ringwald     if (setup->sm_use_secure_connections == 0) return false;
2463bbd73538SMatthias Ringwald     // - bonding needs to be enabled:
2464bbd73538SMatthias 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;
2465bbd73538SMatthias Ringwald     if (!bonding_enabled) return false;
2466bbd73538SMatthias Ringwald     // - need identity address / public addr
2467bbd73538SMatthias 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);
2468bbd73538SMatthias Ringwald     if (!have_identity_address_info) return false;
2469bbd73538SMatthias 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)
2470bbd73538SMatthias Ringwald     //   this requirement is motivated by BLURtooth paper. The paper recommends to not overwrite keys at all.
2471bbd73538SMatthias Ringwald     //      If SC is authenticated, we consider it safe to overwrite a stored key.
2472bbd73538SMatthias 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.
2473bbd73538SMatthias Ringwald     uint8_t link_key[16];
2474bbd73538SMatthias Ringwald     link_key_type_t link_key_type;
2475bbd73538SMatthias Ringwald     bool have_link_key             = gap_get_link_key_for_bd_addr(setup->sm_peer_address, link_key, &link_key_type);
2476bbd73538SMatthias Ringwald     bool link_key_authenticated    = gap_authenticated_for_link_key_type(link_key_type) != 0;
2477bbd73538SMatthias Ringwald     bool derived_key_authenticated = sm_connection->sm_connection_authenticated != 0;
2478bbd73538SMatthias Ringwald     if (have_link_key && link_key_authenticated && !derived_key_authenticated) {
2479bbd73538SMatthias Ringwald         return false;
2480bbd73538SMatthias Ringwald     }
2481bbd73538SMatthias Ringwald     // get started (all of the above are true)
2482bbd73538SMatthias Ringwald     return true;
2483bbd73538SMatthias Ringwald #else
2484bbd73538SMatthias Ringwald     UNUSED(sm_connection);
2485bbd73538SMatthias Ringwald 	return false;
2486bbd73538SMatthias Ringwald #endif
2487bbd73538SMatthias Ringwald }
2488bbd73538SMatthias Ringwald 
24896f7422f1SMatthias Ringwald static void sm_key_distribution_complete_responder(sm_connection_t * connection){
24906f7422f1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
24916f7422f1SMatthias 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;
24926f7422f1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
24936f7422f1SMatthias Ringwald     } else {
24946f7422f1SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_IDLE;
24956f7422f1SMatthias Ringwald         sm_pairing_complete(connection, ERROR_CODE_SUCCESS, 0);
24966f7422f1SMatthias Ringwald         sm_done_for_handle(connection->sm_handle);
24976f7422f1SMatthias Ringwald     }
24986f7422f1SMatthias Ringwald }
24996f7422f1SMatthias Ringwald 
2500af7ef9d1SMatthias Ringwald static void sm_key_distribution_complete_initiator(sm_connection_t * connection){
2501af7ef9d1SMatthias Ringwald     if (sm_ctkd_from_le(connection)){
2502af7ef9d1SMatthias 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;
2503af7ef9d1SMatthias Ringwald         connection->sm_engine_state = use_h7 ? SM_SC_W2_CALCULATE_ILK_USING_H7 : SM_SC_W2_CALCULATE_ILK_USING_H6;
2504af7ef9d1SMatthias Ringwald     } else {
2505af7ef9d1SMatthias Ringwald         sm_master_pairing_success(connection);
2506af7ef9d1SMatthias Ringwald     }
2507af7ef9d1SMatthias Ringwald }
2508af7ef9d1SMatthias Ringwald 
2509d7f1c72eSMatthias Ringwald static void sm_run(void){
2510d7f1c72eSMatthias Ringwald 
2511d7f1c72eSMatthias Ringwald     // assert that stack has already bootet
2512d7f1c72eSMatthias Ringwald     if (hci_get_state() != HCI_STATE_WORKING) return;
2513d7f1c72eSMatthias Ringwald 
2514d7f1c72eSMatthias Ringwald     // assert that we can send at least commands
2515d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2516d7f1c72eSMatthias Ringwald 
2517d7f1c72eSMatthias Ringwald     // pause until IR/ER are ready
2518d7f1c72eSMatthias Ringwald     if (sm_persistent_keys_random_active) return;
2519d7f1c72eSMatthias Ringwald 
2520d7f1c72eSMatthias Ringwald     bool done;
2521d7f1c72eSMatthias Ringwald 
2522d7f1c72eSMatthias Ringwald     //
2523d7f1c72eSMatthias Ringwald     // non-connection related behaviour
2524d7f1c72eSMatthias Ringwald     //
2525d7f1c72eSMatthias Ringwald 
2526d7f1c72eSMatthias Ringwald     done = sm_run_dpkg();
2527d7f1c72eSMatthias Ringwald     if (done) return;
2528d7f1c72eSMatthias Ringwald 
2529d7f1c72eSMatthias Ringwald     done = sm_run_rau();
2530d7f1c72eSMatthias Ringwald     if (done) return;
2531d7f1c72eSMatthias Ringwald 
2532d7f1c72eSMatthias Ringwald     done = sm_run_csrk();
2533d7f1c72eSMatthias Ringwald     if (done) return;
2534d7f1c72eSMatthias Ringwald 
2535d7f1c72eSMatthias Ringwald     done = sm_run_oob();
2536d7f1c72eSMatthias Ringwald     if (done) return;
2537d7f1c72eSMatthias Ringwald 
2538d7f1c72eSMatthias Ringwald     // assert that we can send at least commands - cmd might have been sent by crypto engine
2539d7f1c72eSMatthias Ringwald     if (!hci_can_send_command_packet_now()) return;
2540d7f1c72eSMatthias Ringwald 
2541d7f1c72eSMatthias Ringwald     // handle basic actions that don't requires the full context
2542d7f1c72eSMatthias Ringwald     done = sm_run_basic();
2543d7f1c72eSMatthias Ringwald     if (done) return;
2544d7f1c72eSMatthias Ringwald 
2545d7f1c72eSMatthias Ringwald     //
2546d7f1c72eSMatthias Ringwald     // active connection handling
2547d7f1c72eSMatthias Ringwald     // -- use loop to handle next connection if lock on setup context is released
2548d7f1c72eSMatthias Ringwald 
2549d7f1c72eSMatthias Ringwald     while (true) {
2550d7f1c72eSMatthias Ringwald 
2551d7f1c72eSMatthias Ringwald         sm_run_activate_connection();
2552d7f1c72eSMatthias Ringwald 
2553d7f1c72eSMatthias Ringwald         if (sm_active_connection_handle == HCI_CON_HANDLE_INVALID) return;
25543deb3ec6SMatthias Ringwald 
25553deb3ec6SMatthias Ringwald         //
25563deb3ec6SMatthias Ringwald         // active connection handling
25573deb3ec6SMatthias Ringwald         //
25583deb3ec6SMatthias Ringwald 
25593cf37b8cSMatthias Ringwald         sm_connection_t * connection = sm_get_connection_for_handle(sm_active_connection_handle);
25603cf37b8cSMatthias Ringwald         if (!connection) {
25613cf37b8cSMatthias Ringwald             log_info("no connection for handle 0x%04x", sm_active_connection_handle);
25623cf37b8cSMatthias Ringwald             return;
25633cf37b8cSMatthias Ringwald         }
25643cf37b8cSMatthias Ringwald 
25653deb3ec6SMatthias Ringwald         // assert that we could send a SM PDU - not needed for all of the following
25667149bde5SMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
25677149bde5SMatthias Ringwald             log_info("cannot send now, requesting can send now event");
25687149bde5SMatthias Ringwald             l2cap_request_can_send_fix_channel_now_event(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
2569b170b20fSMatthias Ringwald             return;
2570b170b20fSMatthias Ringwald         }
25713deb3ec6SMatthias Ringwald 
25723d7fe1e9SMatthias Ringwald         // send keypress notifications
2573dd4a08fbSMatthias Ringwald         if (setup->sm_keypress_notification){
2574403280b9SMatthias Ringwald             sm_run_send_keypress_notification(connection);
2575d7471931SMatthias Ringwald             return;
25763d7fe1e9SMatthias Ringwald         }
25773d7fe1e9SMatthias Ringwald 
25783deb3ec6SMatthias Ringwald         int key_distribution_flags;
257942134bc6SMatthias Ringwald         UNUSED(key_distribution_flags);
2580b6afa23eSMatthias Ringwald 		int err;
2581b6afa23eSMatthias Ringwald 		UNUSED(err);
25829b75de03SMatthias Ringwald         bool have_ltk;
25839b75de03SMatthias Ringwald         uint8_t ltk[16];
25843deb3ec6SMatthias Ringwald 
25853deb3ec6SMatthias Ringwald         log_info("sm_run: state %u", connection->sm_engine_state);
2586dd4a08fbSMatthias Ringwald         if (!l2cap_can_send_fixed_channel_packet_now(sm_active_connection_handle, L2CAP_CID_SECURITY_MANAGER_PROTOCOL)) {
2587dd4a08fbSMatthias Ringwald             log_info("sm_run // cannot send");
2588dd4a08fbSMatthias Ringwald         }
25893deb3ec6SMatthias Ringwald         switch (connection->sm_engine_state){
25903deb3ec6SMatthias Ringwald 
2591f32b7a88SMatthias Ringwald             // secure connections, initiator + responding states
2592aec94140SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2593aec94140SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CONFIRMATION:
2594aec94140SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2595aec94140SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CONFIRMATION;
2596aec94140SMatthias Ringwald                 sm_sc_calculate_local_confirm(connection);
2597aec94140SMatthias Ringwald                 break;
2598688a08f9SMatthias Ringwald             case SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION:
2599688a08f9SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2600688a08f9SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CMAC_FOR_CHECK_CONFIRMATION;
2601688a08f9SMatthias Ringwald                 sm_sc_calculate_remote_confirm(connection);
2602688a08f9SMatthias Ringwald                 break;
2603dc300847SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
2604dc300847SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2605dc300847SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK;
2606dc300847SMatthias Ringwald                 sm_sc_calculate_f6_for_dhkey_check(connection);
2607dc300847SMatthias Ringwald                 break;
2608019005a0SMatthias Ringwald             case SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK:
2609b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2610019005a0SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
26110346c37cSMatthias Ringwald                 sm_sc_calculate_f6_to_verify_dhkey_check(connection);
26120346c37cSMatthias Ringwald                 break;
26130346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_SALT:
2614b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26150346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_SALT;
26160346c37cSMatthias Ringwald                 f5_calculate_salt(connection);
26170346c37cSMatthias Ringwald                 break;
26180346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_MACKEY:
2619b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26200346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_MACKEY;
26210346c37cSMatthias Ringwald                 f5_calculate_mackey(connection);
26220346c37cSMatthias Ringwald                 break;
26230346c37cSMatthias Ringwald             case SM_SC_W2_CALCULATE_F5_LTK:
2624b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
26250346c37cSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_F5_LTK;
26260346c37cSMatthias Ringwald                 f5_calculate_ltk(connection);
2627019005a0SMatthias Ringwald                 break;
2628bd57ffebSMatthias Ringwald             case SM_SC_W2_CALCULATE_G2:
2629b35a3de2SMatthias Ringwald                 if (!sm_cmac_ready()) break;
2630bd57ffebSMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_G2;
2631b35a3de2SMatthias Ringwald                 g2_calculate(connection);
2632bd57ffebSMatthias Ringwald                 break;
2633e0a03c85SMatthias Ringwald #endif
2634e0a03c85SMatthias Ringwald 
263542134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
26363deb3ec6SMatthias Ringwald             // initiator side
2637f32b7a88SMatthias Ringwald 
26385567aa60SMatthias Ringwald             case SM_INITIATOR_PH4_HAS_LTK: {
2639f32b7a88SMatthias Ringwald 				sm_reset_setup();
2640f32b7a88SMatthias Ringwald 				sm_load_security_info(connection);
2641daac6563SMatthias Ringwald                 sm_reencryption_started(connection);
2642f32b7a88SMatthias Ringwald 
26433deb3ec6SMatthias Ringwald                 sm_key_t peer_ltk_flipped;
26449c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_peer_ltk, peer_ltk_flipped);
26455567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
26463deb3ec6SMatthias Ringwald                 log_info("sm: hci_le_start_encryption ediv 0x%04x", setup->sm_peer_ediv);
2647c9b8fdd9SMatthias Ringwald                 uint32_t rand_high = big_endian_read_32(setup->sm_peer_rand, 0);
2648c9b8fdd9SMatthias Ringwald                 uint32_t rand_low  = big_endian_read_32(setup->sm_peer_rand, 4);
26493deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle,rand_low, rand_high, setup->sm_peer_ediv, peer_ltk_flipped);
26503deb3ec6SMatthias Ringwald                 return;
26513deb3ec6SMatthias Ringwald             }
26523deb3ec6SMatthias Ringwald 
2653b26f445fSMatthias Ringwald 			case SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST:
2654b26f445fSMatthias Ringwald 				sm_reset_setup();
2655b26f445fSMatthias Ringwald 				sm_init_setup(connection);
2656b26f445fSMatthias Ringwald 				sm_timeout_start(connection);
2657d3c12277SMatthias Ringwald 				sm_pairing_started(connection);
2658b26f445fSMatthias Ringwald 
26591ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
26603deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_INITIATOR_PH1_W4_PAIRING_RESPONSE;
2661687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
26623deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
26633deb3ec6SMatthias Ringwald                 break;
266442134bc6SMatthias Ringwald #endif
26653deb3ec6SMatthias Ringwald 
266627c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
266741d32297SMatthias Ringwald 
2668c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PUBLIC_KEY_COMMAND: {
26691979f09cSMatthias Ringwald                 bool trigger_user_response   = false;
26701979f09cSMatthias Ringwald                 bool trigger_start_calculating_local_confirm = false;
267127c32905SMatthias Ringwald                 uint8_t buffer[65];
267227c32905SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_PUBLIC_KEY;
267327c32905SMatthias Ringwald                 //
2674fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[0],  &buffer[1]);
2675fc5bff5fSMatthias Ringwald                 reverse_256(&ec_q[32], &buffer[33]);
2676e53be891SMatthias Ringwald 
2677349d0adbSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2678349d0adbSMatthias Ringwald                 if (test_pairing_failure == SM_REASON_DHKEY_CHECK_FAILED){
2679349d0adbSMatthias Ringwald                     log_info("testing_support: invalidating public key");
2680349d0adbSMatthias Ringwald                     // flip single bit of public key coordinate
2681349d0adbSMatthias Ringwald                     buffer[1] ^= 1;
2682349d0adbSMatthias Ringwald                 }
2683349d0adbSMatthias Ringwald #endif
2684349d0adbSMatthias Ringwald 
268545a61d50SMatthias Ringwald                 // stk generation method
268645a61d50SMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
268745a61d50SMatthias Ringwald                 switch (setup->sm_stk_generation_method){
268845a61d50SMatthias Ringwald                     case JUST_WORKS:
268947fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
269042134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
269107036a04SMatthias Ringwald                             // responder
26921979f09cSMatthias Ringwald                             trigger_start_calculating_local_confirm = true;
2693b90c4e75SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_LOCAL_NONCE;
269427c32905SMatthias Ringwald                         } else {
269507036a04SMatthias Ringwald                             // initiator
2696c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
269727c32905SMatthias Ringwald                         }
269845a61d50SMatthias Ringwald                         break;
269945a61d50SMatthias Ringwald                     case PK_INIT_INPUT:
270045a61d50SMatthias Ringwald                     case PK_RESP_INPUT:
270147fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
270207036a04SMatthias Ringwald                         // use random TK for display
27036535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
27046535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
270545a61d50SMatthias Ringwald                         setup->sm_passkey_bit = 0;
270607036a04SMatthias Ringwald 
270742134bc6SMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
270845a61d50SMatthias Ringwald                             // responder
2709c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
271045a61d50SMatthias Ringwald                         } else {
271145a61d50SMatthias Ringwald                             // initiator
2712c6b7cbd9SMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
271345a61d50SMatthias Ringwald                         }
27141979f09cSMatthias Ringwald                         trigger_user_response = true;
271545a61d50SMatthias Ringwald                         break;
271645a61d50SMatthias Ringwald                     case OOB:
271765a9a04eSMatthias Ringwald                         if (IS_RESPONDER(connection->sm_role)){
271865a9a04eSMatthias Ringwald                             // responder
271965a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
272065a9a04eSMatthias Ringwald                         } else {
272165a9a04eSMatthias Ringwald                             // initiator
272265a9a04eSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
272365a9a04eSMatthias Ringwald                         }
272445a61d50SMatthias Ringwald                         break;
27257bbeb3adSMilanka Ringwald                     default:
27267bbeb3adSMilanka Ringwald                         btstack_assert(false);
27277bbeb3adSMilanka Ringwald                         break;
272845a61d50SMatthias Ringwald                 }
272945a61d50SMatthias Ringwald 
2730687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
273127c32905SMatthias Ringwald                 sm_timeout_reset(connection);
2732644c6a1dSMatthias Ringwald 
2733b90c4e75SMatthias Ringwald                 // trigger user response and calc confirm after sending pdu
2734644c6a1dSMatthias Ringwald                 if (trigger_user_response){
2735644c6a1dSMatthias Ringwald                     sm_trigger_user_response(connection);
2736644c6a1dSMatthias Ringwald                 }
2737b90c4e75SMatthias Ringwald                 if (trigger_start_calculating_local_confirm){
2738b90c4e75SMatthias Ringwald                     sm_sc_start_calculating_local_confirm(connection);
2739b90c4e75SMatthias Ringwald                 }
274027c32905SMatthias Ringwald                 break;
274127c32905SMatthias Ringwald             }
2742c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_CONFIRMATION: {
2743e53be891SMatthias Ringwald                 uint8_t buffer[17];
2744e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
27459af0f475SMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
274642134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2747c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2748e53be891SMatthias Ringwald                 } else {
2749c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
2750e53be891SMatthias Ringwald                 }
2751687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2752e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2753e53be891SMatthias Ringwald                 break;
2754e53be891SMatthias Ringwald             }
2755c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_PAIRING_RANDOM: {
2756e53be891SMatthias Ringwald                 uint8_t buffer[17];
2757e53be891SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
2758e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_nonce, &buffer[1]);
27599d0de1e9SMatthias Ringwald                 log_info("stk method %u, bit num: %u", setup->sm_stk_generation_method, setup->sm_passkey_bit);
27604ea43905SMatthias Ringwald                 if (sm_passkey_entry(setup->sm_stk_generation_method) && (setup->sm_passkey_bit < 20u)){
276140c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM A");
276242134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
276345a61d50SMatthias Ringwald                         // responder
2764c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_CONFIRMATION;
276545a61d50SMatthias Ringwald                     } else {
276645a61d50SMatthias Ringwald                         // initiator
2767c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
276845a61d50SMatthias Ringwald                     }
276945a61d50SMatthias Ringwald                 } else {
277040c5d850SMatthias Ringwald                     log_info("SM_SC_SEND_PAIRING_RANDOM B");
277142134bc6SMatthias Ringwald                     if (IS_RESPONDER(connection->sm_role)){
2772e53be891SMatthias Ringwald                         // responder
277347fb4255SMatthias Ringwald                         if (setup->sm_stk_generation_method == NUMERIC_COMPARISON){
277440c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B1");
2775901c000fSMatthias Ringwald                             connection->sm_engine_state = SM_SC_W2_CALCULATE_G2;
27762886623dSMatthias Ringwald                         } else {
277740c5d850SMatthias Ringwald                             log_info("SM_SC_SEND_PAIRING_RANDOM B2");
27782886623dSMatthias Ringwald                             sm_sc_prepare_dhkey_check(connection);
2779446a8c36SMatthias Ringwald                         }
2780e53be891SMatthias Ringwald                     } else {
2781136d331aSMatthias Ringwald                         // initiator
2782c6b7cbd9SMatthias Ringwald                         connection->sm_engine_state = SM_SC_W4_PAIRING_RANDOM;
2783e53be891SMatthias Ringwald                     }
278445a61d50SMatthias Ringwald                 }
2785687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2786e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2787e53be891SMatthias Ringwald                 break;
2788e53be891SMatthias Ringwald             }
2789c6b7cbd9SMatthias Ringwald             case SM_SC_SEND_DHKEY_CHECK_COMMAND: {
2790e083ca23SMatthias Ringwald                 uint8_t buffer[17];
2791e083ca23SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_DHKEY_CHECK;
2792e53be891SMatthias Ringwald                 reverse_128(setup->sm_local_dhkey_check, &buffer[1]);
2793dc300847SMatthias Ringwald 
279442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2795c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_LTK_REQUEST_SC;
2796e53be891SMatthias Ringwald                 } else {
2797c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_DHKEY_CHECK_COMMAND;
2798e53be891SMatthias Ringwald                 }
2799e083ca23SMatthias Ringwald 
2800687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
2801e53be891SMatthias Ringwald                 sm_timeout_reset(connection);
2802e53be891SMatthias Ringwald                 break;
2803e53be891SMatthias Ringwald             }
2804e53be891SMatthias Ringwald 
2805e53be891SMatthias Ringwald #endif
280642134bc6SMatthias Ringwald 
280742134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
2808dd12a62bSMatthias Ringwald 
280987014f74SMatthias Ringwald 			case SM_RESPONDER_SEND_SECURITY_REQUEST: {
281087014f74SMatthias Ringwald 				const uint8_t buffer[2] = {SM_CODE_SECURITY_REQUEST, sm_auth_req};
281187014f74SMatthias Ringwald 				connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_REQUEST;
2812687a03c8SMatthias Ringwald 				sm_send_connectionless(connection,  (uint8_t *) buffer, sizeof(buffer));
2813c8d0ff33SMatthias Ringwald 				sm_timeout_start(connection);
281487014f74SMatthias Ringwald 				break;
281587014f74SMatthias Ringwald 			}
281687014f74SMatthias Ringwald 
281738196718SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
281838196718SMatthias Ringwald 			case SM_SC_RECEIVED_LTK_REQUEST:
281938196718SMatthias Ringwald 				switch (connection->sm_irk_lookup_state){
282038196718SMatthias Ringwald 					case IRK_LOOKUP_SUCCEEDED:
282138196718SMatthias Ringwald 						// assuming Secure Connection, we have a stored LTK and the EDIV/RAND are null
282238196718SMatthias Ringwald 						// start using context by loading security info
282338196718SMatthias Ringwald 						sm_reset_setup();
282438196718SMatthias Ringwald 						sm_load_security_info(connection);
282538196718SMatthias Ringwald 						if ((setup->sm_peer_ediv == 0u) && sm_is_null_random(setup->sm_peer_rand) && !sm_is_null_key(setup->sm_peer_ltk)){
282638196718SMatthias Ringwald 							(void)memcpy(setup->sm_ltk, setup->sm_peer_ltk, 16);
282738196718SMatthias Ringwald 							connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
282842646f38SMatthias Ringwald                             sm_reencryption_started(connection);
282938196718SMatthias Ringwald                             sm_trigger_run();
283038196718SMatthias Ringwald 							break;
283138196718SMatthias Ringwald 						}
283238196718SMatthias Ringwald 						log_info("LTK Request: ediv & random are empty, but no stored LTK (IRK Lookup Succeeded)");
283338196718SMatthias Ringwald 						connection->sm_engine_state = SM_RESPONDER_IDLE;
283438196718SMatthias Ringwald 						hci_send_cmd(&hci_le_long_term_key_negative_reply, connection->sm_handle);
283538196718SMatthias Ringwald 						return;
283638196718SMatthias Ringwald 					default:
283738196718SMatthias Ringwald 						// just wait until IRK lookup is completed
283838196718SMatthias Ringwald 						break;
283938196718SMatthias Ringwald 				}
284038196718SMatthias Ringwald 				break;
284138196718SMatthias Ringwald #endif /* ENABLE_LE_SECURE_CONNECTIONS */
284238196718SMatthias Ringwald 
2843b6afa23eSMatthias Ringwald 			case SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED:
2844b6afa23eSMatthias Ringwald                 sm_reset_setup();
28459b75de03SMatthias Ringwald 
28469b75de03SMatthias Ringwald 			    // handle Pairing Request with LTK available
28479b75de03SMatthias Ringwald                 switch (connection->sm_irk_lookup_state) {
28489b75de03SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
28499b75de03SMatthias Ringwald                         le_device_db_encryption_get(connection->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
28509b75de03SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
28519b75de03SMatthias Ringwald                         if (have_ltk){
28529b75de03SMatthias Ringwald                             log_info("pairing request but LTK available");
285319a40772SMatthias Ringwald                             // emit re-encryption start/fail sequence
28549b75de03SMatthias Ringwald                             sm_reencryption_started(connection);
28559b75de03SMatthias Ringwald                             sm_reencryption_complete(connection, ERROR_CODE_PIN_OR_KEY_MISSING);
28569b75de03SMatthias Ringwald                         }
28579b75de03SMatthias Ringwald                         break;
28589b75de03SMatthias Ringwald                     default:
28599b75de03SMatthias Ringwald                         break;
28609b75de03SMatthias Ringwald                 }
28619b75de03SMatthias Ringwald 
2862b6afa23eSMatthias Ringwald 				sm_init_setup(connection);
2863d3c12277SMatthias Ringwald                 sm_pairing_started(connection);
286439543d07SMatthias Ringwald 
2865b6afa23eSMatthias Ringwald 				// recover pairing request
2866b6afa23eSMatthias Ringwald 				(void)memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
2867b6afa23eSMatthias Ringwald 				err = sm_stk_generation_init(connection);
2868b6afa23eSMatthias Ringwald 
2869b6afa23eSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
2870b6afa23eSMatthias Ringwald 				if ((0 < test_pairing_failure) && (test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED)){
2871b6afa23eSMatthias Ringwald                         log_info("testing_support: respond with pairing failure %u", test_pairing_failure);
2872b6afa23eSMatthias Ringwald                         err = test_pairing_failure;
2873b6afa23eSMatthias Ringwald                     }
2874b6afa23eSMatthias Ringwald #endif
28759305033eSMatthias Ringwald 				if (err != 0){
2876f4935286SMatthias Ringwald                     sm_pairing_error(connection, err);
2877b6afa23eSMatthias Ringwald 					sm_trigger_run();
2878b6afa23eSMatthias Ringwald 					break;
2879b6afa23eSMatthias Ringwald 				}
2880b6afa23eSMatthias Ringwald 
2881b6afa23eSMatthias Ringwald 				sm_timeout_start(connection);
2882b6afa23eSMatthias Ringwald 
2883b6afa23eSMatthias Ringwald 				// generate random number first, if we need to show passkey, otherwise send response
2884b6afa23eSMatthias Ringwald 				if (setup->sm_stk_generation_method == PK_INIT_INPUT){
2885b6afa23eSMatthias 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);
2886b6afa23eSMatthias Ringwald 					break;
2887b6afa23eSMatthias Ringwald 				}
2888b6afa23eSMatthias Ringwald 
2889b6afa23eSMatthias Ringwald 				/* fall through */
2890b6afa23eSMatthias Ringwald 
28913deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE:
28921ad129beSMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres,SM_CODE_PAIRING_RESPONSE);
2893f55bd529SMatthias Ringwald 
2894f55bd529SMatthias Ringwald                 // start with initiator key dist flags
28953deb3ec6SMatthias Ringwald                 key_distribution_flags = sm_key_distribution_flags_for_auth_req();
28961ad129beSMatthias Ringwald 
2897f55bd529SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
2898f55bd529SMatthias Ringwald                 // LTK (= encyrption information & master identification) only exchanged for LE Legacy Connection
2899f55bd529SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2900f55bd529SMatthias Ringwald                     key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
2901f55bd529SMatthias Ringwald                 }
2902f55bd529SMatthias Ringwald #endif
2903f55bd529SMatthias Ringwald                 // setup in response
2904f55bd529SMatthias 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);
2905f55bd529SMatthias 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);
2906f55bd529SMatthias Ringwald 
2907f55bd529SMatthias Ringwald                 // update key distribution after ENC was dropped
29089a90d41aSMatthias 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));
2909f55bd529SMatthias Ringwald 
291027c32905SMatthias Ringwald                 if (setup->sm_use_secure_connections){
2911c6b7cbd9SMatthias Ringwald                     connection->sm_engine_state = SM_SC_W4_PUBLIC_KEY_COMMAND;
29120b8af2a5SMatthias Ringwald                 } else {
29130b8af2a5SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH1_W4_PAIRING_CONFIRM;
291427c32905SMatthias Ringwald                 }
29150b8af2a5SMatthias Ringwald 
2916687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
29173deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
2918446a8c36SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
2919c1ab6cc1SMatthias Ringwald                 if (!setup->sm_use_secure_connections || (setup->sm_stk_generation_method == JUST_WORKS)){
29203deb3ec6SMatthias Ringwald                     sm_trigger_user_response(connection);
2921446a8c36SMatthias Ringwald                 }
29223deb3ec6SMatthias Ringwald                 return;
292342134bc6SMatthias Ringwald #endif
29243deb3ec6SMatthias Ringwald 
29253deb3ec6SMatthias Ringwald             case SM_PH2_SEND_PAIRING_RANDOM: {
29263deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29273deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_RANDOM;
29289c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_random, &buffer[1]);
292942134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29303deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_LTK_REQUEST;
29313deb3ec6SMatthias Ringwald                 } else {
29323deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_RANDOM;
29333deb3ec6SMatthias Ringwald                 }
2934687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
29353deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
29363deb3ec6SMatthias Ringwald                 break;
29373deb3ec6SMatthias Ringwald             }
29383deb3ec6SMatthias Ringwald 
2939d1a1f6a4SMatthias Ringwald             case SM_PH2_C1_GET_ENC_A:
29403deb3ec6SMatthias Ringwald                 // already busy?
29413deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
2942d1a1f6a4SMatthias Ringwald                 // calculate confirm using aes128 engine - step 1
2943d1a1f6a4SMatthias 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);
2944d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_A;
2945d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2946f3582630SMatthias 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);
29473deb3ec6SMatthias Ringwald                 break;
29483deb3ec6SMatthias Ringwald 
29493deb3ec6SMatthias Ringwald             case SM_PH2_C1_GET_ENC_C:
29503deb3ec6SMatthias Ringwald                 // already busy?
29513deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29523deb3ec6SMatthias Ringwald                 // calculate m_confirm using aes128 engine - step 1
2953d1a1f6a4SMatthias 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);
2954d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_C1_W4_ENC_C;
2955d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2956f3582630SMatthias 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);
29573deb3ec6SMatthias Ringwald                 break;
2958d1a1f6a4SMatthias Ringwald 
29593deb3ec6SMatthias Ringwald             case SM_PH2_CALC_STK:
29603deb3ec6SMatthias Ringwald                 // already busy?
29613deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29623deb3ec6SMatthias Ringwald                 // calculate STK
296342134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
2964d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_local_random, setup->sm_peer_random, sm_aes128_plaintext);
29653deb3ec6SMatthias Ringwald                 } else {
2966d1a1f6a4SMatthias Ringwald                     sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
29673deb3ec6SMatthias Ringwald                 }
2968d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_STK;
2969d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2970f3582630SMatthias 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);
29713deb3ec6SMatthias Ringwald                 break;
2972d1a1f6a4SMatthias Ringwald 
29733deb3ec6SMatthias Ringwald             case SM_PH3_Y_GET_ENC:
29743deb3ec6SMatthias Ringwald                 // already busy?
29753deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
29763deb3ec6SMatthias Ringwald                 // PH3B2 - calculate Y from      - enc
29779ad0dd7cSMatthias Ringwald 
29789ad0dd7cSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
29799ad0dd7cSMatthias Ringwald                 // r' = padding || r
29809ad0dd7cSMatthias Ringwald                 // r - 64 bit value
29819ad0dd7cSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
29826535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
29839ad0dd7cSMatthias Ringwald 
29843deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
2985d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_Y_W4_ENC;
2986d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
2987f3582630SMatthias 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);
2988d1a1f6a4SMatthias Ringwald                 break;
2989d1a1f6a4SMatthias Ringwald 
29903deb3ec6SMatthias Ringwald             case SM_PH2_C1_SEND_PAIRING_CONFIRM: {
29913deb3ec6SMatthias Ringwald                 uint8_t buffer[17];
29923deb3ec6SMatthias Ringwald                 buffer[0] = SM_CODE_PAIRING_CONFIRM;
29939c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_local_confirm, &buffer[1]);
299442134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
29953deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_RESPONDER_PH2_W4_PAIRING_RANDOM;
29963deb3ec6SMatthias Ringwald                 } else {
29973deb3ec6SMatthias Ringwald                     connection->sm_engine_state = SM_INITIATOR_PH2_W4_PAIRING_CONFIRM;
29983deb3ec6SMatthias Ringwald                 }
2999687a03c8SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t*) buffer, sizeof(buffer));
30003deb3ec6SMatthias Ringwald                 sm_timeout_reset(connection);
30013deb3ec6SMatthias Ringwald                 return;
30023deb3ec6SMatthias Ringwald             }
300342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
30043deb3ec6SMatthias Ringwald             case SM_RESPONDER_PH2_SEND_LTK_REPLY: {
30053deb3ec6SMatthias Ringwald                 sm_key_t stk_flipped;
30069c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
30073deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
30083deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, stk_flipped);
30093deb3ec6SMatthias Ringwald                 return;
30103deb3ec6SMatthias Ringwald             }
3011d7471931SMatthias Ringwald             case SM_RESPONDER_PH4_SEND_LTK_REPLY: {
30123deb3ec6SMatthias Ringwald                 sm_key_t ltk_flipped;
30139c80e4ccSMatthias Ringwald                 reverse_128(setup->sm_ltk, ltk_flipped);
30145567aa60SMatthias Ringwald                 connection->sm_engine_state = SM_PH4_W4_CONNECTION_ENCRYPTED;
30153deb3ec6SMatthias Ringwald                 hci_send_cmd(&hci_le_long_term_key_request_reply, connection->sm_handle, ltk_flipped);
30163deb3ec6SMatthias Ringwald                 return;
30173deb3ec6SMatthias Ringwald             }
3018dd12a62bSMatthias Ringwald 
3019dd12a62bSMatthias Ringwald 			case SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST:
30203deb3ec6SMatthias Ringwald                 // already busy?
30213deb3ec6SMatthias Ringwald                 if (sm_aes128_state == SM_AES128_ACTIVE) break;
30223deb3ec6SMatthias Ringwald                 log_info("LTK Request: recalculating with ediv 0x%04x", setup->sm_local_ediv);
3023c61cfe5aSMatthias Ringwald 
3024dd12a62bSMatthias Ringwald 				sm_reset_setup();
3025dd12a62bSMatthias Ringwald 				sm_start_calculating_ltk_from_ediv_and_rand(connection);
3026dd12a62bSMatthias Ringwald 
302742646f38SMatthias Ringwald 				sm_reencryption_started(connection);
302842646f38SMatthias Ringwald 
3029c61cfe5aSMatthias Ringwald                 // dm helper (was sm_dm_r_prime)
3030c61cfe5aSMatthias Ringwald                 // r' = padding || r
3031c61cfe5aSMatthias Ringwald                 // r - 64 bit value
3032c61cfe5aSMatthias Ringwald                 memset(&sm_aes128_plaintext[0], 0, 8);
30336535961aSMatthias Ringwald                 (void)memcpy(&sm_aes128_plaintext[8], setup->sm_local_rand, 8);
3034c61cfe5aSMatthias Ringwald 
30353deb3ec6SMatthias Ringwald                 // Y = dm(DHK, Rand)
3036d1a1f6a4SMatthias Ringwald                 connection->sm_engine_state = SM_RESPONDER_PH4_Y_W4_ENC;
3037d1a1f6a4SMatthias Ringwald                 sm_aes128_state = SM_AES128_ACTIVE;
3038f3582630SMatthias 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);
30393deb3ec6SMatthias Ringwald                 return;
304042134bc6SMatthias Ringwald #endif
304142134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
304242134bc6SMatthias Ringwald             case SM_INITIATOR_PH3_SEND_START_ENCRYPTION: {
304342134bc6SMatthias Ringwald                 sm_key_t stk_flipped;
304442134bc6SMatthias Ringwald                 reverse_128(setup->sm_ltk, stk_flipped);
304542134bc6SMatthias Ringwald                 connection->sm_engine_state = SM_PH2_W4_CONNECTION_ENCRYPTED;
304642134bc6SMatthias Ringwald                 hci_send_cmd(&hci_le_start_encryption, connection->sm_handle, 0, 0, 0, stk_flipped);
304742134bc6SMatthias Ringwald                 return;
304842134bc6SMatthias Ringwald             }
304942134bc6SMatthias Ringwald #endif
30503deb3ec6SMatthias Ringwald 
30513deb3ec6SMatthias Ringwald             case SM_PH3_DISTRIBUTE_KEYS:
3052403280b9SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0){
3053403280b9SMatthias Ringwald                     sm_run_distribute_keys(connection);
30543deb3ec6SMatthias Ringwald                     return;
30553deb3ec6SMatthias Ringwald                 }
30563deb3ec6SMatthias Ringwald 
30573deb3ec6SMatthias Ringwald                 // keys are sent
305842134bc6SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)){
30593deb3ec6SMatthias Ringwald                     // slave -> receive master keys if any
306061d1a45eSMatthias Ringwald                     if (sm_key_distribution_all_received()){
30613deb3ec6SMatthias Ringwald                         sm_key_distribution_handle_all_received(connection);
3062f5020412SMatthias Ringwald                         sm_key_distribution_complete_responder(connection);
3063f5020412SMatthias Ringwald                         // start CTKD right away
3064f5020412SMatthias Ringwald                         continue;
30653deb3ec6SMatthias Ringwald                     } else {
30663deb3ec6SMatthias Ringwald                         connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
30673deb3ec6SMatthias Ringwald                     }
30683deb3ec6SMatthias Ringwald                 } else {
30691dca9d8aSMatthias Ringwald                     sm_master_pairing_success(connection);
30703deb3ec6SMatthias Ringwald                 }
30713deb3ec6SMatthias Ringwald                 break;
30723deb3ec6SMatthias Ringwald 
3073c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3074c18be159SMatthias Ringwald             case SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST:
3075c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3076c18be159SMatthias Ringwald                 sm_reset_setup();
3077c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3078c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3079c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3080c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3081c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3082c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3083c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3084c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3085c18be159SMatthias Ringwald 
3086c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3087c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3088c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3089c18be159SMatthias Ringwald                 // Plus signing key if supported
3090c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3091c18be159SMatthias Ringwald #endif
3092c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_m_preq, SM_CODE_PAIRING_REQUEST);
3093c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_m_preq, 0);
3094c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_m_preq, 0);
3095c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_m_preq, SM_AUTHREQ_CT2);
3096c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_m_preq, sm_max_encryption_key_size);
3097c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_m_preq, key_distribution_flags);
3098c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_m_preq, key_distribution_flags);
3099c18be159SMatthias Ringwald 
3100c18be159SMatthias Ringwald                 // set state and send pairing response
3101c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3102c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE;
3103c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_m_preq, sizeof(sm_pairing_packet_t));
3104c18be159SMatthias Ringwald                 break;
3105c18be159SMatthias Ringwald 
3106c18be159SMatthias Ringwald             case SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED:
3107c18be159SMatthias Ringwald                 // fill in sm setup (lite version of sm_init_setup)
3108c18be159SMatthias Ringwald                 sm_reset_setup();
3109c18be159SMatthias Ringwald                 setup->sm_peer_addr_type = connection->sm_peer_addr_type;
3110c18be159SMatthias Ringwald                 setup->sm_m_addr_type = connection->sm_peer_addr_type;
3111c18be159SMatthias Ringwald                 setup->sm_s_addr_type = connection->sm_own_addr_type;
3112c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_peer_address, connection->sm_peer_address, 6);
3113c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_m_address, connection->sm_peer_address, 6);
3114c18be159SMatthias Ringwald                 (void) memcpy(setup->sm_s_address, connection->sm_own_address, 6);
3115c18be159SMatthias Ringwald                 setup->sm_use_secure_connections = true;
3116c18be159SMatthias Ringwald                 sm_ctkd_fetch_br_edr_link_key(connection);
3117c18be159SMatthias Ringwald                 (void) memcpy(&setup->sm_m_preq, &connection->sm_m_preq, sizeof(sm_pairing_packet_t));
3118c18be159SMatthias Ringwald 
3119c18be159SMatthias Ringwald                 // Enc Key and IRK if requested
3120c18be159SMatthias Ringwald                 key_distribution_flags = SM_KEYDIST_ID_KEY | SM_KEYDIST_ENC_KEY;
3121c18be159SMatthias Ringwald #ifdef ENABLE_LE_SIGNED_WRITE
3122c18be159SMatthias Ringwald                 // Plus signing key if supported
3123c18be159SMatthias Ringwald                 key_distribution_flags |= SM_KEYDIST_ID_KEY;
3124c18be159SMatthias Ringwald #endif
3125c18be159SMatthias Ringwald                 // drop flags not requested by initiator
3126c18be159SMatthias Ringwald                 key_distribution_flags &= sm_pairing_packet_get_initiator_key_distribution(connection->sm_m_preq);
3127c18be159SMatthias Ringwald 
3128c18be159SMatthias 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:
3129c18be159SMatthias Ringwald                 // - the IO Capability field,
3130c18be159SMatthias Ringwald                 // - the OOB data flag field, and
3131c18be159SMatthias Ringwald                 // - all bits in the Auth Req field except the CT2 bit.
3132c18be159SMatthias Ringwald                 sm_pairing_packet_set_code(setup->sm_s_pres, SM_CODE_PAIRING_RESPONSE);
3133c18be159SMatthias Ringwald                 sm_pairing_packet_set_io_capability(setup->sm_s_pres, 0);
3134c18be159SMatthias Ringwald                 sm_pairing_packet_set_oob_data_flag(setup->sm_s_pres, 0);
3135c18be159SMatthias Ringwald                 sm_pairing_packet_set_auth_req(setup->sm_s_pres, SM_AUTHREQ_CT2);
3136c18be159SMatthias Ringwald                 sm_pairing_packet_set_max_encryption_key_size(setup->sm_s_pres, connection->sm_actual_encryption_key_size);
3137c18be159SMatthias Ringwald                 sm_pairing_packet_set_initiator_key_distribution(setup->sm_s_pres, key_distribution_flags);
3138c18be159SMatthias Ringwald                 sm_pairing_packet_set_responder_key_distribution(setup->sm_s_pres, key_distribution_flags);
3139c18be159SMatthias Ringwald 
3140c18be159SMatthias Ringwald                 // configure key distribution, LTK is derived locally
3141c18be159SMatthias Ringwald                 key_distribution_flags &= ~SM_KEYDIST_ENC_KEY;
3142c18be159SMatthias Ringwald                 sm_setup_key_distribution(key_distribution_flags, key_distribution_flags);
3143c18be159SMatthias Ringwald 
3144c18be159SMatthias Ringwald                 // set state and send pairing response
3145c18be159SMatthias Ringwald                 sm_timeout_start(connection);
3146c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
3147c18be159SMatthias Ringwald                 sm_send_connectionless(connection, (uint8_t *) &setup->sm_s_pres, sizeof(sm_pairing_packet_t));
3148c18be159SMatthias Ringwald                 break;
3149c18be159SMatthias Ringwald             case SM_BR_EDR_DISTRIBUTE_KEYS:
3150c18be159SMatthias Ringwald                 if (setup->sm_key_distribution_send_set != 0) {
3151c18be159SMatthias Ringwald                     sm_run_distribute_keys(connection);
3152c18be159SMatthias Ringwald                     return;
3153c18be159SMatthias Ringwald                 }
3154c18be159SMatthias Ringwald                 // keys are sent
3155c18be159SMatthias Ringwald                 if (IS_RESPONDER(connection->sm_role)) {
3156c18be159SMatthias Ringwald                     // responder -> receive master keys if there are any
315761d1a45eSMatthias Ringwald                     if (!sm_key_distribution_all_received()){
3158c18be159SMatthias Ringwald                         connection->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
3159c18be159SMatthias Ringwald                         break;
3160c18be159SMatthias Ringwald                     }
3161c18be159SMatthias Ringwald                 }
3162c18be159SMatthias Ringwald                 // otherwise start CTKD right away (responder and no keys to receive / initiator)
3163c18be159SMatthias Ringwald                 sm_ctkd_start_from_br_edr(connection);
3164c18be159SMatthias Ringwald                 continue;
3165c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H6:
3166c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3167c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3168c18be159SMatthias Ringwald                 h6_calculate_ilk_from_le_ltk(connection);
3169c18be159SMatthias Ringwald                 break;
3170c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_BR_EDR_LINK_KEY:
3171c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3172c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_BR_EDR_LINK_KEY;
3173c18be159SMatthias Ringwald                 h6_calculate_br_edr_link_key(connection);
3174c18be159SMatthias Ringwald                 break;
3175c18be159SMatthias Ringwald             case SM_SC_W2_CALCULATE_ILK_USING_H7:
3176c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3177c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_SC_W4_CALCULATE_ILK;
3178c18be159SMatthias Ringwald                 h7_calculate_ilk_from_le_ltk(connection);
3179c18be159SMatthias Ringwald                 break;
3180c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H6:
3181c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3182c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3183c18be159SMatthias Ringwald                 h6_calculate_ilk_from_br_edr(connection);
3184c18be159SMatthias Ringwald                 break;
3185c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_LE_LTK:
3186c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3187c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_LE_LTK;
3188c18be159SMatthias Ringwald                 h6_calculate_le_ltk(connection);
3189c18be159SMatthias Ringwald                 break;
3190c18be159SMatthias Ringwald             case SM_BR_EDR_W2_CALCULATE_ILK_USING_H7:
3191c18be159SMatthias Ringwald                 if (!sm_cmac_ready()) break;
3192c18be159SMatthias Ringwald                 connection->sm_engine_state = SM_BR_EDR_W4_CALCULATE_ILK;
3193c18be159SMatthias Ringwald                 h7_calculate_ilk_from_br_edr(connection);
3194c18be159SMatthias Ringwald                 break;
3195c18be159SMatthias Ringwald #endif
3196c18be159SMatthias Ringwald 
31973deb3ec6SMatthias Ringwald             default:
31983deb3ec6SMatthias Ringwald                 break;
31993deb3ec6SMatthias Ringwald         }
32003deb3ec6SMatthias Ringwald 
32013deb3ec6SMatthias Ringwald         // check again if active connection was released
32027149bde5SMatthias Ringwald         if (sm_active_connection_handle != HCI_CON_HANDLE_INVALID) break;
32033deb3ec6SMatthias Ringwald     }
32043deb3ec6SMatthias Ringwald }
32053deb3ec6SMatthias Ringwald 
3206d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3207d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_a(void *arg){
3208f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
320904678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
321004678764SMatthias Ringwald 
3211f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3212f3582630SMatthias Ringwald     if (connection == NULL) return;
3213f3582630SMatthias Ringwald 
3214d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
321504678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3216f3582630SMatthias 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);
3217d1a1f6a4SMatthias Ringwald }
32183deb3ec6SMatthias Ringwald 
3219d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_b(void *arg){
3220f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
322104678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
322204678764SMatthias Ringwald 
3223f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3224f3582630SMatthias Ringwald     if (connection == NULL) return;
3225f3582630SMatthias Ringwald 
32268314c363SMatthias Ringwald     log_info_key("c1!", setup->sm_local_confirm);
32273deb3ec6SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_SEND_PAIRING_CONFIRM;
322870b44dd4SMatthias Ringwald     sm_trigger_run();
3229d1a1f6a4SMatthias Ringwald }
3230d1a1f6a4SMatthias Ringwald 
3231d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3232d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_c(void *arg){
3233f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
323404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
323504678764SMatthias Ringwald 
3236f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3237f3582630SMatthias Ringwald     if (connection == NULL) return;
3238f3582630SMatthias Ringwald 
3239d1a1f6a4SMatthias Ringwald     sm_c1_t3(sm_aes128_ciphertext, setup->sm_m_address, setup->sm_s_address, setup->sm_c1_t3_value);
324004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3241f3582630SMatthias 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);
3242d1a1f6a4SMatthias Ringwald }
3243d1a1f6a4SMatthias Ringwald 
3244d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_d(void * arg){
3245f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
324604678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
324704678764SMatthias Ringwald 
3248f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3249f3582630SMatthias Ringwald     if (connection == NULL) return;
3250f3582630SMatthias Ringwald 
3251d1a1f6a4SMatthias Ringwald     log_info_key("c1!", sm_aes128_ciphertext);
3252d1a1f6a4SMatthias Ringwald     if (memcmp(setup->sm_peer_confirm, sm_aes128_ciphertext, 16) != 0){
3253f4935286SMatthias Ringwald         sm_pairing_error(connection, SM_REASON_CONFIRM_VALUE_FAILED);
325470b44dd4SMatthias Ringwald         sm_trigger_run();
32553deb3ec6SMatthias Ringwald         return;
32563deb3ec6SMatthias Ringwald     }
325742134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32583deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
325970b44dd4SMatthias Ringwald         sm_trigger_run();
32603deb3ec6SMatthias Ringwald     } else {
3261d1a1f6a4SMatthias Ringwald         sm_s1_r_prime(setup->sm_peer_random, setup->sm_local_random, sm_aes128_plaintext);
3262d1a1f6a4SMatthias Ringwald         sm_aes128_state = SM_AES128_ACTIVE;
3263f3582630SMatthias 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);
32643deb3ec6SMatthias Ringwald     }
32653deb3ec6SMatthias Ringwald }
3266d1a1f6a4SMatthias Ringwald 
3267d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_stk(void *arg){
326804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3269f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
327004678764SMatthias Ringwald 
3271f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3272f3582630SMatthias Ringwald     if (connection == NULL) return;
3273f3582630SMatthias Ringwald 
32743deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
32758314c363SMatthias Ringwald     log_info_key("stk", setup->sm_ltk);
327642134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
32773deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
32783deb3ec6SMatthias Ringwald     } else {
32793deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_INITIATOR_PH3_SEND_START_ENCRYPTION;
32803deb3ec6SMatthias Ringwald     }
328170b44dd4SMatthias Ringwald     sm_trigger_run();
3282d1a1f6a4SMatthias Ringwald }
3283d1a1f6a4SMatthias Ringwald 
3284d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3285d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_y(void *arg){
3286f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
328704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
328804678764SMatthias Ringwald 
3289f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3290f3582630SMatthias Ringwald     if (connection == NULL) return;
3291f3582630SMatthias Ringwald 
3292d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
32933deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
32943deb3ec6SMatthias Ringwald     // PH3B3 - calculate EDIV
32953deb3ec6SMatthias Ringwald     setup->sm_local_ediv = setup->sm_local_y ^ setup->sm_local_div;
32963deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
32973deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
32983deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3299d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
330004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3301f3582630SMatthias 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);
33023deb3ec6SMatthias Ringwald }
3303d1a1f6a4SMatthias Ringwald 
33042a526f21SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3305d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3306d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_y(void *arg){
330704678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
3308f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
330904678764SMatthias Ringwald 
3310f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3311f3582630SMatthias Ringwald     if (connection == NULL) return;
3312f3582630SMatthias Ringwald 
3313d1a1f6a4SMatthias Ringwald     setup->sm_local_y = big_endian_read_16(sm_aes128_ciphertext, 14);
33143deb3ec6SMatthias Ringwald     log_info_hex16("y", setup->sm_local_y);
33153deb3ec6SMatthias Ringwald 
33163deb3ec6SMatthias Ringwald     // PH3B3 - calculate DIV
33173deb3ec6SMatthias Ringwald     setup->sm_local_div = setup->sm_local_y ^ setup->sm_local_ediv;
33183deb3ec6SMatthias Ringwald     log_info_hex16("ediv", setup->sm_local_ediv);
33193deb3ec6SMatthias Ringwald     // PH3B4 - calculate LTK         - enc
33203deb3ec6SMatthias Ringwald     // LTK = d1(ER, DIV, 0))
3321d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 0, sm_aes128_plaintext);
332204678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3323f3582630SMatthias 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);
33243deb3ec6SMatthias Ringwald }
33252a526f21SMatthias Ringwald #endif
3326d1a1f6a4SMatthias Ringwald 
3327d1a1f6a4SMatthias Ringwald // sm_aes128_state stays active
3328d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph3_ltk(void *arg){
3329f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
333004678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
333104678764SMatthias Ringwald 
3332f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3333f3582630SMatthias Ringwald     if (connection == NULL) return;
3334f3582630SMatthias Ringwald 
33358314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
33363deb3ec6SMatthias Ringwald     // calc CSRK next
3337d1a1f6a4SMatthias Ringwald     sm_d1_d_prime(setup->sm_local_div, 1, sm_aes128_plaintext);
333804678764SMatthias Ringwald     sm_aes128_state = SM_AES128_ACTIVE;
3339f3582630SMatthias 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);
3340d1a1f6a4SMatthias Ringwald }
3341d1a1f6a4SMatthias Ringwald 
3342d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_csrk(void *arg){
3343f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
334404678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
334504678764SMatthias Ringwald 
3346f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3347f3582630SMatthias Ringwald     if (connection == NULL) return;
3348f3582630SMatthias Ringwald 
3349d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
33508314c363SMatthias Ringwald     log_info_key("csrk", setup->sm_local_csrk);
33513deb3ec6SMatthias Ringwald     if (setup->sm_key_distribution_send_set){
33523deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
33533deb3ec6SMatthias Ringwald     } else {
33543deb3ec6SMatthias Ringwald         // no keys to send, just continue
335542134bc6SMatthias Ringwald         if (IS_RESPONDER(connection->sm_role)){
335661d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
3357c5a72e35SMatthias Ringwald                 sm_key_distribution_handle_all_received(connection);
3358c5a72e35SMatthias Ringwald                 sm_key_distribution_complete_responder(connection);
3359c5a72e35SMatthias Ringwald             } else {
33603deb3ec6SMatthias Ringwald                 // slave -> receive master keys
33613deb3ec6SMatthias Ringwald                 connection->sm_engine_state = SM_PH3_RECEIVE_KEYS;
3362c5a72e35SMatthias Ringwald             }
33633deb3ec6SMatthias Ringwald         } else {
3364af7ef9d1SMatthias Ringwald             sm_key_distribution_complete_initiator(connection);
33653deb3ec6SMatthias Ringwald         }
33662bacf595SMatthias Ringwald     }
336770b44dd4SMatthias Ringwald     sm_trigger_run();
3368d1a1f6a4SMatthias Ringwald }
3369d1a1f6a4SMatthias Ringwald 
337042134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
3371d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_enc_ph4_ltk(void *arg){
3372f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
337304678764SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
337404678764SMatthias Ringwald 
3375f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3376f3582630SMatthias Ringwald     if (connection == NULL) return;
3377f3582630SMatthias Ringwald 
33783deb3ec6SMatthias Ringwald     sm_truncate_key(setup->sm_ltk, connection->sm_actual_encryption_key_size);
33798314c363SMatthias Ringwald     log_info_key("ltk", setup->sm_ltk);
3380d7471931SMatthias Ringwald     connection->sm_engine_state = SM_RESPONDER_PH4_SEND_LTK_REPLY;
338170b44dd4SMatthias Ringwald     sm_trigger_run();
3382d1a1f6a4SMatthias Ringwald }
3383d1a1f6a4SMatthias Ringwald #endif
3384d1a1f6a4SMatthias Ringwald 
3385d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_address_resolution(void *arg){
3386d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3387d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
338804678764SMatthias Ringwald 
3389d1a1f6a4SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
3390d1a1f6a4SMatthias Ringwald     // compare calulated address against connecting device
3391d1a1f6a4SMatthias Ringwald     uint8_t * hash = &sm_aes128_ciphertext[13];
3392d1a1f6a4SMatthias Ringwald     if (memcmp(&sm_address_resolution_address[3], hash, 3) == 0){
3393d1a1f6a4SMatthias Ringwald         log_info("LE Device Lookup: matched resolvable private address");
3394a66b030fSMatthias Ringwald         sm_address_resolution_handle_event(ADDRESS_RESOLUTION_SUCCEEDED);
339570b44dd4SMatthias Ringwald         sm_trigger_run();
33963deb3ec6SMatthias Ringwald         return;
33973deb3ec6SMatthias Ringwald     }
3398d1a1f6a4SMatthias Ringwald     // no match, try next
3399d1a1f6a4SMatthias Ringwald     sm_address_resolution_test++;
340070b44dd4SMatthias Ringwald     sm_trigger_run();
34013deb3ec6SMatthias Ringwald }
34023deb3ec6SMatthias Ringwald 
3403d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_irk(void *arg){
3404d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3405d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
340604678764SMatthias Ringwald 
3407d1a1f6a4SMatthias Ringwald     log_info_key("irk", sm_persistent_irk);
3408d1a1f6a4SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
340970b44dd4SMatthias Ringwald     sm_trigger_run();
34107df18c15SMatthias Ringwald }
3411d1a1f6a4SMatthias Ringwald 
3412d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_dkg_dhk(void *arg){
3413d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3414d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
341504678764SMatthias Ringwald 
3416d1a1f6a4SMatthias Ringwald     log_info_key("dhk", sm_persistent_dhk);
3417d1a1f6a4SMatthias Ringwald     dkg_state = DKG_READY;
341870b44dd4SMatthias Ringwald     sm_trigger_run();
34197df18c15SMatthias Ringwald }
3420d1a1f6a4SMatthias Ringwald 
3421d1a1f6a4SMatthias Ringwald static void sm_handle_encryption_result_rau(void *arg){
3422d1a1f6a4SMatthias Ringwald     UNUSED(arg);
3423d1a1f6a4SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
342404678764SMatthias Ringwald 
34256535961aSMatthias Ringwald     (void)memcpy(&sm_random_address[3], &sm_aes128_ciphertext[13], 3);
3426*e91ddb40SMatthias Ringwald     rau_state = RAU_IDLE;
3427*e91ddb40SMatthias Ringwald     hci_le_random_address_set(sm_random_address);
3428*e91ddb40SMatthias Ringwald 
342970b44dd4SMatthias Ringwald     sm_trigger_run();
343051fa0b28SMatthias Ringwald }
34317df18c15SMatthias Ringwald 
3432d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_rau(void * arg){
3433d1a1f6a4SMatthias Ringwald     UNUSED(arg);
34343deb3ec6SMatthias Ringwald     // non-resolvable vs. resolvable
34353deb3ec6SMatthias Ringwald     switch (gap_random_adress_type){
34363deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_RESOLVABLE:
34373deb3ec6SMatthias Ringwald             // resolvable: use random as prand and calc address hash
34383deb3ec6SMatthias Ringwald             // "The two most significant bits of prand shall be equal to ‘0’ and ‘1"
34394ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
34404ea43905SMatthias Ringwald             sm_random_address[0u] |= 0x40u;
34413deb3ec6SMatthias Ringwald             rau_state = RAU_GET_ENC;
34423deb3ec6SMatthias Ringwald             break;
34433deb3ec6SMatthias Ringwald         case GAP_RANDOM_ADDRESS_NON_RESOLVABLE:
34443deb3ec6SMatthias Ringwald         default:
34453deb3ec6SMatthias Ringwald             // "The two most significant bits of the address shall be equal to ‘0’""
34464ea43905SMatthias Ringwald             sm_random_address[0u] &= 0x3fu;
3447*e91ddb40SMatthias Ringwald             hci_le_random_address_set(sm_random_address);
34483deb3ec6SMatthias Ringwald             break;
34493deb3ec6SMatthias Ringwald     }
345070b44dd4SMatthias Ringwald     sm_trigger_run();
34513deb3ec6SMatthias Ringwald }
34523deb3ec6SMatthias Ringwald 
3453c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
34546ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_send_pairing_random(void * arg){
3455f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3456f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3457f3582630SMatthias Ringwald     if (connection == NULL) return;
3458c59d0c92SMatthias Ringwald 
345965a9a04eSMatthias Ringwald     connection->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
346070b44dd4SMatthias Ringwald     sm_trigger_run();
346165a9a04eSMatthias Ringwald }
3462d1a1f6a4SMatthias Ringwald 
34636ca80073SMatthias Ringwald static void sm_handle_random_result_sc_next_w2_cmac_for_confirmation(void * arg){
34646ca80073SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
34656ca80073SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
34666ca80073SMatthias Ringwald     if (connection == NULL) return;
34676ca80073SMatthias Ringwald 
3468b35a3de2SMatthias Ringwald     connection->sm_engine_state = SM_SC_W2_CMAC_FOR_CONFIRMATION;
346970b44dd4SMatthias Ringwald     sm_trigger_run();
3470d1a1f6a4SMatthias Ringwald }
3471f1c1783eSMatthias Ringwald #endif
3472f1c1783eSMatthias Ringwald 
3473d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_random(void * arg){
3474f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3475f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3476f3582630SMatthias Ringwald     if (connection == NULL) return;
3477f3582630SMatthias Ringwald 
3478d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH2_C1_GET_ENC_A;
347970b44dd4SMatthias Ringwald     sm_trigger_run();
3480d1a1f6a4SMatthias Ringwald }
3481d1a1f6a4SMatthias Ringwald 
3482d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph2_tk(void * arg){
3483f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3484f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3485f3582630SMatthias Ringwald     if (connection == NULL) return;
3486f3582630SMatthias Ringwald 
3487caf15bf3SMatthias Ringwald     sm_reset_tk();
3488caf15bf3SMatthias Ringwald     uint32_t tk;
34895ce1359eSMatthias Ringwald     if (sm_fixed_passkey_in_display_role == 0xffffffffU){
34903deb3ec6SMatthias Ringwald         // map random to 0-999999 without speding much cycles on a modulus operation
3491d1a1f6a4SMatthias Ringwald         tk = little_endian_read_32(sm_random_data,0);
34923deb3ec6SMatthias Ringwald         tk = tk & 0xfffff;  // 1048575
34934ea43905SMatthias Ringwald         if (tk >= 999999u){
34944ea43905SMatthias Ringwald             tk = tk - 999999u;
34953deb3ec6SMatthias Ringwald         }
3496caf15bf3SMatthias Ringwald     } else {
3497caf15bf3SMatthias Ringwald         // override with pre-defined passkey
34984b8c611fSMatthias Ringwald         tk = sm_fixed_passkey_in_display_role;
3499caf15bf3SMatthias Ringwald     }
3500f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, tk);
350142134bc6SMatthias Ringwald     if (IS_RESPONDER(connection->sm_role)){
35023deb3ec6SMatthias Ringwald         connection->sm_engine_state = SM_RESPONDER_PH1_SEND_PAIRING_RESPONSE;
35033deb3ec6SMatthias Ringwald     } else {
3504b41539d5SMatthias Ringwald         if (setup->sm_use_secure_connections){
3505b41539d5SMatthias Ringwald             connection->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
3506b41539d5SMatthias Ringwald         } else {
35073deb3ec6SMatthias Ringwald             connection->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
35083deb3ec6SMatthias Ringwald             sm_trigger_user_response(connection);
35093deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
35103deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
3511f3582630SMatthias 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);
35123deb3ec6SMatthias Ringwald             }
35133deb3ec6SMatthias Ringwald         }
3514b41539d5SMatthias Ringwald     }
351570b44dd4SMatthias Ringwald     sm_trigger_run();
35163deb3ec6SMatthias Ringwald }
3517d1a1f6a4SMatthias Ringwald 
3518d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_div(void * arg){
3519f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3520f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3521f3582630SMatthias Ringwald     if (connection == NULL) return;
3522f3582630SMatthias Ringwald 
3523d1a1f6a4SMatthias Ringwald     // use 16 bit from random value as div
3524d1a1f6a4SMatthias Ringwald     setup->sm_local_div = big_endian_read_16(sm_random_data, 0);
3525d1a1f6a4SMatthias Ringwald     log_info_hex16("div", setup->sm_local_div);
3526d1a1f6a4SMatthias Ringwald     connection->sm_engine_state = SM_PH3_Y_GET_ENC;
352770b44dd4SMatthias Ringwald     sm_trigger_run();
3528d1a1f6a4SMatthias Ringwald }
3529d1a1f6a4SMatthias Ringwald 
3530d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_ph3_random(void * arg){
3531f3582630SMatthias Ringwald     hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) arg;
3532f3582630SMatthias Ringwald     sm_connection_t * connection = sm_get_connection_for_handle(con_handle);
3533f3582630SMatthias Ringwald     if (connection == NULL) return;
3534f3582630SMatthias Ringwald 
3535d1a1f6a4SMatthias Ringwald     reverse_64(sm_random_data, setup->sm_local_rand);
35363deb3ec6SMatthias Ringwald     // no db for encryption size hack: encryption size is stored in lowest nibble of setup->sm_local_rand
35374ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xf0u) + (connection->sm_actual_encryption_key_size - 1u);
35383deb3ec6SMatthias Ringwald     // no db for authenticated flag hack: store flag in bit 4 of LSB
35394ea43905SMatthias Ringwald     setup->sm_local_rand[7u] = (setup->sm_local_rand[7u] & 0xefu) + (connection->sm_connection_authenticated << 4u);
35408b3ffec5SMatthias 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);
35413deb3ec6SMatthias Ringwald }
3542899e6e02SMatthias Ringwald static void sm_validate_er_ir(void){
3543899e6e02SMatthias Ringwald     // warn about default ER/IR
35441979f09cSMatthias Ringwald     bool warning = false;
3545899e6e02SMatthias Ringwald     if (sm_ir_is_default()){
35461979f09cSMatthias Ringwald         warning = true;
3547899e6e02SMatthias Ringwald         log_error("Persistent IR not set with sm_set_ir. Use of private addresses will cause pairing issues");
3548899e6e02SMatthias Ringwald     }
3549899e6e02SMatthias Ringwald     if (sm_er_is_default()){
35501979f09cSMatthias Ringwald         warning = true;
3551899e6e02SMatthias Ringwald         log_error("Persistent ER not set with sm_set_er. Legacy Pairing LTK is not secure");
3552899e6e02SMatthias Ringwald     }
355321045273SMatthias Ringwald     if (warning) {
3554899e6e02SMatthias Ringwald         log_error("Please configure btstack_tlv to let BTstack setup ER and IR keys");
3555899e6e02SMatthias Ringwald     }
355621045273SMatthias Ringwald }
3557899e6e02SMatthias Ringwald 
3558899e6e02SMatthias Ringwald static void sm_handle_random_result_ir(void *arg){
35591979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35609305033eSMatthias Ringwald     if (arg != NULL){
3561899e6e02SMatthias Ringwald         // key generated, store in tlv
35624ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3563899e6e02SMatthias Ringwald         log_info("Generated IR key. Store in TLV status: %d", status);
3564e0d13a19SMilanka Ringwald         UNUSED(status);
3565899e6e02SMatthias Ringwald     }
3566899e6e02SMatthias Ringwald     log_info_key("IR", sm_persistent_ir);
35678d9b6072SMatthias Ringwald     dkg_state = DKG_CALC_IRK;
3568841468bbSMatthias Ringwald 
3569841468bbSMatthias Ringwald     if (test_use_fixed_local_irk){
3570841468bbSMatthias Ringwald         log_info_key("IRK", sm_persistent_irk);
3571841468bbSMatthias Ringwald         dkg_state = DKG_CALC_DHK;
3572841468bbSMatthias Ringwald     }
3573841468bbSMatthias Ringwald 
357470b44dd4SMatthias Ringwald     sm_trigger_run();
3575899e6e02SMatthias Ringwald }
3576899e6e02SMatthias Ringwald 
3577899e6e02SMatthias Ringwald static void sm_handle_random_result_er(void *arg){
35781979f09cSMatthias Ringwald     sm_persistent_keys_random_active = false;
35799305033eSMatthias Ringwald     if (arg != 0){
3580899e6e02SMatthias Ringwald         // key generated, store in tlv
35814ea43905SMatthias Ringwald         int status = sm_tlv_impl->store_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3582899e6e02SMatthias Ringwald         log_info("Generated ER key. Store in TLV status: %d", status);
3583e0d13a19SMilanka Ringwald         UNUSED(status);
3584899e6e02SMatthias Ringwald     }
3585899e6e02SMatthias Ringwald     log_info_key("ER", sm_persistent_er);
3586899e6e02SMatthias Ringwald 
3587899e6e02SMatthias Ringwald     // try load ir
35884ea43905SMatthias Ringwald     int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','I','R'), sm_persistent_ir, 16u);
3589899e6e02SMatthias Ringwald     if (key_size == 16){
3590899e6e02SMatthias Ringwald         // ok, let's continue
3591899e6e02SMatthias Ringwald         log_info("IR from TLV");
3592899e6e02SMatthias Ringwald         sm_handle_random_result_ir( NULL );
3593899e6e02SMatthias Ringwald     } else {
3594899e6e02SMatthias Ringwald         // invalid, generate new random one
35951979f09cSMatthias Ringwald         sm_persistent_keys_random_active = true;
3596899e6e02SMatthias Ringwald         btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_ir, 16, &sm_handle_random_result_ir, &sm_persistent_ir);
3597899e6e02SMatthias Ringwald     }
3598899e6e02SMatthias Ringwald }
35993deb3ec6SMatthias Ringwald 
3600f664b5e8SMatthias 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){
3601f664b5e8SMatthias Ringwald 
3602f664b5e8SMatthias Ringwald     // connection info
3603f664b5e8SMatthias Ringwald     sm_conn->sm_handle = con_handle;
3604f664b5e8SMatthias Ringwald     sm_conn->sm_role = role;
3605f664b5e8SMatthias Ringwald     sm_conn->sm_peer_addr_type = addr_type;
3606f664b5e8SMatthias Ringwald     memcpy(sm_conn->sm_peer_address, address, 6);
3607f664b5e8SMatthias Ringwald 
3608f664b5e8SMatthias Ringwald     // security properties
3609f664b5e8SMatthias Ringwald     sm_conn->sm_connection_encrypted = 0;
3610f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authenticated = 0;
3611f664b5e8SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_UNKNOWN;
3612f664b5e8SMatthias Ringwald     sm_conn->sm_le_db_index = -1;
3613f664b5e8SMatthias Ringwald     sm_conn->sm_reencryption_active = false;
3614f664b5e8SMatthias Ringwald 
3615f664b5e8SMatthias Ringwald     // prepare CSRK lookup (does not involve setup)
3616f664b5e8SMatthias Ringwald     sm_conn->sm_irk_lookup_state = IRK_LOOKUP_W4_READY;
3617f664b5e8SMatthias Ringwald 
3618f664b5e8SMatthias Ringwald     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
3619f664b5e8SMatthias Ringwald }
3620f664b5e8SMatthias Ringwald 
3621d9a7306aSMatthias Ringwald static void sm_event_packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
36223deb3ec6SMatthias Ringwald 
3623cbdfe9f7SMatthias Ringwald     UNUSED(channel);    // ok: there is no channel
3624cbdfe9f7SMatthias Ringwald     UNUSED(size);       // ok: fixed format HCI events
36259ec2630cSMatthias Ringwald 
36263deb3ec6SMatthias Ringwald     sm_connection_t * sm_conn;
3627711e6c80SMatthias Ringwald     hci_con_handle_t  con_handle;
3628fbe050beSMatthias Ringwald     uint8_t           status;
3629f664b5e8SMatthias Ringwald     bd_addr_t         addr;
3630f664b5e8SMatthias Ringwald 
36313deb3ec6SMatthias Ringwald     switch (packet_type) {
36323deb3ec6SMatthias Ringwald 
36333deb3ec6SMatthias Ringwald 		case HCI_EVENT_PACKET:
36340e2df43fSMatthias Ringwald 			switch (hci_event_packet_get_type(packet)) {
36353deb3ec6SMatthias Ringwald 
36363deb3ec6SMatthias Ringwald                 case BTSTACK_EVENT_STATE:
36373deb3ec6SMatthias Ringwald 					// bt stack activated, get started
3638be7cc9a0SMilanka Ringwald 					if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
36393deb3ec6SMatthias Ringwald                         log_info("HCI Working!");
3640899e6e02SMatthias Ringwald 
3641899e6e02SMatthias Ringwald                         // setup IR/ER with TLV
3642899e6e02SMatthias Ringwald                         btstack_tlv_get_instance(&sm_tlv_impl, &sm_tlv_context);
36439305033eSMatthias Ringwald                         if (sm_tlv_impl != NULL){
36444ea43905SMatthias Ringwald                             int key_size = sm_tlv_impl->get_tag(sm_tlv_context, BTSTACK_TAG32('S','M','E','R'), sm_persistent_er, 16u);
3645899e6e02SMatthias Ringwald                             if (key_size == 16){
3646899e6e02SMatthias Ringwald                                 // ok, let's continue
3647899e6e02SMatthias Ringwald                                 log_info("ER from TLV");
3648899e6e02SMatthias Ringwald                                 sm_handle_random_result_er( NULL );
3649899e6e02SMatthias Ringwald                             } else {
3650899e6e02SMatthias Ringwald                                 // invalid, generate random one
36511979f09cSMatthias Ringwald                                 sm_persistent_keys_random_active = true;
3652899e6e02SMatthias Ringwald                                 btstack_crypto_random_generate(&sm_crypto_random_request, sm_persistent_er, 16, &sm_handle_random_result_er, &sm_persistent_er);
3653899e6e02SMatthias Ringwald                             }
3654899e6e02SMatthias Ringwald                         } else {
3655899e6e02SMatthias Ringwald                             sm_validate_er_ir();
36568d9b6072SMatthias Ringwald                             dkg_state = DKG_CALC_IRK;
3657841468bbSMatthias Ringwald 
3658841468bbSMatthias Ringwald                             if (test_use_fixed_local_irk){
3659841468bbSMatthias Ringwald                                 log_info_key("IRK", sm_persistent_irk);
3660841468bbSMatthias Ringwald                                 dkg_state = DKG_CALC_DHK;
3661841468bbSMatthias Ringwald                             }
3662899e6e02SMatthias Ringwald                         }
36631bf086daSMatthias Ringwald 
36641bf086daSMatthias Ringwald                         // restart random address updates after power cycle
36651bf086daSMatthias Ringwald                         gap_random_address_set_mode(gap_random_adress_type);
36663deb3ec6SMatthias Ringwald 					}
36673deb3ec6SMatthias Ringwald 					break;
3668c18be159SMatthias Ringwald 
36692d095694SMatthias Ringwald #ifdef ENABLE_CLASSIC
36702d095694SMatthias Ringwald 			    case HCI_EVENT_CONNECTION_COMPLETE:
36712d095694SMatthias Ringwald 			        // ignore if connection failed
36722d095694SMatthias Ringwald 			        if (hci_event_connection_complete_get_status(packet)) return;
36733deb3ec6SMatthias Ringwald 
36742d095694SMatthias Ringwald 			        con_handle = hci_event_connection_complete_get_connection_handle(packet);
36752d095694SMatthias Ringwald 			        sm_conn = sm_get_connection_for_handle(con_handle);
36762d095694SMatthias Ringwald 			        if (!sm_conn) break;
36772d095694SMatthias Ringwald 
36782d095694SMatthias Ringwald                     hci_event_connection_complete_get_bd_addr(packet, addr);
36792d095694SMatthias Ringwald 			        sm_connection_init(sm_conn,
36802d095694SMatthias Ringwald                                        con_handle,
36812d095694SMatthias Ringwald                                        (uint8_t) gap_get_role(con_handle),
3682f72f7944SMatthias Ringwald                                        BD_ADDR_TYPE_LE_PUBLIC,
36832d095694SMatthias Ringwald                                        addr);
36842d095694SMatthias Ringwald 			        // classic connection corresponds to public le address
36852d095694SMatthias Ringwald 			        sm_conn->sm_own_addr_type = BD_ADDR_TYPE_LE_PUBLIC;
36862d095694SMatthias Ringwald                     gap_local_bd_addr(sm_conn->sm_own_address);
36872d095694SMatthias Ringwald                     sm_conn->sm_cid = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
3688c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_W4_ENCRYPTION_COMPLETE;
36892d095694SMatthias Ringwald 			        break;
36902d095694SMatthias Ringwald #endif
3691c18be159SMatthias Ringwald 
3692c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3693c18be159SMatthias Ringwald 			    case HCI_EVENT_SIMPLE_PAIRING_COMPLETE:
3694c18be159SMatthias Ringwald 			        if (hci_event_simple_pairing_complete_get_status(packet) != ERROR_CODE_SUCCESS) break;
3695c18be159SMatthias Ringwald                     hci_event_simple_pairing_complete_get_bd_addr(packet, addr);
3696c18be159SMatthias Ringwald                     sm_conn = sm_get_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL);
3697c18be159SMatthias Ringwald                     if (sm_conn == NULL) break;
3698c18be159SMatthias Ringwald                     sm_conn->sm_pairing_requested = 1;
3699c18be159SMatthias Ringwald 			        break;
3700c18be159SMatthias Ringwald #endif
3701c18be159SMatthias Ringwald 
37023deb3ec6SMatthias Ringwald                 case HCI_EVENT_LE_META:
37033deb3ec6SMatthias Ringwald                     switch (packet[2]) {
37043deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
3705f664b5e8SMatthias Ringwald                             // ignore if connection failed
3706f664b5e8SMatthias Ringwald                             if (packet[3]) return;
37073deb3ec6SMatthias Ringwald 
3708711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 4);
3709711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37103deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37113deb3ec6SMatthias Ringwald 
3712f664b5e8SMatthias Ringwald                             hci_subevent_le_connection_complete_get_peer_address(packet, addr);
3713f664b5e8SMatthias Ringwald                             sm_connection_init(sm_conn,
3714f664b5e8SMatthias Ringwald                                                con_handle,
3715f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_role(packet),
3716f664b5e8SMatthias Ringwald                                                hci_subevent_le_connection_complete_get_peer_address_type(packet),
3717f664b5e8SMatthias Ringwald                                                addr);
3718687a03c8SMatthias Ringwald                             sm_conn->sm_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
3719f664b5e8SMatthias Ringwald 
3720f664b5e8SMatthias Ringwald                             // track our addr used for this connection and set state
3721b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3722b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) != 0){
3723ba9fc867SMatthias Ringwald                                 // responder - use own address from advertisements
3724ba9fc867SMatthias Ringwald                                 gap_le_get_own_advertisements_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
3725f664b5e8SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
3726b892db1cSMatthias Ringwald                             }
3727b892db1cSMatthias Ringwald #endif
3728b892db1cSMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
3729b892db1cSMatthias Ringwald                             if (hci_subevent_le_connection_complete_get_role(packet) == 0){
3730ba9fc867SMatthias Ringwald                                 // initiator - use own address from create connection
3731ba9fc867SMatthias Ringwald                                 gap_le_get_own_connection_address(&sm_conn->sm_own_addr_type, sm_conn->sm_own_address);
37323deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
37333deb3ec6SMatthias Ringwald                             }
3734b892db1cSMatthias Ringwald #endif
37353deb3ec6SMatthias Ringwald                             break;
37363deb3ec6SMatthias Ringwald 
37373deb3ec6SMatthias Ringwald                         case HCI_SUBEVENT_LE_LONG_TERM_KEY_REQUEST:
3738711e6c80SMatthias Ringwald                             con_handle = little_endian_read_16(packet, 3);
3739711e6c80SMatthias Ringwald                             sm_conn = sm_get_connection_for_handle(con_handle);
37403deb3ec6SMatthias Ringwald                             if (!sm_conn) break;
37413deb3ec6SMatthias Ringwald 
37423deb3ec6SMatthias Ringwald                             log_info("LTK Request: state %u", sm_conn->sm_engine_state);
37433deb3ec6SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_RESPONDER_PH2_W4_LTK_REQUEST){
37443deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH2_CALC_STK;
37453deb3ec6SMatthias Ringwald                                 break;
37463deb3ec6SMatthias Ringwald                             }
3747c6b7cbd9SMatthias Ringwald                             if (sm_conn->sm_engine_state == SM_SC_W4_LTK_REQUEST_SC){
3748778b6aadSMatthias Ringwald                                 // PH2 SEND LTK as we need to exchange keys in PH3
3749778b6aadSMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_PH2_SEND_LTK_REPLY;
3750e53be891SMatthias Ringwald                                 break;
3751e53be891SMatthias Ringwald                             }
37523deb3ec6SMatthias Ringwald 
37533deb3ec6SMatthias Ringwald                             // store rand and ediv
37549c80e4ccSMatthias Ringwald                             reverse_64(&packet[5], sm_conn->sm_local_rand);
3755f8fbdce0SMatthias Ringwald                             sm_conn->sm_local_ediv = little_endian_read_16(packet, 13);
3756549ad5d2SMatthias Ringwald 
3757549ad5d2SMatthias Ringwald                             // For Legacy Pairing (<=> EDIV != 0 || RAND != NULL), we need to recalculated our LTK as a
3758549ad5d2SMatthias Ringwald                             // potentially stored LTK is from the master
37594ea43905SMatthias Ringwald                             if ((sm_conn->sm_local_ediv != 0u) || !sm_is_null_random(sm_conn->sm_local_rand)){
37606c39055aSMatthias Ringwald                                 if (sm_reconstruct_ltk_without_le_device_db_entry){
376106cd539fSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
3762549ad5d2SMatthias Ringwald                                     break;
3763549ad5d2SMatthias Ringwald                                 }
37646c39055aSMatthias Ringwald                                 // additionally check if remote is in LE Device DB if requested
37656c39055aSMatthias Ringwald                                 switch(sm_conn->sm_irk_lookup_state){
37666c39055aSMatthias Ringwald                                     case IRK_LOOKUP_FAILED:
37676c39055aSMatthias Ringwald                                         log_info("LTK Request: device not in device db");
37686c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
37696c39055aSMatthias Ringwald                                         break;
37706c39055aSMatthias Ringwald                                     case IRK_LOOKUP_SUCCEEDED:
37716c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_REQUEST;
37726c39055aSMatthias Ringwald                                         break;
37736c39055aSMatthias Ringwald                                     default:
37746c39055aSMatthias Ringwald                                         // wait for irk look doen
37756c39055aSMatthias Ringwald                                         sm_conn->sm_engine_state = SM_RESPONDER_PH0_RECEIVED_LTK_W4_IRK;
37766c39055aSMatthias Ringwald                                         break;
37776c39055aSMatthias Ringwald                                 }
37786c39055aSMatthias Ringwald                                 break;
37796c39055aSMatthias Ringwald                             }
3780549ad5d2SMatthias Ringwald 
3781549ad5d2SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
378206cd539fSMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_RECEIVED_LTK_REQUEST;
3783549ad5d2SMatthias Ringwald #else
3784549ad5d2SMatthias Ringwald                             log_info("LTK Request: ediv & random are empty, but LE Secure Connections not supported");
3785549ad5d2SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_PH0_SEND_LTK_REQUESTED_NEGATIVE_REPLY;
3786549ad5d2SMatthias Ringwald #endif
37873deb3ec6SMatthias Ringwald                             break;
3788804d3e67SMatthias Ringwald 
37893deb3ec6SMatthias Ringwald                         default:
37903deb3ec6SMatthias Ringwald                             break;
37913deb3ec6SMatthias Ringwald                     }
37923deb3ec6SMatthias Ringwald                     break;
37933deb3ec6SMatthias Ringwald 
37943deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_CHANGE:
37953b7fd749SMatthias Ringwald                 	con_handle = hci_event_encryption_change_get_connection_handle(packet);
3796711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
37973deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
37983deb3ec6SMatthias Ringwald 
37993b7fd749SMatthias Ringwald                     sm_conn->sm_connection_encrypted = hci_event_encryption_change_get_encryption_enabled(packet);
38003deb3ec6SMatthias Ringwald                     log_info("Encryption state change: %u, key size %u", sm_conn->sm_connection_encrypted,
38013deb3ec6SMatthias Ringwald                         sm_conn->sm_actual_encryption_key_size);
38023deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
380303a9359aSMatthias Ringwald 
3804fbe050beSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
3805fbe050beSMatthias Ringwald 
38065567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
380703a9359aSMatthias Ringwald                             // encryption change event concludes re-encryption for bonded devices (even if it fails)
3808fbe050beSMatthias Ringwald                             if (sm_conn->sm_connection_encrypted) {
3809fbe050beSMatthias Ringwald                                 status = ERROR_CODE_SUCCESS;
38108d4eef95SMatthias Ringwald                                 if (sm_conn->sm_role){
38118d4eef95SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38128d4eef95SMatthias Ringwald                                 } else {
381303a9359aSMatthias Ringwald                                     sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38148d4eef95SMatthias Ringwald                                 }
3815fbe050beSMatthias Ringwald                             } else {
3816e28291c1SMatthias Ringwald                                 status = hci_event_encryption_change_get_status(packet);
3817cb6d7eb0SMatthias Ringwald                                 // set state to 'RE-ENCRYPTION FAILED' to allow pairing but prevent other interactions
38183b7fd749SMatthias Ringwald                                 // also, gap_reconnect_security_setup_active will return true
3819cb6d7eb0SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_GENERAL_REENCRYPTION_FAILED;
38203b7fd749SMatthias Ringwald                             }
3821fbe050beSMatthias Ringwald 
3822fbe050beSMatthias Ringwald                             // emit re-encryption complete
382373102768SMatthias Ringwald                             sm_reencryption_complete(sm_conn, status);
3824fbe050beSMatthias Ringwald 
3825c245ca32SMatthias Ringwald                             // notify client, if pairing was requested before
3826c245ca32SMatthias Ringwald                             if (sm_conn->sm_pairing_requested){
3827c245ca32SMatthias Ringwald                                 sm_conn->sm_pairing_requested = 0;
38280ccf6c9cSMatthias Ringwald                                 sm_pairing_complete(sm_conn, status, 0);
382903a9359aSMatthias Ringwald                             }
383003a9359aSMatthias Ringwald 
38313deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38323deb3ec6SMatthias Ringwald                             break;
3833fbe050beSMatthias Ringwald 
38343deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
3835fbe050beSMatthias Ringwald                             if (!sm_conn->sm_connection_encrypted) break;
3836dd583d9fSMatthias Ringwald                             sm_conn->sm_connection_sc = setup->sm_use_secure_connections;
383742134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38383deb3ec6SMatthias Ringwald                                 // slave
3839bbf8db22SMatthias Ringwald                                 if (setup->sm_use_secure_connections){
3840bbf8db22SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
3841bbf8db22SMatthias Ringwald                                 } else {
3842f3582630SMatthias 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);
3843bbf8db22SMatthias Ringwald                                 }
38443deb3ec6SMatthias Ringwald                             } else {
38453deb3ec6SMatthias Ringwald                                 // master
384661d1a45eSMatthias Ringwald                                 if (sm_key_distribution_all_received()){
38473deb3ec6SMatthias Ringwald                                     // skip receiving keys as there are none
38483deb3ec6SMatthias Ringwald                                     sm_key_distribution_handle_all_received(sm_conn);
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);
38503deb3ec6SMatthias Ringwald                                 } else {
38513deb3ec6SMatthias Ringwald                                     sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38523deb3ec6SMatthias Ringwald                                 }
38533deb3ec6SMatthias Ringwald                             }
38543deb3ec6SMatthias Ringwald                             break;
3855c18be159SMatthias Ringwald 
3856c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
3857c18be159SMatthias Ringwald                         case SM_BR_EDR_W4_ENCRYPTION_COMPLETE:
3858c18be159SMatthias Ringwald                             if (sm_conn->sm_connection_encrypted != 2) break;
3859c18be159SMatthias Ringwald                             // prepare for pairing request
3860c18be159SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
3861c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST;
3862c18be159SMatthias Ringwald                             } else if (sm_conn->sm_pairing_requested){
3863c18be159SMatthias Ringwald                                 // only send LE pairing request after BR/EDR SSP
3864c18be159SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_BR_EDR_INITIATOR_SEND_PAIRING_REQUEST;
3865c18be159SMatthias Ringwald                             }
3866c18be159SMatthias Ringwald                             break;
3867c18be159SMatthias Ringwald #endif
38683deb3ec6SMatthias Ringwald                         default:
38693deb3ec6SMatthias Ringwald                             break;
38703deb3ec6SMatthias Ringwald                     }
38713deb3ec6SMatthias Ringwald                     break;
38723deb3ec6SMatthias Ringwald 
38733deb3ec6SMatthias Ringwald                 case HCI_EVENT_ENCRYPTION_KEY_REFRESH_COMPLETE:
3874711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3875711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
38763deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
38773deb3ec6SMatthias Ringwald 
38783deb3ec6SMatthias Ringwald                     log_info("Encryption key refresh complete, key size %u", sm_conn->sm_actual_encryption_key_size);
38793deb3ec6SMatthias Ringwald                     log_info("event handler, state %u", sm_conn->sm_engine_state);
38803deb3ec6SMatthias Ringwald                     // continue if part of initial pairing
38813deb3ec6SMatthias Ringwald                     switch (sm_conn->sm_engine_state){
38825567aa60SMatthias Ringwald                         case SM_PH4_W4_CONNECTION_ENCRYPTED:
38835567aa60SMatthias Ringwald                             if (sm_conn->sm_role){
38845567aa60SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_RESPONDER_IDLE;
38855567aa60SMatthias Ringwald                             } else {
38863deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_INITIATOR_CONNECTED;
38875567aa60SMatthias Ringwald                             }
38883deb3ec6SMatthias Ringwald                             sm_done_for_handle(sm_conn->sm_handle);
38893deb3ec6SMatthias Ringwald                             break;
38903deb3ec6SMatthias Ringwald                         case SM_PH2_W4_CONNECTION_ENCRYPTED:
389142134bc6SMatthias Ringwald                             if (IS_RESPONDER(sm_conn->sm_role)){
38923deb3ec6SMatthias Ringwald                                 // slave
3893f3582630SMatthias 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);
38943deb3ec6SMatthias Ringwald                             } else {
38953deb3ec6SMatthias Ringwald                                 // master
38963deb3ec6SMatthias Ringwald                                 sm_conn->sm_engine_state = SM_PH3_RECEIVE_KEYS;
38973deb3ec6SMatthias Ringwald                             }
38983deb3ec6SMatthias Ringwald                             break;
38993deb3ec6SMatthias Ringwald                         default:
39003deb3ec6SMatthias Ringwald                             break;
39013deb3ec6SMatthias Ringwald                     }
39023deb3ec6SMatthias Ringwald                     break;
39033deb3ec6SMatthias Ringwald 
39043deb3ec6SMatthias Ringwald 
39053deb3ec6SMatthias Ringwald                 case HCI_EVENT_DISCONNECTION_COMPLETE:
3906711e6c80SMatthias Ringwald                     con_handle = little_endian_read_16(packet, 3);
3907711e6c80SMatthias Ringwald                     sm_done_for_handle(con_handle);
3908711e6c80SMatthias Ringwald                     sm_conn = sm_get_connection_for_handle(con_handle);
39093deb3ec6SMatthias Ringwald                     if (!sm_conn) break;
39103deb3ec6SMatthias Ringwald 
391103f736b1SMatthias Ringwald                     // pairing failed, if it was ongoing
39127f3f442dSMatthias Ringwald                     switch (sm_conn->sm_engine_state){
39137f3f442dSMatthias Ringwald                         case SM_GENERAL_IDLE:
39147f3f442dSMatthias Ringwald                         case SM_INITIATOR_CONNECTED:
39157f3f442dSMatthias Ringwald                         case SM_RESPONDER_IDLE:
39167f3f442dSMatthias Ringwald                             break;
39177f3f442dSMatthias Ringwald                         default:
391868a18fb9SMatthias Ringwald                             sm_reencryption_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION);
39190ccf6c9cSMatthias Ringwald                             sm_pairing_complete(sm_conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION, 0);
39207f3f442dSMatthias Ringwald                             break;
392103f736b1SMatthias Ringwald                     }
3922accbde80SMatthias Ringwald 
39233deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_GENERAL_IDLE;
39243deb3ec6SMatthias Ringwald                     sm_conn->sm_handle = 0;
39253deb3ec6SMatthias Ringwald                     break;
39263deb3ec6SMatthias Ringwald 
39273deb3ec6SMatthias Ringwald                 case HCI_EVENT_COMMAND_COMPLETE:
392833373e40SMatthias Ringwald                     if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
39299091c5f5SMatthias Ringwald                         // set local addr for le device db
393033373e40SMatthias Ringwald                         reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], addr);
39310c130b19SMatthias Ringwald                         le_device_db_set_local_bd_addr(addr);
393233373e40SMatthias Ringwald                     }
393365b44ffdSMatthias Ringwald                     break;
393465b44ffdSMatthias Ringwald                 default:
393565b44ffdSMatthias Ringwald                     break;
39363deb3ec6SMatthias Ringwald 			}
393765b44ffdSMatthias Ringwald             break;
393865b44ffdSMatthias Ringwald         default:
393965b44ffdSMatthias Ringwald             break;
39403deb3ec6SMatthias Ringwald 	}
39413deb3ec6SMatthias Ringwald 
39423deb3ec6SMatthias Ringwald     sm_run();
39433deb3ec6SMatthias Ringwald }
39443deb3ec6SMatthias Ringwald 
39453deb3ec6SMatthias Ringwald static inline int sm_calc_actual_encryption_key_size(int other){
39463deb3ec6SMatthias Ringwald     if (other < sm_min_encryption_key_size) return 0;
39473deb3ec6SMatthias Ringwald     if (other < sm_max_encryption_key_size) return other;
39483deb3ec6SMatthias Ringwald     return sm_max_encryption_key_size;
39493deb3ec6SMatthias Ringwald }
39503deb3ec6SMatthias Ringwald 
3951945888f5SMatthias Ringwald 
395231c09488SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
3953945888f5SMatthias Ringwald static int sm_just_works_or_numeric_comparison(stk_generation_method_t method){
3954945888f5SMatthias Ringwald     switch (method){
3955945888f5SMatthias Ringwald         case JUST_WORKS:
395647fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
3957945888f5SMatthias Ringwald             return 1;
3958945888f5SMatthias Ringwald         default:
3959945888f5SMatthias Ringwald             return 0;
3960945888f5SMatthias Ringwald     }
3961945888f5SMatthias Ringwald }
396207036a04SMatthias Ringwald // responder
3963945888f5SMatthias Ringwald 
3964688a08f9SMatthias Ringwald static int sm_passkey_used(stk_generation_method_t method){
3965688a08f9SMatthias Ringwald     switch (method){
3966688a08f9SMatthias Ringwald         case PK_RESP_INPUT:
3967688a08f9SMatthias Ringwald             return 1;
3968688a08f9SMatthias Ringwald         default:
3969688a08f9SMatthias Ringwald             return 0;
3970688a08f9SMatthias Ringwald     }
3971688a08f9SMatthias Ringwald }
397240c5d850SMatthias Ringwald 
397340c5d850SMatthias Ringwald static int sm_passkey_entry(stk_generation_method_t method){
397440c5d850SMatthias Ringwald     switch (method){
397540c5d850SMatthias Ringwald         case PK_RESP_INPUT:
397640c5d850SMatthias Ringwald         case PK_INIT_INPUT:
397747fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
397840c5d850SMatthias Ringwald             return 1;
397940c5d850SMatthias Ringwald         default:
398040c5d850SMatthias Ringwald             return 0;
398140c5d850SMatthias Ringwald     }
398240c5d850SMatthias Ringwald }
398340c5d850SMatthias Ringwald 
398431c09488SMatthias Ringwald #endif
3985688a08f9SMatthias Ringwald 
39863deb3ec6SMatthias Ringwald /**
39873deb3ec6SMatthias Ringwald  * @return ok
39883deb3ec6SMatthias Ringwald  */
39893deb3ec6SMatthias Ringwald static int sm_validate_stk_generation_method(void){
39903deb3ec6SMatthias Ringwald     // check if STK generation method is acceptable by client
39913deb3ec6SMatthias Ringwald     switch (setup->sm_stk_generation_method){
39923deb3ec6SMatthias Ringwald         case JUST_WORKS:
39934ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_JUST_WORKS) != 0u;
39943deb3ec6SMatthias Ringwald         case PK_RESP_INPUT:
39953deb3ec6SMatthias Ringwald         case PK_INIT_INPUT:
399647fb4255SMatthias Ringwald         case PK_BOTH_INPUT:
39974ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_PASSKEY) != 0u;
39983deb3ec6SMatthias Ringwald         case OOB:
39994ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_OOB) != 0u;
400047fb4255SMatthias Ringwald         case NUMERIC_COMPARISON:
40014ea43905SMatthias Ringwald             return (sm_accepted_stk_generation_methods & SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON) != 0u;
40023deb3ec6SMatthias Ringwald         default:
40033deb3ec6SMatthias Ringwald             return 0;
40043deb3ec6SMatthias Ringwald     }
40053deb3ec6SMatthias Ringwald }
40063deb3ec6SMatthias Ringwald 
40078334d3d8SMatthias Ringwald static void sm_pdu_handler(uint8_t packet_type, hci_con_handle_t con_handle, uint8_t *packet, uint16_t size){
40088334d3d8SMatthias Ringwald 
40094c1d1092SMatthias Ringwald     // size of complete sm_pdu used to validate input
40104c1d1092SMatthias Ringwald     static const uint8_t sm_pdu_size[] = {
40114c1d1092SMatthias Ringwald             0,  // 0x00 invalid opcode
40124c1d1092SMatthias Ringwald             7,  // 0x01 pairing request
40134c1d1092SMatthias Ringwald             7,  // 0x02 pairing response
40144c1d1092SMatthias Ringwald             17, // 0x03 pairing confirm
40154c1d1092SMatthias Ringwald             17, // 0x04 pairing random
40164c1d1092SMatthias Ringwald             2,  // 0x05 pairing failed
40174c1d1092SMatthias Ringwald             17, // 0x06 encryption information
40187a2e6387SMatthias Ringwald             11, // 0x07 master identification
40194c1d1092SMatthias Ringwald             17, // 0x08 identification information
40204c1d1092SMatthias Ringwald             8,  // 0x09 identify address information
40214c1d1092SMatthias Ringwald             17, // 0x0a signing information
40224c1d1092SMatthias Ringwald             2,  // 0x0b security request
40234c1d1092SMatthias Ringwald             65, // 0x0c pairing public key
40244c1d1092SMatthias Ringwald             17, // 0x0d pairing dhk check
40254c1d1092SMatthias Ringwald             2,  // 0x0e keypress notification
40264c1d1092SMatthias Ringwald     };
40273deb3ec6SMatthias Ringwald 
4028c1ab6cc1SMatthias Ringwald     if ((packet_type == HCI_EVENT_PACKET) && (packet[0] == L2CAP_EVENT_CAN_SEND_NOW)){
4029b170b20fSMatthias Ringwald         sm_run();
4030b170b20fSMatthias Ringwald     }
4031b170b20fSMatthias Ringwald 
40323deb3ec6SMatthias Ringwald     if (packet_type != SM_DATA_PACKET) return;
40334ea43905SMatthias Ringwald     if (size == 0u) return;
40344c1d1092SMatthias Ringwald 
40354c1d1092SMatthias Ringwald     uint8_t sm_pdu_code = packet[0];
40364c1d1092SMatthias Ringwald 
40374c1d1092SMatthias Ringwald     // validate pdu size
40384c1d1092SMatthias Ringwald     if (sm_pdu_code >= sizeof(sm_pdu_size)) return;
40397a2e6387SMatthias Ringwald     if (sm_pdu_size[sm_pdu_code] != size)   return;
40403deb3ec6SMatthias Ringwald 
4041711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
40423deb3ec6SMatthias Ringwald     if (!sm_conn) return;
40433deb3ec6SMatthias Ringwald 
40444c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_PAIRING_FAILED){
404568a18fb9SMatthias Ringwald         sm_reencryption_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE);
40460ccf6c9cSMatthias Ringwald         sm_pairing_complete(sm_conn, ERROR_CODE_AUTHENTICATION_FAILURE, packet[1]);
4047accbde80SMatthias Ringwald         sm_done_for_handle(con_handle);
40483deb3ec6SMatthias Ringwald         sm_conn->sm_engine_state = sm_conn->sm_role ? SM_RESPONDER_IDLE : SM_INITIATOR_CONNECTED;
40493deb3ec6SMatthias Ringwald         return;
40503deb3ec6SMatthias Ringwald     }
40513deb3ec6SMatthias Ringwald 
40524c1d1092SMatthias Ringwald     log_debug("sm_pdu_handler: state %u, pdu 0x%02x", sm_conn->sm_engine_state, sm_pdu_code);
40533deb3ec6SMatthias Ringwald 
40543deb3ec6SMatthias Ringwald     int err;
405542134bc6SMatthias Ringwald     UNUSED(err);
40563deb3ec6SMatthias Ringwald 
40574c1d1092SMatthias Ringwald     if (sm_pdu_code == SM_CODE_KEYPRESS_NOTIFICATION){
40583d7fe1e9SMatthias Ringwald         uint8_t buffer[5];
40593d7fe1e9SMatthias Ringwald         buffer[0] = SM_EVENT_KEYPRESS_NOTIFICATION;
40603d7fe1e9SMatthias Ringwald         buffer[1] = 3;
40613d7fe1e9SMatthias Ringwald         little_endian_store_16(buffer, 2, con_handle);
40623d7fe1e9SMatthias Ringwald         buffer[4] = packet[1];
40633d7fe1e9SMatthias Ringwald         sm_dispatch_event(HCI_EVENT_PACKET, 0, buffer, sizeof(buffer));
40643d7fe1e9SMatthias Ringwald         return;
40653d7fe1e9SMatthias Ringwald     }
40663d7fe1e9SMatthias Ringwald 
4067a6ca6916SDavid Lechner #ifdef ENABLE_LE_CENTRAL
4068212d735eSMatthias Ringwald     int have_ltk;
4069212d735eSMatthias Ringwald     uint8_t ltk[16];
4070a6ca6916SDavid Lechner #endif
4071212d735eSMatthias Ringwald 
40723deb3ec6SMatthias Ringwald     switch (sm_conn->sm_engine_state){
40733deb3ec6SMatthias Ringwald 
4074c8d0ff33SMatthias Ringwald         // a sm timeout requires a new physical connection
40753deb3ec6SMatthias Ringwald         case SM_GENERAL_TIMEOUT:
40763deb3ec6SMatthias Ringwald             return;
40773deb3ec6SMatthias Ringwald 
407842134bc6SMatthias Ringwald #ifdef ENABLE_LE_CENTRAL
407942134bc6SMatthias Ringwald 
40803deb3ec6SMatthias Ringwald         // Initiator
40813deb3ec6SMatthias Ringwald         case SM_INITIATOR_CONNECTED:
40824c1d1092SMatthias Ringwald             if ((sm_pdu_code != SM_CODE_SECURITY_REQUEST) || (sm_conn->sm_role)){
40833deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
40843deb3ec6SMatthias Ringwald                 break;
40853deb3ec6SMatthias Ringwald             }
408634c39fbdSMatthias Ringwald 
40872c041b42SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
40882c041b42SMatthias Ringwald             if (sm_sc_only_mode){
40892c041b42SMatthias Ringwald                 uint8_t auth_req = packet[1];
40902c041b42SMatthias Ringwald                 if ((auth_req & SM_AUTHREQ_SECURE_CONNECTION) == 0){
4091f4935286SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_AUTHENTHICATION_REQUIREMENTS);
40922c041b42SMatthias Ringwald                     break;
40932c041b42SMatthias Ringwald                 }
40942c041b42SMatthias Ringwald             }
40952c041b42SMatthias Ringwald #endif
40962c041b42SMatthias Ringwald 
409734c39fbdSMatthias Ringwald             // IRK complete?
409834c39fbdSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
409934c39fbdSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
4100dc8ca372SMatthias Ringwald                     // start pairing
41013deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
41023deb3ec6SMatthias Ringwald                     break;
4103e061bbd4SMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4104e061bbd4SMatthias Ringwald                     le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4105e061bbd4SMatthias Ringwald                     have_ltk = !sm_is_null_key(ltk);
41068549a61eSMatthias Ringwald                     log_info("central: security request - have_ltk %u, encryption %u", have_ltk, sm_conn->sm_connection_encrypted);
41078549a61eSMatthias Ringwald                     if (have_ltk && (sm_conn->sm_connection_encrypted == 0)){
41088549a61eSMatthias Ringwald                         // start re-encrypt if we have LTK and the connection is not already encrypted
41095567aa60SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4110e061bbd4SMatthias Ringwald                     } else {
4111dc8ca372SMatthias Ringwald                         // start pairing
4112e061bbd4SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4113e061bbd4SMatthias Ringwald                     }
4114e061bbd4SMatthias Ringwald                     break;
411534c39fbdSMatthias Ringwald                 default:
41163deb3ec6SMatthias Ringwald                     // otherwise, store security request
41173deb3ec6SMatthias Ringwald                     sm_conn->sm_security_request_received = 1;
41183deb3ec6SMatthias Ringwald                     break;
4119dc8ca372SMatthias Ringwald             }
4120dc8ca372SMatthias Ringwald             break;
41213deb3ec6SMatthias Ringwald 
41223deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH1_W4_PAIRING_RESPONSE:
4123aacfafc3SMatthias Ringwald             // Core 5, Vol 3, Part H, 2.4.6:
4124aacfafc3SMatthias Ringwald             // "The master shall ignore the slave’s Security Request if the master has sent a Pairing Request
4125aacfafc3SMatthias Ringwald             //  without receiving a Pairing Response from the slave or if the master has initiated encryption mode setup."
4126aacfafc3SMatthias Ringwald             if (sm_pdu_code == SM_CODE_SECURITY_REQUEST){
4127aacfafc3SMatthias Ringwald                 log_info("Ignoring Security Request");
4128aacfafc3SMatthias Ringwald                 break;
4129aacfafc3SMatthias Ringwald             }
4130aacfafc3SMatthias Ringwald 
4131aacfafc3SMatthias Ringwald             // all other pdus are incorrect
41324c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
41333deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41343deb3ec6SMatthias Ringwald                 break;
41353deb3ec6SMatthias Ringwald             }
41360af429c6SMatthias Ringwald 
41373deb3ec6SMatthias Ringwald             // store pairing request
41386535961aSMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet,
41396535961aSMatthias Ringwald                          sizeof(sm_pairing_packet_t));
41403deb3ec6SMatthias Ringwald             err = sm_stk_generation_init(sm_conn);
41410af429c6SMatthias Ringwald 
41420af429c6SMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
41430af429c6SMatthias Ringwald             if (0 < test_pairing_failure && test_pairing_failure < SM_REASON_DHKEY_CHECK_FAILED){
41440af429c6SMatthias Ringwald                 log_info("testing_support: abort with pairing failure %u", test_pairing_failure);
41450af429c6SMatthias Ringwald                 err = test_pairing_failure;
41460af429c6SMatthias Ringwald             }
41470af429c6SMatthias Ringwald #endif
41480af429c6SMatthias Ringwald 
41499305033eSMatthias Ringwald             if (err != 0){
4150f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, err);
41513deb3ec6SMatthias Ringwald                 break;
41523deb3ec6SMatthias Ringwald             }
4153b41539d5SMatthias Ringwald 
4154b41539d5SMatthias Ringwald             // generate random number first, if we need to show passkey
4155b41539d5SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_RESP_INPUT){
4156f3582630SMatthias 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);
4157b41539d5SMatthias Ringwald                 break;
4158b41539d5SMatthias Ringwald             }
4159b41539d5SMatthias Ringwald 
4160136d331aSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4161136d331aSMatthias Ringwald             if (setup->sm_use_secure_connections){
41628cba5ca3SMatthias Ringwald                 // SC Numeric Comparison will trigger user response after public keys & nonces have been exchanged
41638cba5ca3SMatthias Ringwald                 if (setup->sm_stk_generation_method == JUST_WORKS){
4164136d331aSMatthias Ringwald                     sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
4165136d331aSMatthias Ringwald                     sm_trigger_user_response(sm_conn);
4166136d331aSMatthias Ringwald                     if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4167c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4168136d331aSMatthias Ringwald                     }
41698cba5ca3SMatthias Ringwald                 } else {
4170c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
41718cba5ca3SMatthias Ringwald                 }
4172136d331aSMatthias Ringwald                 break;
4173136d331aSMatthias Ringwald             }
4174136d331aSMatthias Ringwald #endif
41753deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
41763deb3ec6SMatthias Ringwald             sm_trigger_user_response(sm_conn);
41773deb3ec6SMatthias Ringwald             // response_idle == nothing <--> sm_trigger_user_response() did not require response
41783deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_IDLE){
4179f3582630SMatthias 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);
41803deb3ec6SMatthias Ringwald             }
41813deb3ec6SMatthias Ringwald             break;
41823deb3ec6SMatthias Ringwald 
41833deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_CONFIRM:
41844c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
41853deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
41863deb3ec6SMatthias Ringwald                 break;
41873deb3ec6SMatthias Ringwald             }
41883deb3ec6SMatthias Ringwald 
41893deb3ec6SMatthias Ringwald             // store s_confirm
41909c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
4191192365feSMatthias Ringwald 
4192aa9b34e5SMatthias Ringwald             // abort if s_confirm matches m_confirm
4193aa9b34e5SMatthias Ringwald             if (memcmp(setup->sm_local_confirm, setup->sm_peer_confirm, 16) == 0){
4194aa9b34e5SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4195aa9b34e5SMatthias Ringwald                 break;
4196aa9b34e5SMatthias Ringwald             }
4197aa9b34e5SMatthias Ringwald 
4198192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4199192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4200192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4201192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4202192365feSMatthias Ringwald             }
4203192365feSMatthias Ringwald #endif
42043deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_SEND_PAIRING_RANDOM;
42053deb3ec6SMatthias Ringwald             break;
42063deb3ec6SMatthias Ringwald 
42073deb3ec6SMatthias Ringwald         case SM_INITIATOR_PH2_W4_PAIRING_RANDOM:
42084c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
42093deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42103deb3ec6SMatthias Ringwald                 break;;
42113deb3ec6SMatthias Ringwald             }
42123deb3ec6SMatthias Ringwald 
42133deb3ec6SMatthias Ringwald             // received random value
42149c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
42153deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
42163deb3ec6SMatthias Ringwald             break;
421742134bc6SMatthias Ringwald #endif
42183deb3ec6SMatthias Ringwald 
421942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
42203deb3ec6SMatthias Ringwald         // Responder
42213deb3ec6SMatthias Ringwald         case SM_RESPONDER_IDLE:
42223deb3ec6SMatthias Ringwald         case SM_RESPONDER_SEND_SECURITY_REQUEST:
42233deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_REQUEST:
42244c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
42253deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
42263deb3ec6SMatthias Ringwald                 break;;
42273deb3ec6SMatthias Ringwald             }
42283deb3ec6SMatthias Ringwald 
42293deb3ec6SMatthias Ringwald             // store pairing request
4230212d735eSMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4231212d735eSMatthias Ringwald 
4232212d735eSMatthias Ringwald             // check if IRK completed
4233212d735eSMatthias Ringwald             switch (sm_conn->sm_irk_lookup_state){
4234212d735eSMatthias Ringwald                 case IRK_LOOKUP_SUCCEEDED:
4235212d735eSMatthias Ringwald                 case IRK_LOOKUP_FAILED:
42363deb3ec6SMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED;
42373deb3ec6SMatthias Ringwald                     break;
4238212d735eSMatthias Ringwald                 default:
4239212d735eSMatthias Ringwald                     sm_conn->sm_engine_state = SM_RESPONDER_PH1_PAIRING_REQUEST_RECEIVED_W4_IRK;
4240212d735eSMatthias Ringwald                     break;
4241212d735eSMatthias Ringwald             }
4242212d735eSMatthias Ringwald             break;
424342134bc6SMatthias Ringwald #endif
42443deb3ec6SMatthias Ringwald 
424527c32905SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4246c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
42474c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_PUBLIC_KEY){
424827c32905SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
424927c32905SMatthias Ringwald                 break;
425027c32905SMatthias Ringwald             }
4251bccf5e67SMatthias Ringwald 
4252e53be891SMatthias Ringwald             // store public key for DH Key calculation
4253fc5bff5fSMatthias Ringwald             reverse_256(&packet[01], &setup->sm_peer_q[0]);
4254fc5bff5fSMatthias Ringwald             reverse_256(&packet[33], &setup->sm_peer_q[32]);
4255bccf5e67SMatthias Ringwald 
425602658749SMatthias Ringwald             // CVE-2020-26558: abort pairing if remote uses the same public key
425702658749SMatthias Ringwald             if (memcmp(&setup->sm_peer_q, ec_q, 64) == 0){
425802658749SMatthias Ringwald                 log_info("Remote PK matches ours");
425902658749SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
426002658749SMatthias Ringwald                 break;
426102658749SMatthias Ringwald             }
426202658749SMatthias Ringwald 
4263d1a1f6a4SMatthias Ringwald             // validate public key
4264d1a1f6a4SMatthias Ringwald             err = btstack_crypto_ecc_p256_validate_public_key(setup->sm_peer_q);
42659305033eSMatthias Ringwald             if (err != 0){
426602658749SMatthias Ringwald                 log_info("sm: peer public key invalid %x", err);
4267349d0adbSMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_DHKEY_CHECK_FAILED);
4268bccf5e67SMatthias Ringwald                 break;
4269bccf5e67SMatthias Ringwald             }
4270891bb64aSMatthias Ringwald 
4271d1a1f6a4SMatthias Ringwald             // start calculating dhkey
4272f3582630SMatthias 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);
42733cf37b8cSMatthias Ringwald 
427465a9a04eSMatthias Ringwald 
427565a9a04eSMatthias Ringwald             log_info("public key received, generation method %u", setup->sm_stk_generation_method);
427642134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
4277136d331aSMatthias Ringwald                 // responder
4278c6b7cbd9SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4279136d331aSMatthias Ringwald             } else {
4280136d331aSMatthias Ringwald                 // initiator
4281a1e31e9cSMatthias Ringwald                 // stk generation method
4282a1e31e9cSMatthias Ringwald                 // passkey entry: notify app to show passkey or to request passkey
4283a1e31e9cSMatthias Ringwald                 switch (setup->sm_stk_generation_method){
4284a1e31e9cSMatthias Ringwald                     case JUST_WORKS:
428547fb4255SMatthias Ringwald                     case NUMERIC_COMPARISON:
4286c6b7cbd9SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_CONFIRMATION;
4287a1e31e9cSMatthias Ringwald                         break;
4288a1e31e9cSMatthias Ringwald                     case PK_RESP_INPUT:
428907036a04SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
429007036a04SMatthias Ringwald                         break;
429107036a04SMatthias Ringwald                     case PK_INIT_INPUT:
429247fb4255SMatthias Ringwald                     case PK_BOTH_INPUT:
429307036a04SMatthias Ringwald                         if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
429407036a04SMatthias Ringwald                             sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
429507036a04SMatthias Ringwald                             break;
429607036a04SMatthias Ringwald                         }
4297b35a3de2SMatthias Ringwald                         sm_sc_start_calculating_local_confirm(sm_conn);
4298a1e31e9cSMatthias Ringwald                         break;
4299a1e31e9cSMatthias Ringwald                     case OOB:
4300d1a1f6a4SMatthias Ringwald                         // generate Nx
43014acf7b7bSMatthias Ringwald                         log_info("Generate Na");
43026ca80073SMatthias 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);
4303a1e31e9cSMatthias Ringwald                         break;
43047bbeb3adSMilanka Ringwald                     default:
43057bbeb3adSMilanka Ringwald                         btstack_assert(false);
43067bbeb3adSMilanka Ringwald                         break;
4307a1e31e9cSMatthias Ringwald                 }
4308136d331aSMatthias Ringwald             }
430927c32905SMatthias Ringwald             break;
4310e53be891SMatthias Ringwald 
4311c6b7cbd9SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
43124c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
431345a61d50SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
431445a61d50SMatthias Ringwald                 break;
431545a61d50SMatthias Ringwald             }
431645a61d50SMatthias Ringwald             // received confirm value
431745a61d50SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
431845a61d50SMatthias Ringwald 
4319192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4320192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4321192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4322192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4323192365feSMatthias Ringwald             }
4324192365feSMatthias Ringwald #endif
432542134bc6SMatthias Ringwald             if (IS_RESPONDER(sm_conn->sm_role)){
432645a61d50SMatthias Ringwald                 // responder
432707036a04SMatthias Ringwald                 if (sm_passkey_used(setup->sm_stk_generation_method)){
432807036a04SMatthias Ringwald                     if (setup->sm_user_response != SM_USER_RESPONSE_PASSKEY){
432907036a04SMatthias Ringwald                         // still waiting for passkey
433007036a04SMatthias Ringwald                         sm_conn->sm_engine_state = SM_SC_W4_USER_RESPONSE;
433107036a04SMatthias Ringwald                         break;
433207036a04SMatthias Ringwald                     }
433307036a04SMatthias Ringwald                 }
4334b35a3de2SMatthias Ringwald                 sm_sc_start_calculating_local_confirm(sm_conn);
433545a61d50SMatthias Ringwald             } else {
433645a61d50SMatthias Ringwald                 // initiator
4337945888f5SMatthias Ringwald                 if (sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method)){
43386ca80073SMatthias 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);
4339f1c1783eSMatthias Ringwald                 } else {
4340c6b7cbd9SMatthias Ringwald                     sm_conn->sm_engine_state = SM_SC_SEND_PAIRING_RANDOM;
434145a61d50SMatthias Ringwald                 }
4342f1c1783eSMatthias Ringwald             }
434345a61d50SMatthias Ringwald             break;
434445a61d50SMatthias Ringwald 
4345c6b7cbd9SMatthias Ringwald         case SM_SC_W4_PAIRING_RANDOM:
43464c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
4347e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4348136d331aSMatthias Ringwald                 break;
4349e53be891SMatthias Ringwald             }
4350e53be891SMatthias Ringwald 
4351e53be891SMatthias Ringwald             // received random value
4352e53be891SMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_nonce);
4353e53be891SMatthias Ringwald 
43545a293e6eSMatthias Ringwald             // validate confirm value if Cb = f4(Pkb, Pka, Nb, z)
4355ae451ec5SMatthias Ringwald             // only check for JUST WORK/NC in initiator role OR passkey entry
4356d686b2d0SMatthias Ringwald             log_info("SM_SC_W4_PAIRING_RANDOM, responder: %u, just works: %u, passkey used %u, passkey entry %u",
4357d686b2d0SMatthias Ringwald                      IS_RESPONDER(sm_conn->sm_role), sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method),
4358d686b2d0SMatthias Ringwald                      sm_passkey_used(setup->sm_stk_generation_method), sm_passkey_entry(setup->sm_stk_generation_method));
435965a9a04eSMatthias Ringwald             if ( (!IS_RESPONDER(sm_conn->sm_role) && sm_just_works_or_numeric_comparison(setup->sm_stk_generation_method))
4360d686b2d0SMatthias Ringwald             ||   (sm_passkey_entry(setup->sm_stk_generation_method)) ) {
4361688a08f9SMatthias Ringwald                  sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4362ae451ec5SMatthias Ringwald                  break;
43635a293e6eSMatthias Ringwald             }
43646f52a196SMatthias Ringwald 
43654acf7b7bSMatthias Ringwald             // OOB
43664acf7b7bSMatthias Ringwald             if (setup->sm_stk_generation_method == OOB){
43674acf7b7bSMatthias Ringwald 
43684acf7b7bSMatthias Ringwald                 // setup local random, set to zero if remote did not receive our data
43694acf7b7bSMatthias Ringwald                 log_info("Received nonce, setup local random ra/rb for dhkey check");
43704acf7b7bSMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
43714ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_m_preq) == 0u){
43724acf7b7bSMatthias Ringwald                         log_info("Reset rb as A does not have OOB data");
43734acf7b7bSMatthias Ringwald                         memset(setup->sm_rb, 0, 16);
43744acf7b7bSMatthias Ringwald                     } else {
43756535961aSMatthias Ringwald                         (void)memcpy(setup->sm_rb, sm_sc_oob_random, 16);
43764acf7b7bSMatthias Ringwald                         log_info("Use stored rb");
43774acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_rb, 16);
43784acf7b7bSMatthias Ringwald                     }
43794acf7b7bSMatthias Ringwald                 }  else {
43804ea43905SMatthias Ringwald                     if (sm_pairing_packet_get_oob_data_flag(setup->sm_s_pres) == 0u){
43814acf7b7bSMatthias Ringwald                         log_info("Reset ra as B does not have OOB data");
43824acf7b7bSMatthias Ringwald                         memset(setup->sm_ra, 0, 16);
43834acf7b7bSMatthias Ringwald                     } else {
43846535961aSMatthias Ringwald                         (void)memcpy(setup->sm_ra, sm_sc_oob_random, 16);
43854acf7b7bSMatthias Ringwald                         log_info("Use stored ra");
43864acf7b7bSMatthias Ringwald                         log_info_hexdump(setup->sm_ra, 16);
43874acf7b7bSMatthias Ringwald                     }
43884acf7b7bSMatthias Ringwald                 }
43894acf7b7bSMatthias Ringwald 
4390a680ba6bSMatthias Ringwald                 // validate confirm value if Cb = f4(PKb, Pkb, rb, 0) for OOB if data received
43914acf7b7bSMatthias Ringwald                 if (setup->sm_have_oob_data){
4392a680ba6bSMatthias Ringwald                      sm_conn->sm_engine_state = SM_SC_W2_CMAC_FOR_CHECK_CONFIRMATION;
4393a680ba6bSMatthias Ringwald                      break;
4394a680ba6bSMatthias Ringwald                 }
43954acf7b7bSMatthias Ringwald             }
4396a680ba6bSMatthias Ringwald 
4397a680ba6bSMatthias Ringwald             // TODO: we only get here for Responder role with JW/NC
4398688a08f9SMatthias Ringwald             sm_sc_state_after_receiving_random(sm_conn);
4399e53be891SMatthias Ringwald             break;
4400e53be891SMatthias Ringwald 
4401901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_G2:
4402901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_G2:
44033cf37b8cSMatthias Ringwald         case SM_SC_W4_CALCULATE_DHKEY:
4404901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_SALT:
4405901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_SALT:
4406901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_MACKEY:
4407901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_MACKEY:
4408901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F5_LTK:
4409901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F5_LTK:
4410901c000fSMatthias Ringwald         case SM_SC_W2_CALCULATE_F6_FOR_DHKEY_CHECK:
4411c6b7cbd9SMatthias Ringwald         case SM_SC_W4_DHKEY_CHECK_COMMAND:
4412901c000fSMatthias Ringwald         case SM_SC_W4_CALCULATE_F6_FOR_DHKEY_CHECK:
4413d08147dfSMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
44144c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_DHKEY_CHECK){
4415e53be891SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4416e53be891SMatthias Ringwald                 break;
4417e53be891SMatthias Ringwald             }
4418e53be891SMatthias Ringwald             // store DHKey Check
4419901c000fSMatthias Ringwald             setup->sm_state_vars |= SM_STATE_VAR_DHKEY_COMMAND_RECEIVED;
4420e53be891SMatthias Ringwald             reverse_128(&packet[01], setup->sm_peer_dhkey_check);
4421446a8c36SMatthias Ringwald 
4422901c000fSMatthias Ringwald             // have we been only waiting for dhkey check command?
4423901c000fSMatthias Ringwald             if (sm_conn->sm_engine_state == SM_SC_W4_DHKEY_CHECK_COMMAND){
4424019005a0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_SC_W2_CALCULATE_F6_TO_VERIFY_DHKEY_CHECK;
4425bd57ffebSMatthias Ringwald             }
4426bd57ffebSMatthias Ringwald             break;
442727c32905SMatthias Ringwald #endif
442827c32905SMatthias Ringwald 
442942134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
44303deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH1_W4_PAIRING_CONFIRM:
44314c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_CONFIRM){
44323deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
443327c32905SMatthias Ringwald                 break;
44343deb3ec6SMatthias Ringwald             }
44353deb3ec6SMatthias Ringwald 
44363deb3ec6SMatthias Ringwald             // received confirm value
44379c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_confirm);
44383deb3ec6SMatthias Ringwald 
4439192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4440192365feSMatthias Ringwald             if (test_pairing_failure == SM_REASON_CONFIRM_VALUE_FAILED){
4441192365feSMatthias Ringwald                 log_info("testing_support: reset confirm value");
4442192365feSMatthias Ringwald                 memset(setup->sm_peer_confirm, 0, 16);
4443192365feSMatthias Ringwald             }
4444192365feSMatthias Ringwald #endif
44453deb3ec6SMatthias Ringwald             // notify client to hide shown passkey
44463deb3ec6SMatthias Ringwald             if (setup->sm_stk_generation_method == PK_INIT_INPUT){
44475611a760SMatthias 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);
44483deb3ec6SMatthias Ringwald             }
44493deb3ec6SMatthias Ringwald 
44503deb3ec6SMatthias Ringwald             // handle user cancel pairing?
44513deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_DECLINE){
4452f4935286SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
44533deb3ec6SMatthias Ringwald                 break;
44543deb3ec6SMatthias Ringwald             }
44553deb3ec6SMatthias Ringwald 
44563deb3ec6SMatthias Ringwald             // wait for user action?
44573deb3ec6SMatthias Ringwald             if (setup->sm_user_response == SM_USER_RESPONSE_PENDING){
44583deb3ec6SMatthias Ringwald                 sm_conn->sm_engine_state = SM_PH1_W4_USER_RESPONSE;
44593deb3ec6SMatthias Ringwald                 break;
44603deb3ec6SMatthias Ringwald             }
44613deb3ec6SMatthias Ringwald 
44623deb3ec6SMatthias Ringwald             // calculate and send local_confirm
4463f3582630SMatthias 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);
44643deb3ec6SMatthias Ringwald             break;
44653deb3ec6SMatthias Ringwald 
44663deb3ec6SMatthias Ringwald         case SM_RESPONDER_PH2_W4_PAIRING_RANDOM:
44674c1d1092SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RANDOM){
44683deb3ec6SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
44693deb3ec6SMatthias Ringwald                 break;;
44703deb3ec6SMatthias Ringwald             }
44713deb3ec6SMatthias Ringwald 
44723deb3ec6SMatthias Ringwald             // received random value
44739c80e4ccSMatthias Ringwald             reverse_128(&packet[1], setup->sm_peer_random);
44743deb3ec6SMatthias Ringwald             sm_conn->sm_engine_state = SM_PH2_C1_GET_ENC_C;
44753deb3ec6SMatthias Ringwald             break;
447642134bc6SMatthias Ringwald #endif
44773deb3ec6SMatthias Ringwald 
44783deb3ec6SMatthias Ringwald         case SM_PH3_RECEIVE_KEYS:
44794c1d1092SMatthias Ringwald             switch(sm_pdu_code){
44803deb3ec6SMatthias Ringwald                 case SM_CODE_ENCRYPTION_INFORMATION:
44813deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_ENCRYPTION_INFORMATION;
44829c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_ltk);
44833deb3ec6SMatthias Ringwald                     break;
44843deb3ec6SMatthias Ringwald 
44853deb3ec6SMatthias Ringwald                 case SM_CODE_MASTER_IDENTIFICATION:
44863deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_MASTER_IDENTIFICATION;
4487f8fbdce0SMatthias Ringwald                     setup->sm_peer_ediv = little_endian_read_16(packet, 1);
44889c80e4ccSMatthias Ringwald                     reverse_64(&packet[3], setup->sm_peer_rand);
44893deb3ec6SMatthias Ringwald                     break;
44903deb3ec6SMatthias Ringwald 
44913deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
44923deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
44939c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
44943deb3ec6SMatthias Ringwald                     break;
44953deb3ec6SMatthias Ringwald 
44963deb3ec6SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
44973deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
44983deb3ec6SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4499724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
45003deb3ec6SMatthias Ringwald                     break;
45013deb3ec6SMatthias Ringwald 
45023deb3ec6SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
45033deb3ec6SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
45049c80e4ccSMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
45053deb3ec6SMatthias Ringwald                     break;
45063deb3ec6SMatthias Ringwald                 default:
45073deb3ec6SMatthias Ringwald                     // Unexpected PDU
45083deb3ec6SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
45093deb3ec6SMatthias Ringwald                     break;
45103deb3ec6SMatthias Ringwald             }
45113deb3ec6SMatthias Ringwald             // done with key distribution?
451261d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
45133deb3ec6SMatthias Ringwald 
45143deb3ec6SMatthias Ringwald                 sm_key_distribution_handle_all_received(sm_conn);
45153deb3ec6SMatthias Ringwald 
451642134bc6SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
45176f7422f1SMatthias Ringwald                     sm_key_distribution_complete_responder(sm_conn);
45183deb3ec6SMatthias Ringwald                 } else {
4519625f00b2SMatthias Ringwald                     if (setup->sm_use_secure_connections){
4520625f00b2SMatthias Ringwald                         sm_conn->sm_engine_state = SM_PH3_DISTRIBUTE_KEYS;
4521bbf8db22SMatthias Ringwald                     } else {
4522f3582630SMatthias 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);
4523625f00b2SMatthias Ringwald                     }
45243deb3ec6SMatthias Ringwald                 }
45253deb3ec6SMatthias Ringwald             }
45263deb3ec6SMatthias Ringwald             break;
4527c18be159SMatthias Ringwald 
4528c18be159SMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
4529c18be159SMatthias Ringwald         case SM_BR_EDR_INITIATOR_W4_PAIRING_RESPONSE:
4530c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_RESPONSE){
4531c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4532c18be159SMatthias Ringwald                 break;
4533c18be159SMatthias Ringwald             }
4534c18be159SMatthias Ringwald             // store pairing response
4535c18be159SMatthias Ringwald             (void)memcpy(&setup->sm_s_pres, packet, sizeof(sm_pairing_packet_t));
4536c18be159SMatthias Ringwald 
4537c18be159SMatthias Ringwald             // validate encryption key size
4538c18be159SMatthias 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));
4539c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4540c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4541c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4542c18be159SMatthias Ringwald             }
4543c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4544c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4545c18be159SMatthias Ringwald                 break;
4546c18be159SMatthias Ringwald             }
4547c18be159SMatthias Ringwald 
4548c18be159SMatthias Ringwald             // prepare key exchange, LTK is derived locally
4549c18be159SMatthias Ringwald             sm_setup_key_distribution(sm_pairing_packet_get_initiator_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY,
4550c18be159SMatthias Ringwald                                       sm_pairing_packet_get_responder_key_distribution(setup->sm_s_pres) & ~SM_KEYDIST_ENC_KEY);
4551c18be159SMatthias Ringwald 
4552c18be159SMatthias Ringwald             // skip receive if there are none
455361d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4554c18be159SMatthias Ringwald                 // distribute keys in run handles 'no keys to send'
4555c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4556c18be159SMatthias Ringwald             } else {
4557c18be159SMatthias Ringwald                 sm_conn->sm_engine_state = SM_BR_EDR_RECEIVE_KEYS;
4558c18be159SMatthias Ringwald             }
4559c18be159SMatthias Ringwald             break;
4560c18be159SMatthias Ringwald 
4561c18be159SMatthias Ringwald         case SM_BR_EDR_RESPONDER_W4_PAIRING_REQUEST:
4562c18be159SMatthias Ringwald             if (sm_pdu_code != SM_CODE_PAIRING_REQUEST){
4563c18be159SMatthias Ringwald                 sm_pdu_received_in_wrong_state(sm_conn);
4564c18be159SMatthias Ringwald                 break;
4565c18be159SMatthias Ringwald             }
4566c18be159SMatthias Ringwald             // store pairing request
4567c18be159SMatthias Ringwald             (void)memcpy(&sm_conn->sm_m_preq, packet, sizeof(sm_pairing_packet_t));
4568c18be159SMatthias Ringwald             // validate encryption key size
4569c18be159SMatthias 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));
4570c18be159SMatthias Ringwald             // SC Only mandates 128 bit key size
4571c18be159SMatthias Ringwald             if (sm_sc_only_mode && (sm_conn->sm_actual_encryption_key_size < 16)) {
4572c18be159SMatthias Ringwald                 sm_conn->sm_actual_encryption_key_size  = 0;
4573c18be159SMatthias Ringwald             }
4574c18be159SMatthias Ringwald             if (sm_conn->sm_actual_encryption_key_size == 0){
4575c18be159SMatthias Ringwald                 sm_pairing_error(sm_conn, SM_REASON_ENCRYPTION_KEY_SIZE);
4576c18be159SMatthias Ringwald                 break;
4577c18be159SMatthias Ringwald             }
4578c18be159SMatthias Ringwald             // trigger response
4579c18be159SMatthias Ringwald             sm_conn->sm_engine_state = SM_BR_EDR_RESPONDER_PAIRING_REQUEST_RECEIVED;
4580c18be159SMatthias Ringwald             break;
4581c18be159SMatthias Ringwald 
4582c18be159SMatthias Ringwald         case SM_BR_EDR_RECEIVE_KEYS:
4583c18be159SMatthias Ringwald             switch(sm_pdu_code){
4584c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_INFORMATION:
4585c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_INFORMATION;
4586c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_irk);
4587c18be159SMatthias Ringwald                     break;
4588c18be159SMatthias Ringwald                 case SM_CODE_IDENTITY_ADDRESS_INFORMATION:
4589c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_IDENTITY_ADDRESS_INFORMATION;
4590c18be159SMatthias Ringwald                     setup->sm_peer_addr_type = packet[1];
4591c18be159SMatthias Ringwald                     reverse_bd_addr(&packet[2], setup->sm_peer_address);
4592c18be159SMatthias Ringwald                     break;
4593c18be159SMatthias Ringwald                 case SM_CODE_SIGNING_INFORMATION:
4594c18be159SMatthias Ringwald                     setup->sm_key_distribution_received_set |= SM_KEYDIST_FLAG_SIGNING_IDENTIFICATION;
4595c18be159SMatthias Ringwald                     reverse_128(&packet[1], setup->sm_peer_csrk);
4596c18be159SMatthias Ringwald                     break;
4597c18be159SMatthias Ringwald                 default:
4598c18be159SMatthias Ringwald                     // Unexpected PDU
4599c18be159SMatthias Ringwald                     log_info("Unexpected PDU %u in SM_PH3_RECEIVE_KEYS", packet[0]);
4600c18be159SMatthias Ringwald                     break;
4601c18be159SMatthias Ringwald             }
4602c18be159SMatthias Ringwald 
4603c18be159SMatthias Ringwald             // all keys received
460461d1a45eSMatthias Ringwald             if (sm_key_distribution_all_received()){
4605c18be159SMatthias Ringwald                 if (IS_RESPONDER(sm_conn->sm_role)){
4606c18be159SMatthias Ringwald                     // responder -> keys exchanged, derive LE LTK
4607c18be159SMatthias Ringwald                     sm_ctkd_start_from_br_edr(sm_conn);
4608c18be159SMatthias Ringwald                 } else {
4609c18be159SMatthias Ringwald                     // initiator -> send our keys if any
4610c18be159SMatthias Ringwald                     sm_conn->sm_engine_state = SM_BR_EDR_DISTRIBUTE_KEYS;
4611c18be159SMatthias Ringwald                 }
4612c18be159SMatthias Ringwald             }
4613c18be159SMatthias Ringwald             break;
4614c18be159SMatthias Ringwald #endif
4615c18be159SMatthias Ringwald 
46163deb3ec6SMatthias Ringwald         default:
46173deb3ec6SMatthias Ringwald             // Unexpected PDU
46183deb3ec6SMatthias Ringwald             log_info("Unexpected PDU %u in state %u", packet[0], sm_conn->sm_engine_state);
46192d095694SMatthias Ringwald             sm_pdu_received_in_wrong_state(sm_conn);
46203deb3ec6SMatthias Ringwald             break;
46213deb3ec6SMatthias Ringwald     }
46223deb3ec6SMatthias Ringwald 
462370b44dd4SMatthias Ringwald     // try to send next pdu
462470b44dd4SMatthias Ringwald     sm_trigger_run();
46253deb3ec6SMatthias Ringwald }
46263deb3ec6SMatthias Ringwald 
46273deb3ec6SMatthias Ringwald // Security Manager Client API
4628a680ba6bSMatthias Ringwald void sm_register_oob_data_callback( int (*get_oob_data_callback)(uint8_t address_type, bd_addr_t addr, uint8_t * oob_data)){
46293deb3ec6SMatthias Ringwald     sm_get_oob_data = get_oob_data_callback;
46303deb3ec6SMatthias Ringwald }
46313deb3ec6SMatthias Ringwald 
46324acf7b7bSMatthias 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)){
4633a680ba6bSMatthias Ringwald     sm_get_sc_oob_data = get_sc_oob_data_callback;
4634a680ba6bSMatthias Ringwald }
4635a680ba6bSMatthias Ringwald 
463689a78d34SMatthias Ringwald void sm_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
463789a78d34SMatthias Ringwald     btstack_linked_list_add_tail(&sm_event_handlers, (btstack_linked_item_t*) callback_handler);
463889a78d34SMatthias Ringwald }
463989a78d34SMatthias Ringwald 
46403deb3ec6SMatthias Ringwald void sm_set_accepted_stk_generation_methods(uint8_t accepted_stk_generation_methods){
46413deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = accepted_stk_generation_methods;
46423deb3ec6SMatthias Ringwald }
46433deb3ec6SMatthias Ringwald 
46443deb3ec6SMatthias Ringwald void sm_set_encryption_key_size_range(uint8_t min_size, uint8_t max_size){
46453deb3ec6SMatthias Ringwald 	sm_min_encryption_key_size = min_size;
46463deb3ec6SMatthias Ringwald 	sm_max_encryption_key_size = max_size;
46473deb3ec6SMatthias Ringwald }
46483deb3ec6SMatthias Ringwald 
46493deb3ec6SMatthias Ringwald void sm_set_authentication_requirements(uint8_t auth_req){
465098d95509SMatthias Ringwald #ifndef ENABLE_LE_SECURE_CONNECTIONS
465198d95509SMatthias Ringwald     if (auth_req & SM_AUTHREQ_SECURE_CONNECTION){
465298d95509SMatthias Ringwald         log_error("ENABLE_LE_SECURE_CONNECTIONS not defined, but requested by app. Dropping SC flag");
465398d95509SMatthias Ringwald         auth_req &= ~SM_AUTHREQ_SECURE_CONNECTION;
465498d95509SMatthias Ringwald     }
465598d95509SMatthias Ringwald #endif
46563deb3ec6SMatthias Ringwald     sm_auth_req = auth_req;
46573deb3ec6SMatthias Ringwald }
46583deb3ec6SMatthias Ringwald 
46593deb3ec6SMatthias Ringwald void sm_set_io_capabilities(io_capability_t io_capability){
46603deb3ec6SMatthias Ringwald     sm_io_capabilities = io_capability;
46613deb3ec6SMatthias Ringwald }
46623deb3ec6SMatthias Ringwald 
466342134bc6SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
46643deb3ec6SMatthias Ringwald void sm_set_request_security(int enable){
46653deb3ec6SMatthias Ringwald     sm_slave_request_security = enable;
46663deb3ec6SMatthias Ringwald }
466742134bc6SMatthias Ringwald #endif
46683deb3ec6SMatthias Ringwald 
46693deb3ec6SMatthias Ringwald void sm_set_er(sm_key_t er){
46706535961aSMatthias Ringwald     (void)memcpy(sm_persistent_er, er, 16);
46713deb3ec6SMatthias Ringwald }
46723deb3ec6SMatthias Ringwald 
46733deb3ec6SMatthias Ringwald void sm_set_ir(sm_key_t ir){
46746535961aSMatthias Ringwald     (void)memcpy(sm_persistent_ir, ir, 16);
46753deb3ec6SMatthias Ringwald }
46763deb3ec6SMatthias Ringwald 
46773deb3ec6SMatthias Ringwald // Testing support only
46783deb3ec6SMatthias Ringwald void sm_test_set_irk(sm_key_t irk){
46796535961aSMatthias Ringwald     (void)memcpy(sm_persistent_irk, irk, 16);
4680103fa6b0SMatthias Ringwald     dkg_state = DKG_CALC_DHK;
4681841468bbSMatthias Ringwald     test_use_fixed_local_irk = true;
46823deb3ec6SMatthias Ringwald }
46833deb3ec6SMatthias Ringwald 
46843deb3ec6SMatthias Ringwald void sm_test_use_fixed_local_csrk(void){
4685841468bbSMatthias Ringwald     test_use_fixed_local_csrk = true;
46863deb3ec6SMatthias Ringwald }
46873deb3ec6SMatthias Ringwald 
4688d1a1f6a4SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4689d1a1f6a4SMatthias Ringwald static void sm_ec_generated(void * arg){
4690d1a1f6a4SMatthias Ringwald     UNUSED(arg);
4691d1a1f6a4SMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_DONE;
469234b6528fSMatthias Ringwald     // trigger pairing if pending for ec key
469370b44dd4SMatthias Ringwald     sm_trigger_run();
4694d1a1f6a4SMatthias Ringwald }
4695674e5b4aSMatthias Ringwald static void sm_ec_generate_new_key(void){
469634b6528fSMatthias Ringwald     log_info("sm: generate new ec key");
4697674e5b4aSMatthias Ringwald     ec_key_generation_state = EC_KEY_GENERATION_ACTIVE;
4698674e5b4aSMatthias Ringwald     btstack_crypto_ecc_p256_generate_key(&sm_crypto_ecc_p256_request, ec_q, &sm_ec_generated, NULL);
4699674e5b4aSMatthias Ringwald }
4700d1a1f6a4SMatthias Ringwald #endif
4701d1a1f6a4SMatthias Ringwald 
4702192365feSMatthias Ringwald #ifdef ENABLE_TESTING_SUPPORT
4703192365feSMatthias Ringwald void sm_test_set_pairing_failure(int reason){
4704192365feSMatthias Ringwald     test_pairing_failure = reason;
4705192365feSMatthias Ringwald }
4706192365feSMatthias Ringwald #endif
4707192365feSMatthias Ringwald 
47083deb3ec6SMatthias Ringwald void sm_init(void){
47092d2d4d3cSMatthias Ringwald 
47102d2d4d3cSMatthias Ringwald     if (sm_initialized) return;
47112d2d4d3cSMatthias Ringwald 
4712899e6e02SMatthias Ringwald     // set default ER and IR values (should be unique - set by app or sm later using TLV)
4713899e6e02SMatthias Ringwald     sm_er_ir_set_default();
4714899e6e02SMatthias Ringwald 
47153deb3ec6SMatthias Ringwald     // defaults
47163deb3ec6SMatthias Ringwald     sm_accepted_stk_generation_methods = SM_STK_GENERATION_METHOD_JUST_WORKS
47173deb3ec6SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_OOB
4718b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_PASSKEY
4719b4343428SMatthias Ringwald                                        | SM_STK_GENERATION_METHOD_NUMERIC_COMPARISON;
4720b4343428SMatthias Ringwald 
47213deb3ec6SMatthias Ringwald     sm_max_encryption_key_size = 16;
47223deb3ec6SMatthias Ringwald     sm_min_encryption_key_size = 7;
47233deb3ec6SMatthias Ringwald 
47245ce1359eSMatthias Ringwald     sm_fixed_passkey_in_display_role = 0xffffffffU;
47251979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = true;
4726caf15bf3SMatthias Ringwald 
4727d1a1f6a4SMatthias Ringwald #ifdef USE_CMAC_ENGINE
4728d1a1f6a4SMatthias Ringwald     sm_cmac_active  = 0;
47297a766ebfSMatthias Ringwald #endif
47308d9b6072SMatthias Ringwald     dkg_state = DKG_W4_WORKING;
4731fbd4e238SMatthias Ringwald     rau_state = RAU_IDLE;
47323deb3ec6SMatthias Ringwald     sm_aes128_state = SM_AES128_IDLE;
47333deb3ec6SMatthias Ringwald     sm_address_resolution_test = -1;    // no private address to resolve yet
47343deb3ec6SMatthias Ringwald     sm_address_resolution_ah_calculation_active = 0;
47353deb3ec6SMatthias Ringwald     sm_address_resolution_mode = ADDRESS_RESOLUTION_IDLE;
47363deb3ec6SMatthias Ringwald     sm_address_resolution_general_queue = NULL;
47373deb3ec6SMatthias Ringwald 
47383deb3ec6SMatthias Ringwald     gap_random_adress_update_period = 15 * 60 * 1000L;
47397149bde5SMatthias Ringwald     sm_active_connection_handle = HCI_CON_HANDLE_INVALID;
47403deb3ec6SMatthias Ringwald 
4741841468bbSMatthias Ringwald     test_use_fixed_local_csrk = false;
47423deb3ec6SMatthias Ringwald 
474384c0c5c7SMatthias Ringwald     btstack_run_loop_set_timer_handler(&sm_run_timer, &sm_run_timer_handler);
474484c0c5c7SMatthias Ringwald 
4745e03e489aSMatthias Ringwald     // register for HCI Events from HCI
4746e03e489aSMatthias Ringwald     hci_event_callback_registration.callback = &sm_event_packet_handler;
4747e03e489aSMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
4748e03e489aSMatthias Ringwald 
4749d1a1f6a4SMatthias Ringwald     //
4750d1a1f6a4SMatthias Ringwald     btstack_crypto_init();
4751d1a1f6a4SMatthias Ringwald 
475251bd74d1SMatthias Ringwald     // init le_device_db
475351bd74d1SMatthias Ringwald     le_device_db_init();
475451bd74d1SMatthias Ringwald 
4755b170b20fSMatthias Ringwald     // and L2CAP PDUs + L2CAP_EVENT_CAN_SEND_NOW
4756e03e489aSMatthias Ringwald     l2cap_register_fixed_channel(sm_pdu_handler, L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
475727c32905SMatthias Ringwald 
475809e4d397SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4759674e5b4aSMatthias Ringwald     sm_ec_generate_new_key();
4760a3aba2f9SMatthias Ringwald #endif
47612d2d4d3cSMatthias Ringwald 
47622d2d4d3cSMatthias Ringwald     sm_initialized = true;
47633deb3ec6SMatthias Ringwald }
47643deb3ec6SMatthias Ringwald 
476515537ea4SMatthias Ringwald void sm_deinit(void){
476615537ea4SMatthias Ringwald     sm_initialized = false;
476715537ea4SMatthias Ringwald     btstack_run_loop_remove_timer(&sm_run_timer);
476815537ea4SMatthias Ringwald }
476915537ea4SMatthias Ringwald 
47704b8c611fSMatthias Ringwald void sm_use_fixed_passkey_in_display_role(uint32_t passkey){
47714b8c611fSMatthias Ringwald     sm_fixed_passkey_in_display_role = passkey;
4772caf15bf3SMatthias Ringwald }
4773caf15bf3SMatthias Ringwald 
47746c39055aSMatthias Ringwald void sm_allow_ltk_reconstruction_without_le_device_db_entry(int allow){
47751979f09cSMatthias Ringwald     sm_reconstruct_ltk_without_le_device_db_entry = allow != 0;
47766c39055aSMatthias Ringwald }
47776c39055aSMatthias Ringwald 
4778711e6c80SMatthias Ringwald static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4779711e6c80SMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
47803deb3ec6SMatthias Ringwald     if (!hci_con) return NULL;
47813deb3ec6SMatthias Ringwald     return &hci_con->sm_connection;
47823deb3ec6SMatthias Ringwald }
47833deb3ec6SMatthias Ringwald 
478477e2e5edSMatthias Ringwald #ifdef ENABLE_CROSS_TRANSPORT_KEY_DERIVATION
478577e2e5edSMatthias Ringwald static sm_connection_t * sm_get_connection_for_bd_addr_and_type(bd_addr_t address, bd_addr_type_t addr_type){
478677e2e5edSMatthias Ringwald     hci_connection_t * hci_con = hci_connection_for_bd_addr_and_type(address, addr_type);
478777e2e5edSMatthias Ringwald     if (!hci_con) return NULL;
478877e2e5edSMatthias Ringwald     return &hci_con->sm_connection;
478977e2e5edSMatthias Ringwald }
479077e2e5edSMatthias Ringwald #endif
479177e2e5edSMatthias Ringwald 
47926bc3aba4SMatthias Ringwald // @deprecated: map onto sm_request_pairing
4793711e6c80SMatthias Ringwald void sm_send_security_request(hci_con_handle_t con_handle){
4794711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
47953deb3ec6SMatthias Ringwald     if (!sm_conn) return;
47966bc3aba4SMatthias Ringwald     if (!IS_RESPONDER(sm_conn->sm_role)) return;
47976bc3aba4SMatthias Ringwald     sm_request_pairing(con_handle);
47983deb3ec6SMatthias Ringwald }
47993deb3ec6SMatthias Ringwald 
48003deb3ec6SMatthias Ringwald // request pairing
4801711e6c80SMatthias Ringwald void sm_request_pairing(hci_con_handle_t con_handle){
4802711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48033deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48043deb3ec6SMatthias Ringwald 
48057af5dcd5SMatthias Ringwald     bool have_ltk;
48067af5dcd5SMatthias Ringwald     uint8_t ltk[16];
48073deb3ec6SMatthias Ringwald     log_info("sm_request_pairing in role %u, state %u", sm_conn->sm_role, sm_conn->sm_engine_state);
480842134bc6SMatthias Ringwald     if (IS_RESPONDER(sm_conn->sm_role)){
480924c20dc4SMatthias Ringwald         switch (sm_conn->sm_engine_state){
481024c20dc4SMatthias Ringwald             case SM_GENERAL_IDLE:
481124c20dc4SMatthias Ringwald             case SM_RESPONDER_IDLE:
48127af5dcd5SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48137af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48147af5dcd5SMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
48157af5dcd5SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
48167af5dcd5SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
48177af5dcd5SMatthias Ringwald                         if (have_ltk){
48187af5dcd5SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
481924c20dc4SMatthias Ringwald                             sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48207af5dcd5SMatthias Ringwald                             sm_reencryption_started(sm_conn);
48217af5dcd5SMatthias Ringwald                             break;
48227af5dcd5SMatthias Ringwald                         }
48237af5dcd5SMatthias Ringwald                         /* fall through */
48247af5dcd5SMatthias Ringwald 
48257af5dcd5SMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48267af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48277af5dcd5SMatthias Ringwald                         sm_conn->sm_engine_state = SM_RESPONDER_SEND_SECURITY_REQUEST;
48287af5dcd5SMatthias Ringwald                         sm_pairing_started(sm_conn);
48297af5dcd5SMatthias Ringwald                         break;
48307af5dcd5SMatthias Ringwald                     default:
48317af5dcd5SMatthias Ringwald                         log_info("irk lookup pending");
48327af5dcd5SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48337af5dcd5SMatthias Ringwald                         break;
48347af5dcd5SMatthias Ringwald                 }
483524c20dc4SMatthias Ringwald                 break;
483624c20dc4SMatthias Ringwald             default:
483724c20dc4SMatthias Ringwald                 break;
483824c20dc4SMatthias Ringwald         }
48393deb3ec6SMatthias Ringwald     } else {
48403deb3ec6SMatthias Ringwald         // used as a trigger to start central/master/initiator security procedures
4841175b7faaSMatthias Ringwald         switch (sm_conn->sm_engine_state){
4842175b7faaSMatthias Ringwald             case SM_INITIATOR_CONNECTED:
48433deb3ec6SMatthias Ringwald                 switch (sm_conn->sm_irk_lookup_state){
48443deb3ec6SMatthias Ringwald                     case IRK_LOOKUP_SUCCEEDED:
48453dc3a67dSMatthias Ringwald                         le_device_db_encryption_get(sm_conn->sm_le_db_index, NULL, NULL, ltk, NULL, NULL, NULL, NULL);
4846f53ec649SMatthias Ringwald                         have_ltk = !sm_is_null_key(ltk);
4847f53ec649SMatthias Ringwald                         log_info("have ltk %u", have_ltk);
4848f53ec649SMatthias Ringwald                         if (have_ltk){
4849c245ca32SMatthias Ringwald                             sm_conn->sm_pairing_requested = 1;
48505567aa60SMatthias Ringwald                             sm_conn->sm_engine_state = SM_INITIATOR_PH4_HAS_LTK;
4851c245ca32SMatthias Ringwald                             break;
4852f53ec649SMatthias Ringwald                         }
4853cf373d3aSMatthias Ringwald                         /* fall through */
4854c245ca32SMatthias Ringwald 
485534c39fbdSMatthias Ringwald                     case IRK_LOOKUP_FAILED:
48563deb3ec6SMatthias Ringwald                         sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
48573deb3ec6SMatthias Ringwald                         break;
48583deb3ec6SMatthias Ringwald                     default:
4859d1a1f6a4SMatthias Ringwald                         log_info("irk lookup pending");
486009ea1b62SMatthias Ringwald                         sm_conn->sm_pairing_requested = 1;
48613deb3ec6SMatthias Ringwald                         break;
48623deb3ec6SMatthias Ringwald                 }
4863175b7faaSMatthias Ringwald                 break;
4864cb6d7eb0SMatthias Ringwald             case SM_GENERAL_REENCRYPTION_FAILED:
4865cb6d7eb0SMatthias Ringwald                 sm_conn->sm_engine_state = SM_INITIATOR_PH1_W2_SEND_PAIRING_REQUEST;
4866cb6d7eb0SMatthias Ringwald                 break;
4867175b7faaSMatthias Ringwald             case SM_GENERAL_IDLE:
486809ea1b62SMatthias Ringwald                 sm_conn->sm_pairing_requested = 1;
4869175b7faaSMatthias Ringwald                 break;
4870175b7faaSMatthias Ringwald             default:
4871175b7faaSMatthias Ringwald                 break;
48723deb3ec6SMatthias Ringwald         }
48733deb3ec6SMatthias Ringwald     }
487470b44dd4SMatthias Ringwald     sm_trigger_run();
48753deb3ec6SMatthias Ringwald }
48763deb3ec6SMatthias Ringwald 
48773deb3ec6SMatthias Ringwald // called by client app on authorization request
4878711e6c80SMatthias Ringwald void sm_authorization_decline(hci_con_handle_t con_handle){
4879711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48803deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48813deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_DECLINED;
4882589f5a99SMatthias 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);
48833deb3ec6SMatthias Ringwald }
48843deb3ec6SMatthias Ringwald 
4885711e6c80SMatthias Ringwald void sm_authorization_grant(hci_con_handle_t con_handle){
4886711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48873deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48883deb3ec6SMatthias Ringwald     sm_conn->sm_connection_authorization_state = AUTHORIZATION_GRANTED;
4889589f5a99SMatthias 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);
48903deb3ec6SMatthias Ringwald }
48913deb3ec6SMatthias Ringwald 
48923deb3ec6SMatthias Ringwald // GAP Bonding API
48933deb3ec6SMatthias Ringwald 
4894711e6c80SMatthias Ringwald void sm_bonding_decline(hci_con_handle_t con_handle){
4895711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
48963deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
48973deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_DECLINE;
48980af429c6SMatthias Ringwald     log_info("decline, state %u", sm_conn->sm_engine_state);
48990af429c6SMatthias Ringwald     switch(sm_conn->sm_engine_state){
49000af429c6SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49010af429c6SMatthias Ringwald         case SM_SC_W4_USER_RESPONSE:
49020af429c6SMatthias Ringwald         case SM_SC_W4_CONFIRMATION:
49030af429c6SMatthias Ringwald         case SM_SC_W4_PUBLIC_KEY_COMMAND:
49040af429c6SMatthias Ringwald #endif
49050af429c6SMatthias Ringwald         case SM_PH1_W4_USER_RESPONSE:
4906de2fd182SMatthias Ringwald             switch (setup->sm_stk_generation_method){
4907de2fd182SMatthias Ringwald                 case PK_RESP_INPUT:
4908de2fd182SMatthias Ringwald                 case PK_INIT_INPUT:
490947fb4255SMatthias Ringwald                 case PK_BOTH_INPUT:
49100af429c6SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_PASSKEY_ENTRY_FAILED);
4911de2fd182SMatthias Ringwald                     break;
491247fb4255SMatthias Ringwald                 case NUMERIC_COMPARISON:
4913de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_NUMERIC_COMPARISON_FAILED);
4914de2fd182SMatthias Ringwald                     break;
4915de2fd182SMatthias Ringwald                 case JUST_WORKS:
4916de2fd182SMatthias Ringwald                 case OOB:
4917de2fd182SMatthias Ringwald                     sm_pairing_error(sm_conn, SM_REASON_UNSPECIFIED_REASON);
4918de2fd182SMatthias Ringwald                     break;
49197bbeb3adSMilanka Ringwald                 default:
49207bbeb3adSMilanka Ringwald                     btstack_assert(false);
49217bbeb3adSMilanka Ringwald                     break;
4922de2fd182SMatthias Ringwald             }
49230af429c6SMatthias Ringwald             break;
49240af429c6SMatthias Ringwald         default:
49250af429c6SMatthias Ringwald             break;
49263deb3ec6SMatthias Ringwald     }
492770b44dd4SMatthias Ringwald     sm_trigger_run();
49283deb3ec6SMatthias Ringwald }
49293deb3ec6SMatthias Ringwald 
4930711e6c80SMatthias Ringwald void sm_just_works_confirm(hci_con_handle_t con_handle){
4931711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49323deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49333deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_CONFIRM;
49343deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4935136d331aSMatthias Ringwald         if (setup->sm_use_secure_connections){
4936c6b7cbd9SMatthias Ringwald             sm_conn->sm_engine_state = SM_SC_SEND_PUBLIC_KEY_COMMAND;
4937bbf8db22SMatthias Ringwald         } else {
4938f3582630SMatthias 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);
4939136d331aSMatthias Ringwald         }
49403deb3ec6SMatthias Ringwald     }
49410346c37cSMatthias Ringwald 
49420346c37cSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
4943c6b7cbd9SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
4944dc300847SMatthias Ringwald         sm_sc_prepare_dhkey_check(sm_conn);
4945446a8c36SMatthias Ringwald     }
49460346c37cSMatthias Ringwald #endif
49470346c37cSMatthias Ringwald 
494870b44dd4SMatthias Ringwald     sm_trigger_run();
49493deb3ec6SMatthias Ringwald }
49503deb3ec6SMatthias Ringwald 
4951c8c46d51SMatthias Ringwald void sm_numeric_comparison_confirm(hci_con_handle_t con_handle){
4952c8c46d51SMatthias Ringwald     // for now, it's the same
4953c8c46d51SMatthias Ringwald     sm_just_works_confirm(con_handle);
4954c8c46d51SMatthias Ringwald }
4955c8c46d51SMatthias Ringwald 
4956711e6c80SMatthias Ringwald void sm_passkey_input(hci_con_handle_t con_handle, uint32_t passkey){
4957711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49583deb3ec6SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49593deb3ec6SMatthias Ringwald     sm_reset_tk();
4960f8fbdce0SMatthias Ringwald     big_endian_store_32(setup->sm_tk, 12, passkey);
49613deb3ec6SMatthias Ringwald     setup->sm_user_response = SM_USER_RESPONSE_PASSKEY;
49623deb3ec6SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_PH1_W4_USER_RESPONSE){
4963f3582630SMatthias 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);
49643deb3ec6SMatthias Ringwald     }
49651c516d8fSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
49666535961aSMatthias Ringwald     (void)memcpy(setup->sm_ra, setup->sm_tk, 16);
49676535961aSMatthias Ringwald     (void)memcpy(setup->sm_rb, setup->sm_tk, 16);
496807036a04SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_SC_W4_USER_RESPONSE){
496907036a04SMatthias Ringwald         sm_sc_start_calculating_local_confirm(sm_conn);
497007036a04SMatthias Ringwald     }
49711c516d8fSMatthias Ringwald #endif
497270b44dd4SMatthias Ringwald     sm_trigger_run();
49733deb3ec6SMatthias Ringwald }
49743deb3ec6SMatthias Ringwald 
49753d7fe1e9SMatthias Ringwald void sm_keypress_notification(hci_con_handle_t con_handle, uint8_t action){
49763d7fe1e9SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
49773d7fe1e9SMatthias Ringwald     if (!sm_conn) return;     // wrong connection
49783d7fe1e9SMatthias Ringwald     if (action > SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED) return;
4979dd4a08fbSMatthias Ringwald     uint8_t num_actions = setup->sm_keypress_notification >> 5;
49804ea43905SMatthias Ringwald     uint8_t flags = setup->sm_keypress_notification & 0x1fu;
4981dd4a08fbSMatthias Ringwald     switch (action){
4982dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_STARTED:
4983dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_ENTRY_COMPLETED:
49844ea43905SMatthias Ringwald             flags |= (1u << action);
4985dd4a08fbSMatthias Ringwald             break;
4986dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_CLEARED:
4987dd4a08fbSMatthias Ringwald             // clear counter, keypress & erased flags + set passkey cleared
49884ea43905SMatthias Ringwald             flags = (flags & 0x19u) | (1u << SM_KEYPRESS_PASSKEY_CLEARED);
4989dd4a08fbSMatthias Ringwald             break;
4990dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ENTERED:
49914ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED)){
4992dd4a08fbSMatthias Ringwald                 // erase actions queued
4993dd4a08fbSMatthias Ringwald                 num_actions--;
49944ea43905SMatthias Ringwald                 if (num_actions == 0u){
4995dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
49964ea43905SMatthias Ringwald                     flags &= 0x19u;
4997dd4a08fbSMatthias Ringwald                 }
4998dd4a08fbSMatthias Ringwald                 break;
4999dd4a08fbSMatthias Ringwald             }
5000dd4a08fbSMatthias Ringwald             num_actions++;
50014ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED);
5002dd4a08fbSMatthias Ringwald             break;
5003dd4a08fbSMatthias Ringwald         case SM_KEYPRESS_PASSKEY_DIGIT_ERASED:
50044ea43905SMatthias Ringwald             if (flags & (1u << SM_KEYPRESS_PASSKEY_DIGIT_ENTERED)){
5005dd4a08fbSMatthias Ringwald                 // enter actions queued
5006dd4a08fbSMatthias Ringwald                 num_actions--;
50074ea43905SMatthias Ringwald                 if (num_actions == 0u){
5008dd4a08fbSMatthias Ringwald                     // clear counter, keypress & erased flags
50094ea43905SMatthias Ringwald                     flags &= 0x19u;
5010dd4a08fbSMatthias Ringwald                 }
5011dd4a08fbSMatthias Ringwald                 break;
5012dd4a08fbSMatthias Ringwald             }
5013dd4a08fbSMatthias Ringwald             num_actions++;
50144ea43905SMatthias Ringwald             flags |= (1u << SM_KEYPRESS_PASSKEY_DIGIT_ERASED);
5015dd4a08fbSMatthias Ringwald             break;
5016dd4a08fbSMatthias Ringwald         default:
5017dd4a08fbSMatthias Ringwald             break;
5018dd4a08fbSMatthias Ringwald     }
5019dd4a08fbSMatthias Ringwald     setup->sm_keypress_notification = (num_actions << 5) | flags;
502070b44dd4SMatthias Ringwald     sm_trigger_run();
50213d7fe1e9SMatthias Ringwald }
50223d7fe1e9SMatthias Ringwald 
5023c59d0c92SMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
5024d1a1f6a4SMatthias Ringwald static void sm_handle_random_result_oob(void * arg){
5025d1a1f6a4SMatthias Ringwald     UNUSED(arg);
5026d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W2_CALC_CONFIRM;
502770b44dd4SMatthias Ringwald     sm_trigger_run();
5028d1a1f6a4SMatthias Ringwald }
5029c59d0c92SMatthias Ringwald uint8_t sm_generate_sc_oob_data(void (*callback)(const uint8_t * confirm_value, const uint8_t * random_value)){
50308334d3d8SMatthias Ringwald 
50318334d3d8SMatthias Ringwald     static btstack_crypto_random_t   sm_crypto_random_oob_request;
50328334d3d8SMatthias Ringwald 
5033c59d0c92SMatthias Ringwald     if (sm_sc_oob_state != SM_SC_OOB_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
5034c59d0c92SMatthias Ringwald     sm_sc_oob_callback = callback;
5035d1a1f6a4SMatthias Ringwald     sm_sc_oob_state = SM_SC_OOB_W4_RANDOM;
5036d1a1f6a4SMatthias Ringwald     btstack_crypto_random_generate(&sm_crypto_random_oob_request, sm_sc_oob_random, 16, &sm_handle_random_result_oob, NULL);
5037c59d0c92SMatthias Ringwald     return 0;
5038c59d0c92SMatthias Ringwald }
5039c59d0c92SMatthias Ringwald #endif
5040c59d0c92SMatthias Ringwald 
50413deb3ec6SMatthias Ringwald /**
5042ba394633SMatthias Ringwald  * @brief Get Identity Resolving state
5043ba394633SMatthias Ringwald  * @param con_handle
5044ba394633SMatthias Ringwald  * @return irk_lookup_state_t
5045ba394633SMatthias Ringwald  */
5046ba394633SMatthias Ringwald irk_lookup_state_t sm_identity_resolving_state(hci_con_handle_t con_handle){
5047ba394633SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5048ba394633SMatthias Ringwald     if (!sm_conn) return IRK_LOOKUP_IDLE;
5049ba394633SMatthias Ringwald     return sm_conn->sm_irk_lookup_state;
5050ba394633SMatthias Ringwald }
5051ba394633SMatthias Ringwald 
5052ba394633SMatthias Ringwald /**
50533deb3ec6SMatthias Ringwald  * @brief Identify device in LE Device DB
50543deb3ec6SMatthias Ringwald  * @param handle
50553deb3ec6SMatthias Ringwald  * @returns index from le_device_db or -1 if not found/identified
50563deb3ec6SMatthias Ringwald  */
5057711e6c80SMatthias Ringwald int sm_le_device_index(hci_con_handle_t con_handle ){
5058711e6c80SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
50593deb3ec6SMatthias Ringwald     if (!sm_conn) return -1;
50603deb3ec6SMatthias Ringwald     return sm_conn->sm_le_db_index;
50613deb3ec6SMatthias Ringwald }
50623deb3ec6SMatthias Ringwald 
50638f57b085SMatthias Ringwald static int gap_random_address_type_requires_updates(void){
506447ba4de1SMatthias Ringwald     switch (gap_random_adress_type){
506547ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
506647ba4de1SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_STATIC:
506747ba4de1SMatthias Ringwald             return 0;
506847ba4de1SMatthias Ringwald         default:
50698f57b085SMatthias Ringwald             return 1;
50708f57b085SMatthias Ringwald     }
507147ba4de1SMatthias Ringwald }
5072d70217a2SMatthias Ringwald 
507333373e40SMatthias Ringwald static uint8_t own_address_type(void){
5074b95a5a35SMatthias Ringwald     switch (gap_random_adress_type){
5075b95a5a35SMatthias Ringwald         case GAP_RANDOM_ADDRESS_TYPE_OFF:
5076b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_PUBLIC;
5077b95a5a35SMatthias Ringwald         default:
5078b95a5a35SMatthias Ringwald             return BD_ADDR_TYPE_LE_RANDOM;
5079b95a5a35SMatthias Ringwald     }
508033373e40SMatthias Ringwald }
50818f57b085SMatthias Ringwald 
50823deb3ec6SMatthias Ringwald // GAP LE API
50833deb3ec6SMatthias Ringwald void gap_random_address_set_mode(gap_random_address_type_t random_address_type){
50843deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
50853deb3ec6SMatthias Ringwald     gap_random_adress_type = random_address_type;
5086b95a5a35SMatthias Ringwald     hci_le_set_own_address_type(own_address_type());
50878f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
50883deb3ec6SMatthias Ringwald     gap_random_address_update_start();
50893deb3ec6SMatthias Ringwald     gap_random_address_trigger();
50903deb3ec6SMatthias Ringwald }
50913deb3ec6SMatthias Ringwald 
50923deb3ec6SMatthias Ringwald gap_random_address_type_t gap_random_address_get_mode(void){
50933deb3ec6SMatthias Ringwald     return gap_random_adress_type;
50943deb3ec6SMatthias Ringwald }
50953deb3ec6SMatthias Ringwald 
50963deb3ec6SMatthias Ringwald void gap_random_address_set_update_period(int period_ms){
50973deb3ec6SMatthias Ringwald     gap_random_adress_update_period = period_ms;
50988f57b085SMatthias Ringwald     if (!gap_random_address_type_requires_updates()) return;
50993deb3ec6SMatthias Ringwald     gap_random_address_update_stop();
51003deb3ec6SMatthias Ringwald     gap_random_address_update_start();
51013deb3ec6SMatthias Ringwald }
51023deb3ec6SMatthias Ringwald 
5103667ba9d1SMatthias Ringwald void gap_random_address_set(const bd_addr_t addr){
51048f57b085SMatthias Ringwald     gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_STATIC);
51056535961aSMatthias Ringwald     (void)memcpy(sm_random_address, addr, 6);
5106*e91ddb40SMatthias Ringwald     hci_le_random_address_set(addr);
51077e252622SMatthias Ringwald }
51087e252622SMatthias Ringwald 
5109d70217a2SMatthias Ringwald #ifdef ENABLE_LE_PERIPHERAL
51103deb3ec6SMatthias Ringwald /*
51113deb3ec6SMatthias Ringwald  * @brief Set Advertisement Paramters
51123deb3ec6SMatthias Ringwald  * @param adv_int_min
51133deb3ec6SMatthias Ringwald  * @param adv_int_max
51143deb3ec6SMatthias Ringwald  * @param adv_type
51153deb3ec6SMatthias Ringwald  * @param direct_address_type
51163deb3ec6SMatthias Ringwald  * @param direct_address
51173deb3ec6SMatthias Ringwald  * @param channel_map
51183deb3ec6SMatthias Ringwald  * @param filter_policy
51193deb3ec6SMatthias Ringwald  *
51203deb3ec6SMatthias Ringwald  * @note own_address_type is used from gap_random_address_set_mode
51213deb3ec6SMatthias Ringwald  */
51223deb3ec6SMatthias Ringwald void gap_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
51233deb3ec6SMatthias Ringwald     uint8_t direct_address_typ, bd_addr_t direct_address, uint8_t channel_map, uint8_t filter_policy){
5124b95a5a35SMatthias Ringwald     hci_le_advertisements_set_params(adv_int_min, adv_int_max, adv_type,
51253deb3ec6SMatthias Ringwald         direct_address_typ, direct_address, channel_map, filter_policy);
51263deb3ec6SMatthias Ringwald }
5127d70217a2SMatthias Ringwald #endif
5128dcd6c9b5SMatthias Ringwald 
5129dcd6c9b5SMatthias Ringwald int gap_reconnect_security_setup_active(hci_con_handle_t con_handle){
5130dcd6c9b5SMatthias Ringwald     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5131dcd6c9b5SMatthias Ringwald      // wrong connection
5132dcd6c9b5SMatthias Ringwald     if (!sm_conn) return 0;
5133dcd6c9b5SMatthias Ringwald     // already encrypted
5134dcd6c9b5SMatthias Ringwald     if (sm_conn->sm_connection_encrypted) return 0;
5135dcd6c9b5SMatthias Ringwald     // irk status?
5136dcd6c9b5SMatthias Ringwald     switch(sm_conn->sm_irk_lookup_state){
5137dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_FAILED:
5138dcd6c9b5SMatthias Ringwald             // done, cannot setup encryption
5139dcd6c9b5SMatthias Ringwald             return 0;
5140dcd6c9b5SMatthias Ringwald         case IRK_LOOKUP_SUCCEEDED:
5141dcd6c9b5SMatthias Ringwald             break;
5142dcd6c9b5SMatthias Ringwald         default:
5143dcd6c9b5SMatthias Ringwald             // IR Lookup pending
5144dcd6c9b5SMatthias Ringwald             return 1;
5145dcd6c9b5SMatthias Ringwald     }
5146f0674e22SMatthias Ringwald     // IRK Lookup Succeeded, re-encryption should be initiated. When done, state gets reset or indicates failure
5147f0674e22SMatthias Ringwald     if (sm_conn->sm_engine_state == SM_GENERAL_REENCRYPTION_FAILED) return 0;
5148b15d5ceaSMatthias Ringwald     if (sm_conn->sm_role){
5149b15d5ceaSMatthias Ringwald         return sm_conn->sm_engine_state != SM_RESPONDER_IDLE;
5150b15d5ceaSMatthias Ringwald     } else {
5151dcd6c9b5SMatthias Ringwald         return sm_conn->sm_engine_state != SM_INITIATOR_CONNECTED;
5152dcd6c9b5SMatthias Ringwald     }
5153b15d5ceaSMatthias Ringwald }
51543cdbe9dbSMatthias Ringwald 
51553cdbe9dbSMatthias Ringwald void sm_set_secure_connections_only_mode(bool enable){
51563cdbe9dbSMatthias Ringwald #ifdef ENABLE_LE_SECURE_CONNECTIONS
51573cdbe9dbSMatthias Ringwald     sm_sc_only_mode = enable;
51583cdbe9dbSMatthias Ringwald #else
51593cdbe9dbSMatthias Ringwald     // SC Only mode not possible without support for SC
51603cdbe9dbSMatthias Ringwald     btstack_assert(enable == false);
51613cdbe9dbSMatthias Ringwald #endif
51623cdbe9dbSMatthias Ringwald }
5163052bbdc5SMatthias Ringwald 
5164052bbdc5SMatthias Ringwald const uint8_t * gap_get_persistent_irk(void){
5165052bbdc5SMatthias Ringwald     return sm_persistent_irk;
5166052bbdc5SMatthias Ringwald }
51674f384501SMatthias Ringwald 
51684f384501SMatthias Ringwald void gap_delete_bonding(bd_addr_type_t address_type, bd_addr_t address){
51694f384501SMatthias Ringwald     uint16_t i;
51704f384501SMatthias Ringwald     for (i=0; i < le_device_db_max_count(); i++){
51714f384501SMatthias Ringwald         bd_addr_t entry_address;
51724f384501SMatthias Ringwald         int entry_address_type = BD_ADDR_TYPE_UNKNOWN;
51734f384501SMatthias Ringwald         le_device_db_info(i, &entry_address_type, entry_address, NULL);
51744f384501SMatthias Ringwald         // skip unused entries
51754f384501SMatthias Ringwald         if (entry_address_type == (int) BD_ADDR_TYPE_UNKNOWN) continue;
51764f384501SMatthias Ringwald         if ((entry_address_type == (int) address_type) && (memcmp(entry_address, address, 6) == 0)){
51774f384501SMatthias Ringwald #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION
51784f384501SMatthias Ringwald             hci_remove_le_device_db_entry_from_resolving_list(i);
51794f384501SMatthias Ringwald #endif
51804f384501SMatthias Ringwald             le_device_db_remove(i);
51814f384501SMatthias Ringwald             break;
51824f384501SMatthias Ringwald         }
51834f384501SMatthias Ringwald     }
51844f384501SMatthias Ringwald }
5185